0

Hello in here I want to use Drawer when the Screen is on mobile size. The Navigation will turn into Drawer and creates a menu controller to store the GlobalKey of the ScaffoldState. The Drawer are work properly, turned into Menu Bar and when clicked the Drawer is showing. But in the terminal it throws error

Multiple Widgets used the same GlobalKey

enter image description here

Here's the code for the Menu Controller that I used to store the GlobalKey of the Scaffold:

// Import Dart Packages
import 'package:flutter/material.dart';

class MenuController extends ChangeNotifier {
  // Key Drawer for Dashboard Page
  static final GlobalKey<ScaffoldState> _scaffoldKeyDashboard =
      GlobalKey(debugLabel: 'Scaffold Key Dashboard');

  // Key Drawer for Analytics Page
  static final GlobalKey<ScaffoldState> _scaffoldKeyAnalytics =
      GlobalKey(debugLabel: 'Scaffold Key Analytics');

  // Key Drawer for History Page
  static final GlobalKey<ScaffoldState> _scaffoldKeyHistory =
      GlobalKey(debugLabel: 'Scaffold Key History');

  GlobalKey<ScaffoldState> get scaffoldKey1 => _scaffoldKeyDashboard;
  GlobalKey<ScaffoldState> get scaffoldKey2 => _scaffoldKeyAnalytics;
  GlobalKey<ScaffoldState> get scaffoldKey3 => _scaffoldKeyHistory;

  void controlMenu() {
    if (!_scaffoldKeyDashboard.currentState!.isDrawerOpen) {
      _scaffoldKeyDashboard.currentState!.openDrawer();
    }
    if (!_scaffoldKeyAnalytics.currentState!.isDrawerOpen) {
      _scaffoldKeyAnalytics.currentState!.openDrawer();
    }
    if (!_scaffoldKeyHistory.currentState!.isDrawerOpen) {
      _scaffoldKeyHistory.currentState!.openDrawer();
    }
  }
}

Then the code I used in Header are this code:

// Import Dart Packages
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// Import Pages Widgets
import 'package:dashboard/Styles/style.dart';

// Import Utilities
import 'package:dashboard/Utility/dark_mode_provider.dart';
import 'package:dashboard/Utility/menu_controller.dart';
import 'package:dashboard/Utility/responsive_settings.dart';

// Code for Header Components
class Header extends StatelessWidget {
  const Header({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        if (!Responsive.isDesktop(context))
          IconButton(
            icon: const Icon(
              Icons.menu,
              size: 25.0,
            ),
            onPressed: context.read<MenuController>().controlMenu,
          ),
        if (!Responsive.isMobile(context))
          const Text(
            "Cathodics Monitoring",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 50.0,
            ),
          ),
        if (Responsive.isMobile(context))
          const Text(
            "Cathodics Monitoring",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20.0,
            ),
          ),
        if (!Responsive.isMobile(context))
          Spacer(
            flex: Responsive.isDesktop(context) ? 2 : 1,
          ),
        const DarkThemeSwitch(),
      ],
    );
  }
}

class DarkThemeSwitch extends StatefulWidget {
  const DarkThemeSwitch({Key? key}) : super(key: key);

  @override
  State<DarkThemeSwitch> createState() => _DarkThemeSwitchState();
}

class _DarkThemeSwitchState extends State<DarkThemeSwitch> {
  @override
  Widget build(BuildContext context) {
    final themeChange = Provider.of<DarkThemeProvider>(context);

    return Container(
      padding: const EdgeInsets.all(defaultPadding),
      // decoration: const ,
      child: Column(
        children: [
          IconButton(
            icon: themeChange.darkTheme
                ? const Icon(Icons.light_mode_outlined)
                : const Icon(Icons.dark_mode_rounded),
            onPressed: () {
              setState(() {
                if (themeChange.darkTheme == true) {
                  themeChange.darkTheme = false;
                } else {
                  themeChange.darkTheme = true;
                }
              });
            },
            iconSize: 50.0,
          ),
        ],
      ),
    );
  }
}

For the page I used this key on the Scaffold:

return Scaffold(
      key: context.read<MenuController>().scaffoldKey1,
      drawer: const SideMenu(),
      body: FutureBuilder(),

I have tried to solve this problem by reading alots of the same problem and solving methods like in this How to keep the widget's state in Scaffold.drawer in Flutter?, this one Multiple widgets used the same GlobalKey with FormBuilder, https://stackoverflow.com/questions/49862572/multiple-widgets-used-the-same-globalkey[enter link description here]4 and another similar questions about Multiple Widgets used the same GlobalKey in various platform.

And when I open the drawer in Mobile screen and move to another page, the Drawer does not close like it used to be, why is this happening? Please I don't understand about it.

I am quite a new in Flutter and lack of experience, please if anyone has some suggestions or help, I would really appreciate it. Thank you!

1 Answers1

0

I don't understand why you need 3 different Scaffold keys if you only call open drawer on them, it can be done with only one.

Anyway context.read() cannot be called inside [StatelessWidget.build]/[State.build]. On the other hand, it can be freely called outside of these methods. If that is incompatible with your criteria, consider using Provider.of(context, listen: false). This might be the cause.

noxgood
  • 180
  • 1
  • 7
  • I used 3 different keys in 3 different pages, because I thought it will be solved my problem. But if I am using Provider.of it throw errors saying that "The argument type 'MenuController' can't be assigned to the parameter type 'Key?'". – Agil Calfarera Sep 27 '22 at 03:47
  • This issue is not connected to the Provider, most likely you are trying to provide a wrong parameter to the function(most likely Widget) which requires Key but you give it MenuController – noxgood Sep 27 '22 at 09:40
  • And what am I supposed to do so it does work properly? Can you provide any example for me please? Thank You. – Agil Calfarera Sep 28 '22 at 03:53