Created
August 14, 2019 12:34
-
-
Save av/abea7bb4eb227cde4719490f59d83fe9 to your computer and use it in GitHub Desktop.
Async app init
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
// ... | |
class _RootState extends State<RootWidget> { | |
TenderApiProvider tenderApi = TenderApiProvider(); | |
AppState state = AppState(); | |
Future init() async { | |
return Future.wait(<Future>[ | |
tenderApi.init(), // fetch and store token | |
Future.delayed(const Duration(milliseconds: 2000)) // Let user see the splash for couple of seconds | |
]); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MultiProvider( | |
providers: [ | |
ChangeNotifierProvider(builder: (_) => tenderApi), | |
ChangeNotifierProvider(builder: (_) => state), | |
], | |
child: MaterialApp(title: "My App"), | |
routes: <String, WidgetBuilder>{ | |
'/': _buildLoading | |
}, | |
), | |
); | |
} | |
Widget _buildLoading(BuildContext context) { | |
return FutureBuilder( | |
future: init(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
if (snapshot.hasData) { | |
// All good, show user actual home screen | |
return HomeScreen(); | |
} else if (snapshot.hasError) { | |
// Application probably won't run as expected | |
// as init has failed. | |
return ErrorScreen(); | |
} | |
return LoadingScreen(); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment