FutureBuilder in Flutter

Md Didarul
2 min readJan 20, 2023

Hi there, fellow flutter enthusiast!

Today we are going to learn more about, how to show asynchronous data correctly from Future<T> with FutureBuilderin flutter.

We all know, Future<T>is awesome. It let us do asynchronous work like fetching data from server without thinking about Threads and Deadlocks and all.

Future<Model> _doCalculation() async {
// do calculation / computation asynchronously.
....
return Model;
}

On the other hand, FutureBuilder<T> helps us to show ui according to the state of the future. We can show ui for loading, errors, data by usingFutureBuilder<T>

FutureBuilder<Model>(
future: _doCalculationFuture,
builder: (BuildContext context, AsyncSnapshot<Model> snapshot) {
if (snapshot.hasData) {
return DataWidget(snapshot.requireData);
} else if (snapshot.hasError) {
return ErrorWidget();
} else {
return CircularProgressIndicator();
}
return const SizedBox();
},
);

FutureBuilder takes one required parameter builder.It will be called based on the Future<T>state. We need to provide the future we created in order to show appropriate ui.

We must be careful while providing Future<T>in FutureBuilder. As theFutureBuilder will typically be inside of the build method and we know build method can be called multiple times, we must not create theFuture<T> inside it.

If we create Future<T> inside build method, it will be created again whenever build is called. It probably is not what you want.

So, where to create futures?

The ideal place to create or update a future is the lifecycle methods of a widget such as initState, didUpdateWidget, didChangeDependencies etc. or any place other than build.

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<Model> _doCalculationFuture;

@override
void initState() {
super.initState();
_doCalculationFuture = _doCalculation();
}

Future<Model> _doCalculation() async {
return await Future<Model>.delayed(
const Duration(seconds: 2),
() => Model(),
);
}

@override
Widget build(BuildContext context) {
return FutureBuilder<Model>(
future: _doCalculationFuture,
builder: (BuildContext context, AsyncSnapshot<Model> snapshot) {
if (snapshot.hasData) {
return DataWidget(snapshot.requireData);
} else if (snapshot.hasError) {
return ErrorWidget();
} else {
return CircularProgressIndicator();
}
return const SizedBox();
},
);
}
}

That’s all for today. I hope to see you in Future😄😄

Happy coding!!

--

--

Md Didarul

I am a Mobile Application Developer. I love to build cool things with Flutter. I have prior experience in Android App Development with Kotlin and Java