As a quick Flutter FutureBuilder
note, I wrote a FutureBuilder preferences example, but by the nature of that topic, the code isn’t necessarily simple.
Today I just saw this much simpler FutureBuilder example, so I want to give it props. Besides the clean code, the important concept in that article is that you know that your widget data is coming from an async source — such as a REST call or database access — an you need to know how to handle that.
Please see that article for the complete source code and discussion, but what I’m most interested in is this what the author does inside the build
method:
void main() => runApp(MaterialApp(home: Scaffold(body: Center(child: MyWidget()))));
Future<String> callAsyncFetch() => Future.delayed(Duration(seconds: 2), () => "hi");
class MyWidget extends StatelessWidget {
@override
Widget build(context) {
return FutureBuilder<String>(
future: callAsyncFetch(),
builder: (context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else {
return CircularProgressIndicator();
}
}
);
}
}
That may be the most simple FutureBuilder
example I’ve ever seen, so kudos for that simplicity; this is a great FutureBuilder
template. A great thing about that article is that you can also run the example code inside a DartPad instance that’s embedded in the page.
As a note to myself, I use this approach to tell when the snapshot
has data, or more accurately, when it’s done:
if (snapshot.connectionState == ConnectionState.done)
So the next time I use this technique, I need to research this more to understand the differences between hasData
and done
.
Again, for more details, see that article, or see my FutureBuilder
posts: