MuhammadOsamaQureshi
MuhammadOsamaQureshi

Reputation: 73

How can I add endDrawer outside of appbar in Flutter?

I want to add a Drawer to the icon button but it's outside of appbar here in this code, I tried to implement it by watching some tutorial but its not working for me maybe cuz I used endDraw anyone have idea how to do it?

here is my code

 GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  

    @override
     
    
         Widget build(BuildContext context) {
            return Scaffold(
              key: _scaffoldKey,

          endDrawer: Drawer2() ,
     

     appBar: AppBar(
        backgroundColor: MyColor.backgroud_primary_color,
        leading: Icon(
          Icons.chevron_left_rounded,
          color: MyColor.icon_color,
        ),
        centerTitle: true,
        title: Container(
          width: 100,
          height: 100,
          child: Image(
            image: AssetImage("assets/logo.png"),
            fit: BoxFit.contain,
          ),
        ),
        actions: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 5),
            child: IconButton(
              onPressed: () => _scaffoldKey.currentState!.openDrawer(),
              icon: Icon(Icons.sort),
              iconSize: 30,
              color: MyColor.icon_color,
            ),
          )
        ],
      ),

Drawer2() is a custom drawer that I have made I want to open the end drawer when I click on Icon button is there any way?

Upvotes: 1

Views: 1268

Answers (3)

Abdulrahman
Abdulrahman

Reputation: 26

To open the drawer you need to use _scaffoldKey.currentState!.openEndDrawer(), based on endDrawer docs, here

So, your code should be:

actions: [
  Padding(
    padding: EdgeInsets.symmetric(horizontal: 5),
    child: IconButton(
      onPressed: () => _scaffoldKey.currentState!.openEndDrawer(),
      icon: Icon(Icons.sort),
      iconSize: 30,
      color: MyColor.icon_color,
    ),
  )
],

Upvotes: 1

MD MEHEDI HASAN
MD MEHEDI HASAN

Reputation: 2470

import 'package:flutter/material.dart';

class DemoScreen extends StatelessWidget {
  const DemoScreen({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Demo Screen"),),
      endDrawer: Drawer2(),
      body: Center(
        child: Text("data")
      ),
    );
  }
}

class Drawer2 extends StatelessWidget {
  const Drawer2({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer( // Custom widget must be return Drawer 
      child: ListTile( //Implement any design on child property
        title: Text("Demo tile"),
      ),
    );
  }
}

Upvotes: 1

Use:

 Scaffold.of(context).openEndDrawer()

and if you want to disable the drag behavior set this in Scaffold:

drawerEnableOpenDragGesture: false,

Upvotes: 3

Related Questions