I would like to show a widget on the screen as quickly as possible when my app launches. After the widget has been shown to the user, I'd like to do some app initialization (e.g. set up a database) before leaving the launch screen by pushing another screen. I cannot figure out where to put my app initialization code. Something analogous to viewDidAppear
on iOS.
This is what I tried based on initState
.
class Launch extends StatefulWidget {
@override
_LaunchState createState() {
return _LaunchState();
}
}
class _LaunchState extends State<Launch> {
@override
Widget build(final BuildContext context) {
print('LaunchState build start');
final Widget w = Center(
child: Text('Launching...'),
);
print('LaunchState build end');
return w;
}
@override
void initState() {
print('LaunchState initState start');
super.initState();
print('LaunchState initState middle');
_appInitialization();
print('LaunchState initState end');
}
void _appInitialization() {
print('LaunchState _appInitialization');
}
}
The output was
flutter: LaunchState initState start
flutter: LaunchState initState middle
flutter: LaunchState _appInitialization
flutter: LaunchState initState end
flutter: LaunchState build start
flutter: LaunchState build end
The output I think I want to see is
flutter: LaunchState build start
flutter: LaunchState build end
flutter: LaunchState initState start
flutter: LaunchState initState middle
flutter: LaunchState _appInitialization
flutter: LaunchState initState end
Maybe I'm going about this in a very un-flutter way. If there is a completely different approach, I'm all ears.
SOLUTION
Thanks to Mangaldeep Pannu's answer, it appears I'm missing async
.
class Launch extends StatefulWidget {
@override
_LaunchState createState() {
return _LaunchState();
}
}
class _LaunchState extends State<Launch> {
@override
Widget build(final BuildContext context) {
print('LaunchState build start');
final Widget w = Center(
child: Text('Launching...'),
);
print('LaunchState build end');
return w;
}
@override
void initState() {
print('LaunchState initState start');
super.initState();
print('LaunchState initState middle');
_appInitialization(); // no await
print('LaunchState initState end');
}
void _appInitialization() async {
print('LaunchState _appInitialization begin');
// simulate some time consuming initialization task
await Future.delayed(Duration(seconds: 5));
print('LaunchState _appInitialization middle');
Navigator.push(...);
print('LaunchState _appInitialization end');
}
}
The results are
flutter: LaunchState initState start
flutter: LaunchState initState middle
flutter: LaunchState _appInitialization begin
flutter: LaunchState initState end
flutter: LaunchState build start
flutter: LaunchState build end
[5 second pause]
flutter: LaunchState _appInitialization middle
flutter: LaunchState _appInitialization end