Flutter - How to navigate to another page on an asynchronous value
All you have to do is after you get the preferences, just navigate to the screen and have the build method just build a progress indicator.
Try this:
_fetchPrefs() async {
await Future.delayed(Duration(seconds: 1));
Navigator.of(context).pushNamed("home"); //stateful widgets give you context
}
Here's your new build method:
@override
Widget build(BuildContext context) {
return Center(child: CircularProgressIndicator());
}
I've made a DartPad to illustrate: https://dartpad.dartlang.org/431fcd9a1ea5748a82506f13be042e85
William Terrill
Updated on December 16, 2022Comments
-
William Terrill over 1 year
I'm trying to show a splash screen on initial app startup until I have all of the data properly retrieved. As soon as it's there, I want to navigate to the main screen of the app.
Unfortunately, I can't find a good way to trigger a method that runs that kind of Navigation.
This is the code that I'm using to test this idea. Specifically, I want to run the command
Navigator.pushNamed(context, 'home');
when the variableshouldProceed
becomes true. Right now, the only way I can think to do it is to display a button that I need to press to trigger the navigation code:import 'package:flutter/material.dart'; import 'package:catalogo/src/navigationPage.dart'; class RouteSplash extends StatefulWidget { @override _RouteSplashState createState() => _RouteSplashState(); } class _RouteSplashState extends State<RouteSplash> { ValueNotifier<bool> buttonTrigger; bool shouldProceed = false; _fetchPrefs() async { //this simulates the asynchronous function await Future.delayed(Duration( seconds: 1)); // dummy code showing the wait period while getting the preferences setState(() { shouldProceed = true; //got the prefs; ready to navigate to next page. }); } @override void initState() { super.initState(); _fetchPrefs(); // getting prefs etc. } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: shouldProceed ? RaisedButton( onPressed: () { print("entered Main"); Navigator.pushNamed(context, 'home'); // <----- I want this to be triggered by shouldProceed directly }, child: Text("Continue"), ) : CircularProgressIndicator(), //show splash screen here instead of progress indicator ), ); } }
So, in short, how can I trigger a function that runs the Navigation code when shouldProceed changes?