Reputation: 390
In Flutter I have seen the method Scaffold.of(context).openDrawer()
to open sidebar. Currently I am using GetX in my project. Is there any alternative in Get to open Drawer? Thanks a lot for any help.
Upvotes: 4
Views: 8661
Reputation: 6127
The accepted answer is correct, but it actually explains how to open/close the drawer programmatically. For example, you have some regular button somewhere in your app with the label "Open menu" or "Settings" and when the user clicks on it you want to open a drawer.
But this is a very special case. Usually, we don't need it.
The Scaffold widget has a property drawer. We just need to provide value to this property like:
drawer: const MyDrawer(),
and we will get a sandwich button that opens the drawer:
When the drawer is opened the user just has to click on the outside area to close it.
The only specific code to GetX is when the user clicks on the ListTile:
ListTile(
title: const Text('Theme settings'),
onTap: () {
Get.back(); //close drawer
Get.toNamed(Routes.THEME_SETTINGS_SCREEN);
},
)
We have to call Get.back()
to close the drawer. Otherwise, it will remain open.
Upvotes: 0
Reputation: 542
For Drawer We have to use Scaffold and give darwer widget to it and open drawer using globalKey of scaffold state
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
Get.put(Controller());
runApp(GetMaterialApp(home: Home()));
}
class Controller extends GetxController {
var scaffoldKey = GlobalKey<ScaffoldState>();
void openDrawer() {
scaffoldKey.currentState.openDrawer();
}
void closeDrawer() {
scaffoldKey.currentState.openEndDrawer();
}
}
class Home extends GetView<Controller> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
key: controller.scaffoldKey,
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Item 1'),
onTap: controller.closeDrawer,
)
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: controller.openDrawer,
child: Text('open drawer'),
)
],
)),
);
}
}
Upvotes: 18