No MaterialLocalizations found.和No MediaQuery widget found的解决方法
原创
©著作权归作者所有:来自51CTO博客作者WongKyunban的原创作品,请联系作者获取转载授权,否则将追究法律责任
在使用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(),
);
}
}