如何根据Firebase更新Flutter UI

问题描述 投票:0回答:1

我有此帖子列表,用户可以在其中喜欢,评论和分享。

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:enter image description here

存储帖子集中的点赞。

我需要:

[当用户按下类似图标时,它将更新Firestore并在Flutter UI中计数。

到目前为止我做了什么:

它只会更新firestore,并且要在浮动UI中进行更新,我必须刷新屏幕。

谢谢。

更新:

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

来自UserManagement:

getPosts() async {
    QuerySnapshot Qn = await Firestore.instance.collection("Posts").orderBy(
        "Creation Time", descending: true).getDocuments();
    return Qn.documents;
  }
database firebase flutter google-cloud-firestore flutter-layout
1个回答
0
投票

我假设您应该使用StreamBuilder而不是FutureBuilder。StreamBuilder就像FutureBuilders一样,它们会根据流而不断更新。

您还应该订阅Firestore集合的流,而不是只获取一次。

代替getPosts可能使用此:

Stream<QuerySnapshot> getPostsStream() {
  return Firestore.instance.collection("Posts").orderBy(
      "Creation Time", descending: true).snapshots();
}

并将您的FutureBuilder更改为StreamBuilder:

StreamBuilder<QuerySnapshot>(
  stream: getPostsStream(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
    } else {
      final List<DocumentSnapshot> documents = snapshot.data.documents;
      // use as documents[index].
      // ....
    }
  },
),
© www.soinside.com 2019 - 2024. All rights reserved.