From 6382d12f524932ff1d26957e86428047714b128c Mon Sep 17 00:00:00 2001 From: Kevin Worth Date: Sun, 3 May 2020 20:21:31 -0400 Subject: [PATCH] Add initState to start the async call to fetch player 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. --- flutterempires/lib/main.dart | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/flutterempires/lib/main.dart b/flutterempires/lib/main.dart index 7bb1c7d..816b13e 100644 --- a/flutterempires/lib/main.dart +++ b/flutterempires/lib/main.dart @@ -53,6 +53,14 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { int _counter = 0; + Future futurePlayer; + + @override + void initState() { + super.initState(); + futurePlayer = Player.fetchPlayer(); + } + void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has @@ -107,7 +115,13 @@ class _MyHomePageState extends State { ), Spacer(flex: 1), FutureBuilder( + 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(); }, -- 2.43.0