How to open a sidebar using GetX in Flutter

Issue

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.

Solution

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'),
       )
     ],
   )),
 );
 }
}

Answered By – rishabh mistry

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.