I am building an application in flutter which include a feed of posts, where each post is a card, and each post can be liked by user. The build of the screen depends on future builder that get the collections from posts from Firestore, but something weird is happening : On the first build of the screen, the variable "isliked" (by specific user) of a post is not updated, even all the variables are loaded as it has to be, causing the like icone to be wrong (filled when liked, empty else). After scrolling through the posts, the variable is updated and also the like icon.
The code of the feed :
Widget build(BuildContext context) { return FutureBuilder( future: context.watch<Storage>().getAllPosts(context.read<AuthNotifier>().user!.uid), builder: (context, snapshot) { if (snapshot.hasError) { return Scaffold( body: Center( child: Text(snapshot.error.toString(), textDirection: TextDirection.ltr) ) ); } if (snapshot.connectionState == ConnectionState.done) { return Scaffold( body: Padding( padding: const EdgeInsets.all(8.0), child: ListView.builder( itemCount: snapshot.data?.length, itemBuilder: (BuildContext context, int index) { for (var element in snapshot.data!) { print('hello - ${element.is_liked}'); } return Padding ( padding: const EdgeInsets.all(8.0), child: PostWidget( snapshot: snapshot, index: index, isliked : snapshot.data![index].is_liked) ); }, ), ) ); }
And the post widget:
Widget build(BuildContext context) { print('helllooooo ${widget.isliked}'); print(widget.snapshot.data?[widget.index].is_liked); return Card( elevation: 4, shadowColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), child: Column( children: [ [Some text widgets] Row( children: [ IconButton ( onPressed: () async { if(widget.isliked){ await context.read<Storage>().removeLike(widget.snapshot.data![widget.index].id, context.read<AuthNotifier>().user!.uid); setState(() { widget.isliked = false; widget.snapshot.data![widget.index].likes --; }); } else { await context.read<Storage>().addLike(widget.snapshot.data![widget.index].id, context.read<AuthNotifier>().user!.uid); setState(() { widget.isliked = true; widget.snapshot.data![widget.index].likes ++; }); } }, icon: Icon ( widget.isliked ? Icons.thumb_up : Icons.thumb_up_outlined, color: Colors.blue,)), Text(widget.snapshot.data![widget.index].likes.toString()),
When I try to put the post widget into the feed, the problem disappear, but for all press on like button I have to rebuild the entire feed screen, which is not appreciable by user, and also problematic because the transaction that update the like can take more time than rebuild the screen.