Created
September 3, 2020 12:18
-
-
Save vlasentiy/98403c72c70d17028215f08c604138bf to your computer and use it in GitHub Desktop.
FutureBuilder
This file contains 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
// FutureBuilder *is* a stateful widget | |
class FutureBuilder<T> extends StatefulWidget { | |
// it takes in a `future` and a `builder` | |
const FutureBuilder({ | |
this.future, | |
this.builder | |
}); | |
final Future<T> future; | |
// the AsyncWidgetBuilder<T> type is a function(BuildContext, AsyncSnapshot<T>) which returns Widget | |
final AsyncWidgetBuilder<T> builder; | |
@override | |
State<FutureBuilder<T>> createState() => _FutureBuilderState<T>(); | |
} | |
class _FutureBuilderState<T> extends State<FutureBuilder<T>> { | |
// keeps state in a local variable (so far there's no data) | |
AsyncSnapshot<T> _snapshot = null; | |
@override | |
void initState() { | |
super.initState(); | |
// wait for the future to resolve: | |
// - if it succeeds, create a new snapshot with the data | |
// - if it fails, create a new snapshot with the error | |
// in both cases `setState` will trigger a new build! | |
widget.future.then<void>((T data) { | |
setState(() { _snapshot = AsyncSnapshot<T>(data); }); | |
}, onError: (Object error) { | |
setState(() { _snapshot = AsyncSnapshot<T>(error); }); | |
}); | |
} | |
// builder is called with every `setState` (so it reacts to any event from the `future`) | |
@override | |
Widget build(BuildContext context) => widget.builder(context, _snapshot); | |
@override | |
void didUpdateWidget(FutureBuilder<T> oldWidget) { | |
// compares old and new futures! | |
} | |
@override | |
void dispose() { | |
// ... | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment