how to use showbottomsheet with null safety in flutter?

Issue

I’m still learning flutter new this week, seems the course is outdated, so i struggle every time I face null safety errors. Now, I can’t use showbottomsheet.. tried null check(!)
but onPressed() is always returning null , i can’t figure what should i do to prevent that..

Error: The method ‘showBottomSheet’ can’t be unconditionally invoked because the receiver can be ‘null’.

and when i use null check: it says "can’t use null operand"

here’s the piece of code i use:

var scaffoldkey = GlobalKey<ScaffoldState>();


onPressed: () {
        scaffoldkey.currentState.showBottomSheet(
          (context) => Container(
            color: Colors.red,
            padding: EdgeInsets.all(
              20.0,
            ),
          ),
        );
      },

Solution

Just put a question mark or interjection before errored code:

var scaffoldkey = GlobalKey<ScaffoldState>();
onPressed: () {
        scaffoldkey.currentState?.showBottomSheet(
          (context) => Container(
            color: Colors.red,
            padding: EdgeInsets.all(
              20.0,
            ),
          ),
        );
      },

The problem: currentState may be null.
If you put a question mark, it does nothing when it’s null, does not invoke the showBottomSheet method.

If you put an interjection, it forces to invoke the showBottomSheet method even if it’s null, and if it is null, it throws an error like before null-aware era.

Answered By – EmreSURK

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *