initState is a good place to do asynchronous calls that we just
need to happen one time at the beginning.
So, in initStart we fetch the player and put it in a Future, and then
when (each and every time) build gets called, it uses what has
been fetched or shows the spinner if the fetch hasn't completed
successfully yet.
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
+ Future<Player> futurePlayer;
+
+ @override
+ void initState() {
+ super.initState();
+ futurePlayer = Player.fetchPlayer();
+ }
+
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
),
Spacer(flex: 1),
FutureBuilder<Player>(
+ future: futurePlayer,
builder: (context, snapshot) {
+ if (snapshot.hasData) {
+ return Text(snapshot.data.name);
+ } else if (snapshot.hasError) {
+ return Text("${snapshot.error}");
+ }
// By default, show a loading spinner.
return CircularProgressIndicator();
},