Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid single frame waiting state when passing already-completed future to a FutureBuilder

I have a list of Future<PostData> that I use to create a preload mechanism for tinder-like swipe feed consumption but I'm running into some issues. In fact, when a card is swiped, I rebuild the card stack using the next Posts that are already loaded in my List<Future<PostData>>.

Thing is, even tho my futures are already completed, I get a single frame of ConnectionState.waiting in my future builder making the UI jitter.

This limitation is documented in the docs:

A side-effect of this is that providing a new but already-completed future to a FutureBuilder will result in a single frame in the ConnectionState.waiting state. This is because there is no way to synchronously determine that a Future has already completed.

I was wondering, is there a way to avoid that problem?

Cheers!

like image 301
Théo Champion Avatar asked Dec 12 '25 02:12

Théo Champion


1 Answers

Not sure you can achieve that with FutureBuilder. Consider creating a class that will handle network, caching etc. Then listen to its changes with a ValueListenableBuilder.

Something like this:

class PostsRetriever{
  //handles loading, caching of posts
}

class PostsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final postsRetriever = Provider.of<PostsRetriever>(context);
    return ValueListenableBuilder<PostData>(
      valueListenable: postsRetriever.currentPost,
      builder: (context, currentPost, _) {
      //some ui that will draw currentPost'
      return RawMaterialButton(onPressed: postsRetriever.loadNext());
  };
}

You would need provider library.

like image 133
Max Avatar answered Dec 13 '25 23:12

Max