Skip to content

Instantly share code, notes, and snippets.

@rrousselGit
Last active March 5, 2020 23:19
Show Gist options
  • Select an option

  • Save rrousselGit/90e48f125a4707a49eb051d64ae3a6cf to your computer and use it in GitHub Desktop.

Select an option

Save rrousselGit/90e48f125a4707a49eb051d64ae3a6cf to your computer and use it in GitHub Desktop.
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