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

538

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.

Share:
538
Théo Champion
Author by

Théo Champion

Updated on December 14, 2022

Comments

  • Théo Champion
    Théo Champion over 1 year

    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!

    • Markus Hein
      Markus Hein over 4 years
      Isn't there something like a Completer Class in flutter, which completes Futures. Don't know if this helps you
    • Théo Champion
      Théo Champion over 4 years
      @MarkusHein There is a completer class in Dart doc but I'm not sure how you want to use this in that case
    • Rémi Rousselet
      Rémi Rousselet over 4 years
      You cannot do so with Future+FutureBuilder. Not in a clean way at least. Consider switching to ValueListenable instead
    • Théo Champion
      Théo Champion over 4 years
      I'm sending the List<Future<PostModel>> from a BLoC through a stream. So that would mean converting it to a List<ValueListenable<PostModel>>, sending that through the stream and updating the values when they are ready from the BLoC ?
    • Pablo Barrera
      Pablo Barrera over 4 years
      Could you post some code of your approach? In order to see what you could do in your case to avoid this problem