如何根据firebase更新flutter UI [英] how to update flutter UI according to firebase

查看:13
本文介绍了如何根据firebase更新flutter UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个帖子列表,用户可以在其中点赞、评论和分享.

I have this list of Post where user can like, comment and share.

Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: _data,
          builder: (_, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (_, index) {
                    return Card(
                      elevation: 4,
                      child: Padding(
                        padding: EdgeInsets.only(left: 10.0, top: 10),
                        child: InkWell(
                          onTap: () => navigateToDetail(
                            snapshot.data[index],
                            snapshot.data[index].data["Userid"],
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              new Row(
                                children: <Widget>[
                                  Container(
                                    width: 45,
                                    height: 45,
                                    decoration: BoxDecoration(
                                      image: DecorationImage(
                                        image: NetworkImage(snapshot
                                            .data[index].data["User Pic"]),
                                        fit: BoxFit.cover,
                                      ),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(50.5)),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 15),
                                    child: Text(
                                      snapshot.data[index].data["Name"],
                                      style: TextStyle(
                                          fontWeight: FontWeight.w600,
                                          fontSize: 18),
                                    ),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 60, bottom: 10),
                                child: Text(
                                  DateFormat.yMMMd().add_jm().format(
                                      DateTime.parse(snapshot
                                          .data[index].data["Creation Time"]
                                          .toDate()
                                          .toString())),
                                  style: TextStyle(
                                      color: Colors.black38, fontSize: 12),
                                ),
                              ),
                              Flexible(
                                child: Padding(
                                  padding: EdgeInsets.only(left: 75, right: 15),
                                  child: Text(
                                    snapshot.data[index].data["Description"],
                                    style: TextStyle(fontSize: 16),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                    left: 75, top: 15, bottom: 8),
                                child: Text(
                                  snapshot.data.length.toString() +
                                      "Files uploaded",
                                  style: TextStyle(
                                      color: Colors.blueAccent,
                                      fontSize: 14,
                                      fontStyle: FontStyle.italic),
                                ),
                              ),
                              Divider(),
                              new Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Row(
                                      children: <Widget>[
                                        IconButton(
                                            onPressed: () {
                                              Firestore.instance.runTransaction((transaction) async{
                                                DocumentSnapshot freshData = await transaction.get(snapshot.data[index].reference);
                                                await transaction.update(freshData.reference, {
                                                  'Likes':freshData['Likes']+1,
                                                });
                                              });

                                            },
                                            icon: Icon(Icons.favorite_border,
                                                color: Colors.redAccent,
                                                size: 23.0),
                                        ),
                                        Text(snapshot.data[index].data["Likes"].toString())
                                      ],
                                    ),
                                  ),
                                  Expanded(
                                    child: IconButton(
                                      onPressed: () {},
                                      icon: Icon(
                                        Icons.chat_bubble_outline,
                                        color: Colors.blue,
                                        size: 23.0,
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: IconButton(
                                      onPressed: () {},
                                      icon: Icon(
                                        Icons.near_me,
                                        color: Colors.blue,
                                        size: 23.0,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  });
            }
          }),
    );
  }

并拥有这样的 Firestore:

and have a Firestore like this :

在帖子收藏中存储喜欢.

storing likes in Post collection.

我需要:

当用户按下喜欢的图标时,它将更新 firestore 并计入 Flutter UI.

when the user press on like icon it will update the firestore as well as count in flutter UI.

到目前为止我做了什么:

what I have done so far:

它只会更新 firestore,而对于 Flutter UI 中的更新,我必须刷新屏幕.

it will only update the firestore and for updation in flutter UI I have to refresh the screen.

谢谢.

更新:

@override
  void initState() {
    super.initState();
    _data = UserManagement().getPosts();
  }

来自用户管理:

getPosts() async {
    QuerySnapshot Qn = await Firestore.instance.collection("Posts").orderBy(
        "Creation Time", descending: true).getDocuments();
    return Qn.documents;
  }

推荐答案

只要将您的 FutureBuilder 替换为 StreamBuilder 即可在您的集合中有更新时获取流

Just replace your FutureBuilder with StreamBuilder to get the stream whenever there is an update in your collection

Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance.collection("Posts").orderBy(
           "Creation Time", descending: true).snapshots(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (_, index) {
                    return Card(
                      elevation: 4,
                      child: Padding(
                        padding: EdgeInsets.only(left: 10.0, top: 10),
                        child: InkWell(
                          onTap: () => navigateToDetail(
                            snapshot.data[index],
                            snapshot.data[index].data["Userid"],
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              new Row(
                                children: <Widget>[
                                  Container(
                                    width: 45,
                                    height: 45,
                                    decoration: BoxDecoration(
                                      image: DecorationImage(
                                        image: NetworkImage(snapshot
                                            .data[index].data["User Pic"]),
                                        fit: BoxFit.cover,
                                      ),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(50.5)),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 15),
                                    child: Text(
                                      snapshot.data[index].data["Name"],
                                      style: TextStyle(
                                          fontWeight: FontWeight.w600,
                                          fontSize: 18),
                                    ),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 60, bottom: 10),
                                child: Text(
                                  DateFormat.yMMMd().add_jm().format(
                                      DateTime.parse(snapshot
                                          .data[index].data["Creation Time"]
                                          .toDate()
                                          .toString())),
                                  style: TextStyle(
                                      color: Colors.black38, fontSize: 12),
                                ),
                              ),
                              Flexible(
                                child: Padding(
                                  padding: EdgeInsets.only(left: 75, right: 15),
                                  child: Text(
                                    snapshot.data[index].data["Description"],
                                    style: TextStyle(fontSize: 16),
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                    left: 75, top: 15, bottom: 8),
                                child: Text(
                                  snapshot.data.length.toString() +
                                      "Files uploaded",
                                  style: TextStyle(
                                      color: Colors.blueAccent,
                                      fontSize: 14,
                                      fontStyle: FontStyle.italic),
                                ),
                              ),
                              Divider(),
                              new Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Row(
                                      children: <Widget>[
                                        IconButton(
                                            onPressed: () {
                                              Firestore.instance.runTransaction((transaction) async{
                                                DocumentSnapshot freshData = await transaction.get(snapshot.data[index].reference);
                                                await transaction.update(freshData.reference, {
                                                  'Likes':freshData['Likes']+1,
                                                });
                                              });

                                            },
                                            icon: Icon(Icons.favorite_border,
                                                color: Colors.redAccent,
                                                size: 23.0),
                                        ),
                                        Text(snapshot.data[index].data["Likes"].toString())
                                      ],
                                    ),
                                  ),
                                  Expanded(
                                    child: IconButton(
                                      onPressed: () {},
                                      icon: Icon(
                                        Icons.chat_bubble_outline,
                                        color: Colors.blue,
                                        size: 23.0,
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: IconButton(
                                      onPressed: () {},
                                      icon: Icon(
                                        Icons.near_me,
                                        color: Colors.blue,
                                        size: 23.0,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  });
            }
          }),
    );
  }

这篇关于如何根据firebase更新flutter UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆