Search code examples
flutterdartdart-null-safety

Null Check Operator used on null value - flutter


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.


Solution

  • 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,
        ),
      ),