在写dialog的时候,发现了一个问题,就是 dialog不能直接写在martierapp()这个home属性下面,要把dialog的代码,直接踢出去写。
这个是我发现了,是martierapp的conetxt的问题。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),----这个地方,不能直接写dialog的代码,把所有的内容都要提取出去写。
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
_MyHomePageState createState() => _MyHomePageState();
}
-----------------------------------dialog部分的代码
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('dialog 数据的显示'),),
body: Container(
child: Column(
children: <Widget>[
new RaisedButton(
onPressed: () {
showMyDialog(context);
},
child: new Text("显示SimpleDialog,Material风格")),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showMyDialog(context);
},
tooltip: 'increment',
child: Icon(Icons.add),
),
);
}
void showMySimpleDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return new SimpleDialog(
title: new Text("SimpleDialog"),
children: <Widget>[
new SimpleDialogOption(
child: new Text("SimpleDialogOption One"),
onPressed: () {
Navigator.of(context).pop("SimpleDialogOption One");
},
),
new SimpleDialogOption(
child: new Text("SimpleDialogOption Two"),
onPressed: () {
Navigator.of(context).pop("SimpleDialogOption Two");
},
),
new SimpleDialogOption(
child: new Text("SimpleDialogOption Three"),
onPressed: () {
Navigator.of(context).pop("SimpleDialogOption Three");
},
),
],
);
});
}
void showMyDialog(BuildContext context) {
showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: const Text('message'),
actions: <Widget>[
FlatButton(
child: const Text('ok'),
onPressed: () {
Navigator.of(context).pop(true);
},
)
],
);
});
}
}
在Flutter开发中遇到对话框Dialog无法在MaterialApp的home属性下直接使用的问题,原因是MaterialApp的context限制。解决方案是将Dialog代码移出到独立的方法中,并通过BuildContext调用。示例代码展示了如何创建并展示SimpleDialog和AlertDialog。

被折叠的 条评论
为什么被折叠?



