Flutter FutureBuilder gets constantly called

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) {},
      );
    }
    

Leave a Comment