flutterflutter-layoutdart-null-safetynull-safety

Method 'showBottomSheet' cannot be called on 'ScaffoldState?' because it is potentially null


Hello I'm getting this error when I tried to run the code

lib/layout/home_layout.dart:54:36: Error: Method 'showBottomSheet' cannot be called on 'ScaffoldState?' because it is potentially null.
 - 'ScaffoldState' is from 'package:flutter/src/material/scaffold.dart' ('/C:/src/flutter/packages/flutter/lib/src/material/scaffold.dart').
Try calling using ?. instead.
          scaffoldKey.currentState.showBottomSheet(
                                   ^^^^^^^^^^^^^^^

I have a variable that I have defined:

 var scaffoldKey = GlobalKey<ScaffoldState>();

Here I am trying to build a bottomsheet when clicking on the floatingactionbutton

floatingActionButton: FloatingActionButton(
    onPressed: () {
      scaffoldKey.currentState.showBottomSheet(
              (context) => Container(
                width: double.infinity,
                height: 120.0,
                color: Colors.red
              ),
      );
    },
    child: const Icon(
        Icons.add
    ),
  ),

Kindly, can someone tell me where I am going wrong?


Solution

  • So the problem is, as you might have already figured out, that flutter doesn't know if the current state variable is null, there are some situations in which it is null, and because of that, it will not let you call it, here is the obvious solution:

    if (scaffoldKey.currentState != null) {
      scaffoldKey.currentState!.showBottomSheet(...);
    }
    

    Note the ! after currentState, when you place ! after a potentially null value, you are telling flutter, "trust me, this value is not null" which means it will throw an error if it is null, but it won't complain otherwise.

    A, perhaps better solution is doing what your error code suggests:

    Method 'showBottomSheet' cannot be called on 'ScaffoldState?' because it is potentially null. Try calling using ?. instead. scaffoldKey.currentState.showBottomSheet(

    Like this:

    scaffoldKey.currentState?.showBottomSheet(...);
    

    When using ?. you are conditionally calling a method or a member variable on a potentially null value

    So what the above line says is, "if currentState is not null, call it's showBottomSheet method, otherwise, do nothing".