2

I am creating a drawer in flutter but whenever I click on the menu to open it, I get a Null check operator used on a null value error. What could be wrong?

        final scaffoldKey = GlobalKey<ScaffoldState>(); // the scaffoldKay variable


         AppBar(
          leading: IconButton(
            onPressed: () {
              scaffoldKey.currentState!.openDrawer(); // Error Here
            },
            icon: Icon(
              Icons.menu,
            ),
          ),
          title: Text(
            'Title Here',
            
            align: TextAlign.center,
            family: 'Poppins',
            style: FontStyle.normal,
            shadow: 0,
          ),
          

I have read others with a similar issues but it seems this is unique.

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Kennedy Owusu
  • 5,690
  • 4
  • 15
  • 20

2 Answers2

1

You should null check for scaffoldKey first:

onPressed: () {
    if (scaffoldKey.currentState != null) {
          scaffoldKey.currentState.openDrawer();
    }
},

and also make sure you pass the key to scaffold too, like this:

Scaffold(
  key: scaffoldKey,
  ...
)
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
0

You should assign scaffoldKey to the property key of the Scaffold widget. It's going to be something like this:

return Scaffold(
  key: scaffoldKey,     // <- Here
  appBar: AppBar(
    leading: IconButton(
      onPressed: () {
        scaffoldKey.currentState!.openDrawer();
      },
      icon: Icon(
        Icons.menu,
      ),
    ),
    title: Text(
      'Title Here',
      align: TextAlign.center,
      family: 'Poppins',
      style: FontStyle.normal,
      shadow: 0,
    ),
  ),
lepsch
  • 8,927
  • 5
  • 24
  • 44