Last active
March 5, 2020 21:48
-
-
Save frank06/0fdd8343b739fd81d490a8254e1d3e7a to your computer and use it in GitHub Desktop.
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
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