Want to build drawer with flutter web. But got Duplicate GlobalKey detected in widget tree. instance is moved to the new location. The key was:
- [LabeledGlobalKey#c9754]
GlobalKey reparenting is:
MainScreen(dependencies: [MediaQuery], state: _MainScreenState#dc897) A GlobalKey can only be specified on one widget at a time in the widget tree.
import 'package:flutter/material.dart';
class MenuController with ChangeNotifier { GlobalKey _scaffoldKey = GlobalKey();
GlobalKey<ScaffoldState> get scaffoldKey => _scaffoldKey; void controlMenu() { if (!_scaffoldKey.currentState!.isDrawerOpen) { _scaffoldKey.currentState!.openDrawer(); } } // void disposeKey() { // _scaffoldKey.currentState.(); // }}
class _MainScreenState extends State { @override void initState() { print('init CALLED- GAME---'); super.initState(); }
@override void dispose() { print('DISPOSE CALLED- GAME---'); context.read<MenuController>().scaffoldKey.currentState!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( key: context.read<MenuController>().scaffoldKey, drawer: SideMenu(), body: SafeArea( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // We want this side menu only for large screen if (Responsive.isDesktop(context)) Expanded( // default flex = 1 // and it takes 1/6 part of the screen child: SideMenu(), ), Expanded( // It takes 5/6 part of the screen flex: 5, child: DashboardScreen(), ), ], ), ), ); }}
then want to reuse key from another widget
class ProductsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
key: context.read<MenuController>().scaffoldKey,
drawer: SideMenu(),
body: SafeArea(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// We want this side menu only for large screen
if (Responsive.isDesktop(context))
Expanded(
// default flex = 1
// and it takes 1/6 part of the screen
child: SideMenu(),
),
Expanded(
// It takes 5/6 part of the screen
flex: 5,
child: ProductsListScreen(),
),
],
),
),
);
}
}
and got bug
To navigate inside SideMenu widget use
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ProductsScreen(),
),
);