flutter - 例外:未找到 MaterialLocalizations。尝试显示 AlertDialog 时
问题描述
尝试通过调用父小部件中的函数来显示警报对话框。
这是代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
popUp(context);
},
child: Text("Click"),
),
),
),
);
}
void popUp(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(title: Text("ok"),);
},
);
}
}
但得到以下异常:
I/flutter ( 4041): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 4041): The following assertion was thrown while handling a gesture:
I/flutter ( 4041): No MaterialLocalizations found.
I/flutter ( 4041): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
I/flutter ( 4041): Localizations are used to generate many different messages, labels,and abbreviations which are used
I/flutter ( 4041): by the material library.
I/flutter ( 4041): To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to
I/flutter ( 4041): include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
I/flutter ( 4041): The specific widget that could not find a MaterialLocalizations ancestor was:
I/flutter ( 4041): MyApp
I/flutter ( 4041): The ancestors of this widget were:
I/flutter ( 4041): [root]
上面写着use a MaterialApp at the root of your application
我已经完成了。我在这里做错了什么?
解决方案
问题是context
您传递给popUp
函数的变量实际上来自根。它不包含在MaterialApp
有意义的 if 中。
要解决此问题,您可以重构您的小部件以body
使其成为自己的小部件,或使用Builder
类似:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Builder(builder: (context) => Center(
child: RaisedButton(
onPressed: () {
popUp(context);
},
child: Text("Click"),
),
)),
),
);
}
推荐阅读
- java - Spring 自定义 PropertyEditor / 转换器无法识别:找不到匹配的编辑器或转换策略
- python - 如何组合数据类、属性和 lru_cache
- c++ - 在同一个套接字c ++上多次写入
- filter - 具有特定列日期范围的 SUMIF
- javascript - 如何使用网站中的 jquery/javascript 检测从网络浏览器(chrome)或 webview(移动应用程序)打开的 url?
- c++ - 使用 C++ 在 FireFox 中获取活动标签 URL
- dynamics-crm - 在 Dynamics-365 的选项集中添加元数据中不存在的选项
- ios - 像在照片应用程序中一样向 AVPlayer 添加滚动播放控件
- python - 从循环中重新抛出当前项目异常
- android - 无法为andriod构建intel cs webRTC示例项目