In this example, we are going to show you how to check if the drawer is open or close. If the drawer is open then close it, or if the drawer is closed, then open it programmatically in Flutter. See the example below:
First, declare the key for scaffold:
final scaffoldKey = GlobalKey<ScaffoldState>();
Now, pass this key to the Scaffold widget where the drawer is placed.
Scaffold(
key: scaffoldKey,
drawer: Drawer(),
)
Now, check if drawer is Opened or closed:
if(scaffoldKey.currentState!.isDrawerOpen){
//drawer is opened
}else{
//drawer is closed
}
Now, you can open the drawer if closed, or close the drawer if opened programmatically:
if(scaffoldKey.currentState!.isDrawerOpen){
scaffoldKey.currentState!.closeDrawer();
//close drawer, if drawer is open
}else{
scaffoldKey.currentState!.openDrawer();
//open drawer, if drawer is closed
}
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text("Open/Close Drawer Flutter"),
),
drawer: Drawer(),
body: Container(
height: 150,
child: Center(
child: ElevatedButton(
child: Text("Open/Close Drawer"),
onPressed: (){
if(scaffoldKey.currentState!.isDrawerOpen){
scaffoldKey.currentState!.closeDrawer();
//close drawer, if drawer is open
}else{
scaffoldKey.currentState!.openDrawer();
//open drawer, if drawer is closed
}
},
),
),
)
);
}
}
In this way, you can open or close the drawer programmatically in Flutter.
Please Wait...
No any Comments on this Article