Last active
March 5, 2020 23:19
-
-
Save rrousselGit/90e48f125a4707a49eb051d64ae3a6cf to your computer and use it in GitHub Desktop.
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 WaitUntilFutureProvider<T> extends SingleChildStatefulWidget { | |
| const WaitUntilFutureProvider({ | |
| Key key, | |
| this.waitUntil, | |
| this.create, | |
| Widget child, | |
| }) : super(key: key, child: child); | |
| final bool Function(BuildContext) waitUntil; | |
| final Create<Future<T>> create; | |
| @override | |
| _WaitUntilFutureProviderState<T> createState() => | |
| _WaitUntilFutureProviderState<T>(); | |
| } | |
| class _WaitUntilFutureProviderState<T> | |
| extends SingleChildState<WaitUntilFutureProvider<T>> { | |
| final createCompleter = Completer<T>(); | |
| var running = false; | |
| void start() { | |
| running = true; | |
| tryCreate(); | |
| } | |
| void tryCreate() { | |
| if (widget.waitUntil(context)) { | |
| running = false; | |
| createCompleter.complete(widget.create(context)); | |
| } | |
| } | |
| @override | |
| void didChangeDependencies() { | |
| super.didChangeDependencies(); | |
| if (running) { | |
| tryCreate(); | |
| } | |
| } | |
| @override | |
| Widget buildWithChild(BuildContext context, Widget child) { | |
| return FutureProvider<T>( | |
| create: (_) async { | |
| // not in initState to preserve lazy-loading | |
| start(); | |
| return createCompleter.future; | |
| }, | |
| child: child, | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment