首页 > 解决方案 > 例外:未找到 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我已经完成了。我在这里做错了什么?

标签: flutter

解决方案


问题是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"),
          ),
        )),
      ),
    );
  }

推荐阅读