The Problem with Standard FutureBuilder
When you use the standard FutureBuilder
in Flutter, it's designed to run the future
function every single time the widget is rebuilt. This is fine for simple tasks, but if your future
is something expensive, like making an API call, it can lead to unnecessary requests and costs.
The Solution: Single Execution FutureBuilder
To fix this, you can create a custom widget called SingleExecutionFutureBuilder
. This widget is designed to run the future
function only once.
How It Works
This custom widget holds onto the result of the future
after the first time it runs. On subsequent rebuilds, instead of running the future
again, it simply gives you the result it already has.
Benefits
- Avoids repeating expensive operations.
- Saves network requests (good for API calls).
- Can be useful for implementing retry logic or manual refreshes if needed.
Simple Implementation
The image shows a basic implementation where the future is wrapped in a function that checks if it has already run. If not, it executes the original future; otherwise, it returns the stored result.
Using this SingleExecutionFutureBuilder
ensures that operations like fetching data only happen once when the widget is first shown, not every time the UI updates for other reasons.