21

I'm experiencing interesting behavior. I have a FutureBuilder in Stateful widget. If I return FutureBuilder alone, everything is ok. My API gets called only once. However, if I put extra logic, and make a choice between two widgets - I can see in chrome my API gets called tens of times. I know that build method executes at any time, but how does that extra logic completely breaks Future's behavior?

Here is example of api calling once.

@override
  Widget build(BuildContext context) {
    return FutureBuilder(..);
}

Here is example of api being called multiple times if someBooleanFlag is false.

@override
  Widget build(BuildContext context) {
    if(someBooleanFlag){
      return Text('Hello World');
    }
    else{
    return FutureBuilder(..);
}

Thanks

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Aurimas Deimantas
  • 671
  • 1
  • 10
  • 29

3 Answers3

77

Even if your code is working in the first place, you are not doing it correctly. As stated in the official documentation of FutureBuilder,

The future must be obtained earlier, because if the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

Following are the correct ways of doing it. Use either of them:

  • Lazily initializing your Future.

    // Create a late instance variable and assign your `Future` to it. 
    late final Future myFuture = getFuture();
    
    @override
    Widget build(BuildContext context) {
      return FutureBuilder(
        future: myFuture, // Use that variable here.
        builder: (context, snapshot) {...},
      );
    }
    
  • Initializing your Future in initState:

    // Create an instance variable.
    late final Future myFuture;
    
    @override
    void initState() {
      super.initState();
    
      // Assign that variable your Future.
      myFuture = getFuture();
    }
    
    @override
    Widget build(BuildContext context) {
      return FutureBuilder(
        future: myFuture, // Use that variable here.
        builder: (context, snapshot) {},
      );
    }
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • 2
    I had this in my code, but also surrounded by ```if``` statement. However, today it seems working. Very weird. I need to spend more time in understanding this. Thank you! – Aurimas Deimantas Sep 05 '19 at 04:29
  • 4
    if getFuture() has parameters like `getFuture(id, param)` that id and param in initialized in build method, how could you called in `initState()`? @zeromaro – Cyrus the Great Mar 16 '20 at 05:12
  • Please see my answer. The above answer isn't wrong but it isn't right. It doesn't explain what you did wrong. It just shows you a way of making your code work which is not a good way to use stack overflow. You just left the parenthesis in. Let flutter decide when to call the future you are passing in. – Patrick Kelly Mar 21 '20 at 21:37
  • @PatrickKelly No worries, we all make mistakes, now would you mind deleting your comment and downvote? – CopsOnRoad Mar 26 '20 at 17:47
  • 2
    I had a listview builder returning from my futurebuilder with CheckboxListTile. When list item is checked, I have to call setState to show that it's been selected. This caused my FutureBuilder to fire again and again. This solved that. Thank you so much. – MAA Jul 12 '20 at 04:45
  • @CopsOnRoad We don't really need a late and a nullable(?) for the future declaration. Either one would do. – user1613360 Nov 01 '22 at 20:01
  • 1
    @user1613360 Yes, correct. I updated the code to only use `late`. – CopsOnRoad Nov 02 '22 at 18:07
11

Use AsyncMemoizer A class for running an asynchronous function exactly once and caching its result.

 AsyncMemoizer _memoizer;

  @override
  void initState() {
    super.initState();
    _memoizer = AsyncMemoizer();
  }

  @override
  Widget build(BuildContext context) {
    if (someBooleanFlag) {
         return Text('Hello World');
    } else {
      return FutureBuilder(
      future: _fetchData(),
      builder: (ctx, snapshot) {
        if (snapshot.hasData) {
          return Text(snapshot.data.toString());
        }
        return CircularProgressIndicator();
      },
     );
    }
  }

  _fetchData() async {
    return this._memoizer.runOnce(() async {
      await Future.delayed(Duration(seconds: 2));
      return 'DATA';
    });
  }                

Future Method:

 _fetchData() async {
    return this._memoizer.runOnce(() async {
      await Future.delayed(Duration(seconds: 2));
      return 'REMOTE DATA';
    });
  }

This memoizer does exactly what we want! It takes an asynchronous function, calls it the first time it is called and caches its result. For all subsequent calls to the function, the memoizer returns the same previously calculated future.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
  • Future getUid() async { await Future.delayed(Duration(seconds: 3)); var firebaseUser = await FirebaseAuth.instance.currentUser; var uid = userRef.doc(firebaseUser.uid).get(); return uid; } – Al Mamun Apr 03 '21 at 07:33
0
class QuizScreen extends StatefulWidget {
  const QuizScreen({Key? key}) : super(key: key);

  @override
  _QuizScreenState createState() => _QuizScreenState();
}

class _QuizScreenState extends State<QuizScreen> {
  static int count = 0;  

  initFunction() async {
    if (count > 0) return;
    else "your async function"
    count++;
  }

  @override
  void initState() {
    super.initState();
    count = 0;
  }

 

  @override
  void dispose() {
    super.dispose();
    count = 0;
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: FutureBuilder(
          future: initFunction(),
          builder: (context, snapshot) {
            return SafeArea(
              child: InfiniteCarousel.builder(
                center: true,
-
-
-
Anmol Shah
  • 71
  • 2
  • 3