Flutter FutureBuilder gets constantly called Flutter FutureBuilder gets constantly called dart dart

Flutter FutureBuilder gets constantly called


Even if your code is working in first place, you are still not using it properly. As stated in the official documentation of Future Builder,

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.

The correct way to do this is:

// Create an instance variable.Future myFuture;@overridevoid initState() {  super.initState();    // Assign that variable your Future.  myFuture = getFuture();}@overrideWidget build(BuildContext context) {  return FutureBuilder(      builder: myFuture, // Use that variable here.      ...  );}  


Use AsyncMemoizerA 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