Flutter - Error Scaffold.of() called with a context that does not contain a Scaffold

In this article, I am going to share with you how to solve "Scaffold.of() called with a context that does not contain a Scaffold" error in Flutter. This error may occur when you are using the context of Scaffold. You can see the below error message.

 

══╡ EXCEPTION CAUGHT BY GESTURE ╞═════════════════════
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not 
contain a Scaffold. No Scaffold ancestor could be found 
starting from the context that was passed to Scaffold.of().
This usually happens when the context provided is from the 
same StatefulWidget as that whose build
function actually creates the Scaffold widget being sought.

 

How to solve this error :

First, you have to declare the key for the scaffold-like below.

final scaffoldKey = GlobalKey<ScaffoldState>();

Then, assign the key to the Scaffold like below.

Scaffold(
   key: scaffoldKey,
)

Now, we use scaffoldKey instead of Scaffold.of(context) where we need like the below example.

We can use it to close drawer.

Scaffold.of(context).closeDrawer();

//Use Instead of this

scaffoldKey.currentState!.closeDrawer();

Also, We use to show the bottom sheet dialog.

scaffoldKey.currentState!.showBottomSheet(
   return Container();
)

We can use it when getting errors during showing the Snackbar.

ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text("Hello This is FlutterCampus"))
);

I hope it will help you.

 

 

 

 

Tags: