Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "'context != null': is not true" error when trying to showDialogue after a MaterialPageRoute in Flutter?

I am currently able to MaterialRoute to a page from the Home App in Flutter, as well as show a popup dialogue. However, upon routing from that second page to a third page, which contains a button that is supposed to show a dialogue, I am receiving this error: [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/localizations.dart': Failed assertion: line 446 pos 12: 'context != null': is not true.

The showDialogue that triggers that error looks like so:


class ThirdPageWidgetState extends State<ThirdPageWidget> {

  StreamSubscription<ScanResult> scanSubscription;

  @override
  void initState() {
    super.initState();
  }
Future<void> alert(deviceName) async {
    return showDialog<void>(
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Button Pressed!'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text('test'),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('Ok'),
            ),
          ],
        );
      },
    );
  }

  'Build function omitted'
}

And the routing of the second page to the third page looks like this:

void routeAppToThirdPage() async {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ThirdPageWidget(),
      ),
    );
  }
like image 965
P_equals_NP_2021 Avatar asked Mar 02 '23 13:03

P_equals_NP_2021


1 Answers

The reason you are getting this error is because you are not passing the BuildContext to showDialog you would have to change.

 Future<void> alert(deviceName, context) async {...}
//Then when you call your function in your build function you would pass in context
await alert(deviceName, context);
like image 130
wcyankees424 Avatar answered Mar 05 '23 05:03

wcyankees424