Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

firebase - Flutter FutureBuilder inside StreamBuilder gets rebuild

Title might be a little off topic. I would like to create a profile page which users can see which posts they liked. My Likes structure in Firebase is like this. It has liked post's id and post's DocumentReference. I store the Post's DocumentReference because:

  • Prevent duplicate data.
  • Post's owner can change their name, it would not be affected in the duplicate data.
  • Hard to maintain like count of the Post.

Users should be able to unlike the posts from this page. When they unlike, it should be directly seen in the page (PostTile will be removed from ListView). To create this behaviour I use StreamBuilder as stream value as below:

Stream<QuerySnapshot> likedQuotes(String uid, int limit, Timestamp creationTime) {
  return _likesCollection
      .where('userId', isEqualTo: uid)
      .orderBy('creationTime', descending: true)
      .limit(limit)
      .snapshots();
}

To not load all of the posts I had to limit the snapshot and load new data whenever user scrolls down to near end. Should I increase the limit or add .startAfter([creationTime]) condition to query?

For now, I increase the limit and this causes every PostTile to rebuild. Also when all of the data is loaded, whenever user scrolls the ListView, PostTiles in the ListView get rebuild.

To build the PostTile I use FutureBuilder as future value as below:

class PostTileFromDocument extends StatefulWidget {
  final Stream docRef;
  final String uid;
  PostTileFromDocument({this.uid, this.docRef});

  @override
  _PostTileFromDocumentState createState() => _PostTileFromDocumentState();
}
class _PostTileFromDocumentState extends State<PostTileFromDocument> {

  Future tileFuture;

  @override
  void initState() {
  tileFuture = widget.docRef.get();
  super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: tileFuture,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          currentQuote = PostData.fromSnaphot(snapshot.data);
          return Card(...);
        }
      }
    );
  }
}

Should I change the structure of the data in Firebase? Is my way of building PostTiles are wrong (FutureBuilder inside StreamBuilder)? What is the proper way of doing what I am trying to do?

Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...