Skip to content

Instantly share code, notes, and snippets.

@timsneath
Last active April 5, 2018 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsneath/091818696af1038c3b677638cc115bbc to your computer and use it in GitHub Desktop.
Save timsneath/091818696af1038c3b677638cc115bbc to your computer and use it in GitHub Desktop.
Handling asynchronous state with a FutureBuilder widget
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