Search code examples
flutterdart-null-safety

Got a compilation problem with dart null safety


I am new to flutter null safety and I can't manage how to have no compilation error. This is the (incomplete) code

GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
Scaffold(
  key: _scaffoldKey
);
...
showDialog(context: _scaffold.currentContext)

showdialog is waiting for a non null BuildContext so I got the error:

The argument type 'BuildContext?' can't be assigned to the parameter type 'BuildContext'

Help please!


Solution

  • If you sure that _scaffold.currentContext can never be null:

    GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    Scaffold(
      key: _scaffoldKey
    );
    ...
    showDialog(context: _scaffold.currentContext!) //Add "!" here and the problem is solved