我正在尝试在初始应用程序启动时显示启动画面,直到正确检索到所有数据。一旦出现,我想导航到应用程序的主屏幕。
不幸的是,我找不到触发运行这种导航的方法的好方法。
这是我用来测试这个想法的代码。具体来说,我想运行命令 Navigator.pushNamed(context, 'home');
当变量 shouldProceed
变成真的。现在,我能想到的唯一方法是显示一个我需要按下以触发导航代码的按钮:
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
),
);
}
}
因此,简而言之,如何在 shouldProceed 更改时触发运行导航代码的函数?
最佳答案
您所要做的就是在获得首选项后,只需导航到屏幕并让构建方法构建一个进度指示器。
尝试这个:
_fetchPrefs() async {
await Future.delayed(Duration(seconds: 1));
Navigator.of(context).pushNamed("home"); //stateful widgets give you context
}
这是您的新构建方法:
@override
Widget build(BuildContext context) {
return Center(child: CircularProgressIndicator());
}
我做了一个 DartPad 来说明:https://dartpad.dartlang.org/431fcd9a1ea5748a82506f13be042e85
关于Flutter - 如何导航到异步值上的另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437966/