Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception : No MaterialLocalizations found. when trying to display AlertDialog

Tags:

flutter

Trying to display Alert Dialog by calling a function from the parent widget.

Here's the code :

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

But getting following Exception :

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]

It reads use a MaterialApp at the root of your application which I have already done. What am I doing wrong here?

like image 798
jatin Avatar asked Apr 06 '19 20:04

jatin


1 Answers

The problem is that the context variable you are passing to the popUp function is actually from the root. It is not contained inside the MaterialApp if that makes sense.

To work around this, you could either refactor your widget to have the body be it's own widget, or use a Builder like:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Builder(builder: (context) => Center(
          child: RaisedButton(
            onPressed: () {
              popUp(context);
            },
            child: Text("Click"),
          ),
        )),
      ),
    );
  }
like image 178
Herbert Poul Avatar answered Nov 15 '22 09:11

Herbert Poul