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.
CodePudding user response:
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,
...
)
CodePudding user response:
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,
),
),