我不确定 initState
是否适合此功能。
我想要实现的是检查页面何时呈现以执行一些检查,并基于它们打开 AlertDialog
以在需要时进行一些设置。
我有一个有状态的页面。
它的 initState
函数如下所示:
@override
void initState() {
super.initState();
if (!_checkConfiguration()) {
_showConfiguration(context);
}
}
_showConfiguration
是这样的:
void _showConfiguration(BuildContext context) {
AlertDialog dialog = new AlertDialog(
content: new Column(
children: <Widget>[
new Text('@todo')
],
),
actions: <Widget>[
new FlatButton(onPressed: (){
Navigator.pop(context);
}, child: new Text('OK')),
],
);
showDialog(context: context, child: dialog);
}
如果有更好的方法来进行检查,并且如果需要调用模态,请指出正确的方向,我正在寻找 onState
或 onRender
函数,或者我可以分配给 build
函数以在渲染时调用但找不到的回调。
编辑:这里接缝他们有类似的问题:Flutter Redirect to a page on initState
最佳答案
成员变量 context 在 initState
期间可以访问,但不能用于所有内容。这是来自 initState
文档的 flutter :
You cannot use
[BuildContext.inheritFromWidgetOfExactType]
from this method. However,[didChangeDependencies]
will be called immediately following this method, and[BuildContext.inheritFromWidgetOfExactType]
can be used there.
您可以将初始化逻辑移动到 didChangeDependencies
,但这可能不是您想要的,因为 didChangeDependencies
可以在小部件的生命周期中被多次调用。
如果您改为进行异步调用,将您的调用委托(delegate)给小部件初始化后,您就可以按照您的意愿使用上下文。
一个简单的方法是使用 future 。
Future.delayed(Duration.zero,() {
... showDialog(context, ....)
}
另一种可能更“正确”的方法是使用flutter的调度程序添加帧后回调:
SchedulerBinding.instance.addPostFrameCallback((_) {
... showDialog(context, ....)
});
最后,我喜欢在 initState 函数中使用异步调用的一个小技巧:
() async {
await Future.delayed(Duration.zero);
... showDialog(context, ...)
}();
这是一个使用简单 Future.delayed 的完整示例:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _checkConfiguration() => true;
void initState() {
super.initState();
if (_checkConfiguration()) {
Future.delayed(Duration.zero,() {
showDialog(context: context, builder: (context) => AlertDialog(
content: Column(
children: <Widget>[
Text('@todo')
],
),
actions: <Widget>[
FlatButton(onPressed: (){
Navigator.pop(context);
}, child: Text('OK')),
],
));
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
);
}
}
有了评论中提供的 OP 的更多上下文,我可以为他们的具体问题提供更好的解决方案。根据应用程序的不同,您实际上可能希望根据是否是第一次打开应用程序来决定显示哪个页面,即将 home
设置为不同的值。对话框不一定是移动设备上最好的 UI 元素;最好显示一个完整的页面,其中包含他们需要添加的设置和一个下一步按钮。
https://stackoverflow.com/questions/49457717/