如何解决将上下文传递给 showdialog 以便在起始页加载时不会丢失
我试图在启动应用程序时显示信息对话框。
关闭后,会出现另一个请求许可的窗口。我在 initState 函数中调用它。它有效,但我注意到第一个信息对话框也会在 15 秒过去后自行关闭。据我了解,这是因为应用程序已加载且上下文丢失。
当我将 runApp(MyApp())
更改为 runApp(MaterialApp(home: MyApp()))
时。它有效,弹出窗口不会消失。但是其他页面上的其他显示对话框没有自动关闭 (Navigator.of(context).pop()
并且 Navigator.pop(context)
不起作用。
如何正确地将上下文传递给我的初始显示对话框,以便在开始页面加载时它不会消失?
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
static final navKey = new GlobalKey<NavigatorState>();
const MyApp({Key navKey}) : super(key: navKey);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
final context = MyApp.navKey.currentState.overlay.context;
await showDialogIfFirstLoaded(context);
await initPlatformState();
});
}
showDialogIfFirstLoaded(BuildContext context,prefs) async {
bool isFirstLoaded = prefs.getBool(keyIsFirstLoaded);
if (isFirstLoaded == null) {
return showDialog(
context: context,builder: (BuildContext context) {
// return object of type Dialog
return new AlertDialog(
// title: new Text("title"),content: new Text("//"),actions: <Widget>[
new FlatButton(
child: new Text(".."),onPressed: () {
Navigator.of(context).pop();
},),],);
},);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey:MyApp.navKey,home: new SplashScreen(),}
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => new _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> with SingleTickerProviderStateMixin {
Timer _timer;
bool _visible = true;
startTime() async {
_timer = Timer(new Duration(seconds: 5),navigationPage);
}
void navigationPage() {
Navigator.of(context).pushReplacementNamed('/home');
}
@override
void initState() {
_timer = Timer(Duration(seconds: 4),() => setState(
() {
_visible = !_visible;
},);
startTime();
super.initState();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Stack(
children: <Widget>[
Container(
width: double.infinity,child: Image.asset('images/bg.jpg',fit: BoxFit.cover,height: 1200,Container(
width: double.infinity,color: Color.fromRGBO(0,0.8),Container(
alignment: Alignment.center,child: Row(
children: <Widget>[
Expanded(
flex: 2,child: Container(
child: Text(''),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。