By Alvin Alexander. Last updated: March 15, 2022
As a note to my Future Self, any time you’re working with Flutter and you want to try to make initState
or build
an async
method — or try to use the then
method on a Future
inside initState
or build
— what you probably really want is to use a FutureBuilder
inside the build
method, something like this:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Notification Preferences"),
),
body: FutureBuilder<Map<String, dynamic>>(
future: SharedPreferencesHelper.getAllPrefs(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// YOUR CUSTOM CODE GOES HERE
This is true with the Flutter shared_preferences library, as well as any other data that may take a long time to retrieve, such as reading from a database or REST data source.
Update: You may also want another Flutter async builder, such as StreamBuilder
.