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

Issue

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

Solution

showDialogue<void>() requires a context:context param, which wasn’t being caught by the compiler.

return showDialog<void>(
      context: context // THIS WAS MISSING
      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'),
            ),
          ],
        );
    ```

Answered By – P_equals_NP_2021

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.