Last active
April 5, 2018 00:07
-
-
Save timsneath/091818696af1038c3b677638cc115bbc to your computer and use it in GitHub Desktop.
Handling asynchronous state with a FutureBuilder widget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JokePageState extends State<JokePage> { | |
Future<String> response; | |
initState() { | |
super.initState(); | |
response = http.read(dadJokeApi, headers: httpHeaders); | |
} | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
body: new Center( | |
child: new FutureBuilder<String>( | |
future: response, | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
switch (snapshot.connectionState) { | |
case ConnectionState.none: | |
return const Icon(Icons.sync_problem); | |
case ConnectionState.waiting: | |
case ConnectionState.active: | |
return const CircularProgressIndicator(); | |
case ConnectionState.done: | |
final decoded = json.decode(snapshot.data); | |
if (decoded['status'] == 200) { | |
return new Text(decoded['joke']); | |
} else { | |
return const Icon(Icons.error); | |
} | |
} | |
}, | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment