例外:找不到MaterialLocalizations。尝试显示AlertDialog时

时间:2019-04-06 20:12:01

标签: flutter

尝试通过从父窗口小部件调用函数来显示“警报对话框”。

这是代码:

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,我已经完成了。我在这里做什么错了?

2 个答案:

答案 0 :(得分:1)

问题在于,您传递给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"),
          ),
        )),
      ),
    );
  }

答案 1 :(得分:1)

void main() => runApp(MaterialApp(
      home:MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  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"),);
      },
    );
  }
}

问题是我们必须在程序的根目录 runApp() 中实现 MaterialApp