No MaterialLocalizations found. flutter dialog弹框的问题

在Flutter开发中遇到对话框Dialog无法在MaterialApp的home属性下直接使用的问题,原因是MaterialApp的context限制。解决方案是将Dialog代码移出到独立的方法中,并通过BuildContext调用。示例代码展示了如何创建并展示SimpleDialog和AlertDialog。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在写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);

},

)

],

);

});

}



 

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值