
Why FutureBuilder Keeps Refetching: Never Create the Future in build()
- كاتب موثّق
- Flutter 3.x
محتويات المقال
GET /orders/A1 once a second. Both reports come from one line inside build(): future: api.fetchOrder(widget.orderId).
The common misconception
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.
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
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
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
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 Futurehas 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 hasDatafirst shows no flicker, so on a fast network the bug is invisible.
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, ), ]);}class _OrderScreenState extends State<OrderScreen> { int _secondsLeft = 600; // a Timer calls setState every second late Future<Order> _order; @override void initState() { super.initState(); _order = api.fetchOrder(widget.orderId); // once per State } @override void didUpdateWidget(OrderScreen oldWidget) { super.didUpdateWidget(oldWidget); if (widget.orderId == oldWidget.orderId) return; _order = api.fetchOrder(widget.orderId); // another order: new request } @override Widget build(BuildContext context) => Column(children: [ Text('Arrives in $_secondsLeft s'), FutureBuilder<Order>(future: _order, builder: orderCard), ]);}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
initState | State | |
didUpdateWidget | ||
didChangeDependencies | initState, then when an inherited widget it uses changes | context |
setState(() => _order = ...) | ||
build |
How to apply it in your project
Search for calls in future: and stream: Look for future:orstream:followed by a method call in anybuild(). A field or a variable is fine; a call is a new request on every rebuild.Move the future into State Store 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.Handle the inputs it depends on Recreate the future in didUpdateWidgetwhen the id it was built from changes, or indidChangeDependencieswhen it comes from an inherited widget.Make refresh explicit Pull-to-refresh and retry buttons replace the future in setState. Nothing else should create a new one.Count requests in a test Give 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 whenbuild()runs, beforeFutureBuildereven sees it.A new Futureon each build means a new request, awaitingsnapshot 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 indidUpdateWidgetordidChangeDependencieswhen its input changes, and refresh it throughsetState.StreamBuilderhas the same rule: create the stream outsidebuild().
التعليقات (0)