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.

3
  • Have you checked the value of scaffoldKey in the onPressed method? Commented Aug 28, 2022 at 6:40
  • yeah. its value is null Commented Aug 28, 2022 at 6:46
  • 1
    It would be easier if you could include full scaffold Commented Aug 28, 2022 at 6:52

2 Answers 2

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,
  ...
)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.