Home > Software design >  flutter: GlobalKey error when using Drawer
flutter: GlobalKey error when using Drawer

Time:09-07

I`m new to flutter.

After login, the screen goes dark and the following error occurs when moving to the my HomePage. How can I solve this problem?

The following assertion was thrown while finalizing the widget tree: Multiple widgets used the same GlobalKey. The key [LabeledGlobalKey#c6bc9] was used by multiple widgets. The parents of those widgets were:

  • HomePage(state: _HomePageState#8437e)
  • HomePage(state: _HomePageState#f49a2) A GlobalKey can only be specified on one widget at a time in the widget tree.

This is my HomePage

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String uid = FirebaseAuth.instance.currentUser!.uid;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _willPopCallback,
      child: Scaffold(
        key: _scaffoldKey,
        endDrawer: Drawer(
          child: ListView(
            children: [
              ...
            ],
          ),
        ),
        appBar: AppBar(
          automaticallyImplyLeading: false,
          actions: [
            IconButton(
                onPressed: () {
                  showProfileDialog(context, uid: uid);
                },
                icon: const Icon(Icons.account_circle, size: 30)),
            IconButton(
              onPressed: () {
                _scaffoldKey.currentState!.openEndDrawer();
              },
              icon: const Icon(
                Icons.dehaze_sharp,
                size: 30,
              ),
            ),
            const SizedBox(width: 10)
          ],
        ),
        body: Center(
          child: 
           ...   
          ),
        ),
      ),
    );
  }
}

Future<bool> _willPopCallback() async {
  return true;
}

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

CodePudding user response:

you can access to key

 Scaffold.of(context).openDrawer();

and this will work without create GlobalKey

CodePudding user response:

It means that the key still holds the state of the old widget. Try resetting the global key in dispose of HomePageState class.

  • Related