尝试通过从父窗口小部件调用函数来显示警报对话框。
这是代码:
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
内。
要解决这个问题,您可以重构您的小部件以使body
成为它自己的小部件,或者使用Builder
,如:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Builder(builder: (context) => Center(
child: RaisedButton(
onPressed: () {
popUp(context);
},
child: Text("Click"),
),
)),
),
);
}