Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter FutureBuilder gets constantly called

Tags:

flutter

dart

api

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

like image 212
Aurimas Deimantas Avatar asked Sep 04 '19 17:09

Aurimas Deimantas


2 Answers

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) {},
      );
    }
    
like image 71
CopsOnRoad Avatar answered Sep 21 '22 11:09

CopsOnRoad


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.

Detail Explanation:

https://medium.com/flutterworld/why-future-builder-called-multiple-times-9efeeaf38ba2

like image 37
Jitesh Mohite Avatar answered Sep 23 '22 11:09

Jitesh Mohite