Flutter FutureBuilder gets constantly called

后端 未结 2 1015
無奈伤痛
無奈伤痛 2020-12-20 18:11

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,

相关标签:
2条回答
  • 2020-12-20 18:31

    Even if your code is working in first place, you are still not doing it properly, the correct way to do is:

    // Create instance variable
    Future myFuture;
    
    @override
    void initState() {
      super.initState();
    
      // assign this variable your Future
      myFuture = getFuture();
    }
    
    @override
    Widget build(BuildContext context) {
      if (someBooleanFlag) {
        return Text('Hello World');
      } else {
        return FutureBuilder(
          future: myFuture, // use it like this
          ...
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-20 18:38

    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

    0 讨论(0)
提交回复
热议问题