在使用​​showDialog​​​和​​showModalBottomSheet​​​时,发现它们不能直接写在 ​​MaterialApp​​​的home属性下,会报如下错误:
​​​Another exception was thrown: No MaterialLocalizations found.​​​ 或
​Another exception was thrown: No MediaQuery widget found.​

解决的办法就是将代码提取出来:

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
/// [home]这个地方,不能直接写dialog的代码,否则你会得到 "Another exception was thrown: No MaterialLocalizations found."
/// 也不能写showModalBottomSheet的代码,否则你会得到 Another exception was thrown: No MediaQuery widget found.
/// 正确的做法就是把所有的内容都提取出去写。如下面这样把内容都提出来写到[HomePage]
home: HomePage(),// 不能直接写dialog的代码
);
}
}

提取出来的代码放到HomePage下:

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('分享'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: () {
showModalBottomSheet(
/**
* showModalBottomSheet常用属性
* shape 设置形状
* isScrollControlled:全屏还是半屏
* isDismissible:外部是否可以点击,false不可以点击,true可以点击,点击后消失
* backgroundColor : 设置背景色
*/
backgroundColor: Colors.transparent,
context: context,
builder: (BuildContext context) {
return RaisedButton(
child: Text("Click"),
onPressed: () {},
);
},
);
},
),
],
),
body: Center(),
);
}
}