Skip to content

Instantly share code, notes, and snippets.

@frank06
Last active March 5, 2020 21:48
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 frank06/0fdd8343b739fd81d490a8254e1d3e7a to your computer and use it in GitHub Desktop.
Save frank06/0fdd8343b739fd81d490a8254e1d3e7a to your computer and use it in GitHub Desktop.
void main() async {
// ...
runApp(MultiProvider(
providers: [
Provider<Api>(create: (_) => Api()),
FutureProvider<UserService>(
create: (context) async {
var service = UserService(Provider.of(context, listen: false));
await service.init();
return service;
}
),
AwaitProvider<UserService>(),
ChangeNotifierProvider<ChatService>(
create: (context) => ChatService(Provider.of<UserService>(context, listen: false)), // WORKS!
)
],
// ...
}
typedef LoadingWidget = Widget Function(List);
typedef ProviderList = List Function(BuildContext);
class _DefaultLoadingWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
),
);
}
}
abstract class _AwaitProviders extends SingleChildStatelessWidget {
final Widget child;
final LoadingWidget loading;
final ProviderList values;
const _AwaitProviders({Key key, this.child, this.loading, this.values})
: super(key: key);
@override
Widget buildWithChild(BuildContext context, Widget child) {
final _values = values(context);
if (_values.contains(null)) {
if (loading != null) {
return loading(_values);
}
return _DefaultLoadingWidget();
}
return child;
}
}
class AwaitProvider<T> extends _AwaitProviders {
AwaitProvider({Key key, Widget child, LoadingWidget loading})
: super(
key: key,
child: child,
loading: loading,
values: (context) => [
Provider.of<T>(context),
],
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment