الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 6 دقائق للقراءة

Why FutureBuilder Keeps Refetching: Never Create the Future in build()

A future created in build() is a new request on every rebuild. Create it once in State and pass the same one.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

A delivery app's order screen shows a countdown, "Arrives in 598 s", with the order details below it. On the office Wi-Fi it works. On a slow mobile connection, QA reports that the details never load: the spinner keeps turning. At the same time, the backend team asks why every open order screen calls GET /orders/A1 once a second. Both reports come from one line inside build(): future: api.fetchOrder(widget.orderId).

The common misconception

The belief: FutureBuilder(future: api.fetchOrder(id), ...) calls the API once, and FutureBuilder handles the rest. It runs the request, waits for it and remembers the result.

It's an easy belief to hold. The code reads declaratively, "this part of the screen shows the result of that request", and Flutter teaches you to describe UI rather than manage it. FutureBuilder is also a StatefulWidget, so it does keep state across rebuilds, which sounds a lot like caching. And on a simple screen the bug hides: build() may run twice, the second request is cheap, and the screen shows the right data. The half-truth is that FutureBuilder keeps the latest snapshot. It doesn't own the future. It listens to whatever object you pass it this time.

What actually happens

The request starts before FutureBuilder exists

Dart evaluates arguments before it calls a constructor, so api.fetchOrder(widget.orderId) runs first. An async function starts executing right away and returns a that completes later. Only then is the FutureBuilder created, holding a request that's already on its way. So the real question isn't what FutureBuilder does with your future. It's how many times that line runs, and the answer is once per build().

build() runs more often than you think

The State.build docs list the usual triggers: after initState, after didUpdateWidget (the parent rebuilt), after every setState, when an inherited widget it depends on changes, and when the State moves in the tree. In a real app that means a countdown ticking, a parent calling setState, or a screen that reads MediaQuery.of(context) rebuilding when the keyboard opens or the device rotates. The FutureBuilder docs give the rule to design for: "assume that every build method could get called every frame, and to treat omitted calls as an optimization." The build docs add that it "should not have any side effects beyond building a widget", and a network request is a .

What FutureBuilder does with a new future

When its parent rebuilds, FutureBuilder receives a new widget and its State runs didUpdateWidget. In Flutter's source, it compares the old and new futures with ==. Two calls return two different Future objects, so they're never equal: it stops listening to the old one, subscribes to the new one and moves the snapshot back to ConnectionState.waiting. Three things follow:

  • Every rebuild sends a request. Stopping listening cancels nothing, since Future has no cancel method: the old request runs to the end and its result is ignored.
  • If a response takes longer than the gap between two rebuilds, no result is ever shown. Each future is replaced before it completes.
  • While it waits, the snapshot keeps the previous data (the docs say data and error "will be retained" when you switch to another future). A builder that checks hasData first shows no flicker, so on a fast network the bug is invisible.
Dart order_screen.dart
class _OrderScreenState extends State<OrderScreen> {  int _secondsLeft = 600; // a Timer calls setState every second  @override  Widget build(BuildContext context) => Column(children: [        Text('Arrives in $_secondsLeft s'),        FutureBuilder<Order>(          // Evaluated on every build: a new Future, a new request          future: api.fetchOrder(widget.orderId),          builder: orderCard,        ),      ]);}

In a widget test with a fake API and a timer ticking every second, the first version sent 61 requests in one minute: one for the first build and one per tick. With 300 ms responses the screen looked right the whole time, even though the builder got a waiting snapshot 60 times. With 1.5 s responses, 60 of the 61 requests completed and none was ever shown: the spinner turned for the full minute. The second version sent one request in both runs and showed the order as soon as it arrived. didUpdateWidget is there because initState runs once per State: if the parent switches to another order, that's the place to start the new request.

Where the future should come from

PlaceWhen it runsUse it for
initStateOnce per StateThe first request
didUpdateWidgetWhen the parent passes a new widgetA new request when the id or query changed
didChangeDependenciesAfter initState, then when an inherited widget it uses changesRequests that depend on something from context
setState(() => _order = ...)When you call itPull-to-refresh and retry buttons
buildPotentially every frameNever: it's a new request each time

How to apply it in your project

  1. Search for calls in future: and stream:Look for future: or stream: followed by a method call in any build(). A field or a variable is fine; a call is a new request on every rebuild.
  2. Move the future into StateStore it in a field and create it in initState. If the widget is stateless today, make it stateful, or get the future from an object that already lives longer than the widget.
  3. Handle the inputs it depends onRecreate the future in didUpdateWidget when the id it was built from changes, or in didChangeDependencies when it comes from an inherited widget.
  4. Make refresh explicitPull-to-refresh and retry buttons replace the future in setState. Nothing else should create a new one.
  5. Count requests in a testGive a widget test a fake API with a call counter, trigger a few rebuilds and expect exactly one call. It fails immediately if someone moves the call back into build().

Key takeaways

  • The call you pass as future: runs when build() runs, before FutureBuilder even sees it.
  • A new Future on each build means a new request, a waiting snapshot and the old result ignored, not cancelled.
  • With slow responses and frequent rebuilds, a future created in build() may never show any data.
  • Create the future in initState, recreate it in didUpdateWidget or didChangeDependencies when its input changes, and refresh it through setState.
  • StreamBuilder has the same rule: create the stream outside build().

📚 المصادر

  1. FutureBuilder class — Flutter API
  2. StreamBuilder class — Flutter API
  3. Fetch data from the internet — Flutter docs
  4. State.build — Flutter API
  5. MediaQuery class — Flutter API

التعليقات (0)