Search code examples
flutterdartsidebarfloating-action-button

How to display a sidebar by clicking a floating widget?


I already have a screen and a floating menu.

Scaffold(
      drawer: SideBar(),
      body: isLoading..
..
..
CircularMenuItem(
          //icon: Icons.settings,
          image: Image.asset(
            "assets/images/icons/settings.png",
            scale: 13,
          ),
          onTap: () {
            //callback
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) => SideBar()));
            // toggleSidebar();
          },
          color: Colors.transparent, 
        ),
..

When clicking an item from this floating menu, i want a sidebar to be displayed from left to right, occupying 60% screen width( a typical sidebar). But when i do it, it is displayed just like a page, taking up the whole screen, no animation,

class SideBar extends StatefulWidget {
  @override
  State<SideBar> createState() => _SideBarState();
}

class _SideBarState extends State<SideBar> {
  // const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    final User? user = FirebaseAuth.instance.currentUser;
    final screenwidth = MediaQuery.of(context).size.width;
    return Drawer(
      width: screenwidth * .5,
      child: ListView(
        children: [
          UserAccountsDrawerHeader(
            accountName: Text(user?.displayName ?? ''),
            accountEmail: Text(user?.email ?? ''),
            currentAccountPicture: CircleAvatar(
              child: ClipOval(child: Icon(Icons.person)),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: NetworkImage(
                      'https://oflutter.com/wp-content/uploads/2021/02/profile-bg3.jpg')),
            ),
          ),
        ],
      ),
    );
  }
}

How to display it like normal?


Solution

  • As @Jay commented, stackoverflow.com/a/57748219/19107084 this worked for me.

    final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        key: _key, // Assign the key to Scaffold.
        drawer: Drawer(),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _key.currentState!.openDrawer(), // <-- Opens drawer
        ),
      );
    }