【发布时间】:2020-11-29 22:02:51
【问题描述】:
我在导航时遇到“小部件树中的多个全局键”的问题。
我在基本屏幕的 Scaffold 和 Scaffold 的 body 参数中定义了一个 BottomNavigationBar 和一个 Drawer,我有多个使用 BottomNavigationBar 访问的屏幕。问题是,我正在使用 GlobalKey 从多个屏幕之一访问基本屏幕的抽屉,一切正常,但是当我从另一个屏幕导航到基本屏幕时,我收到上述错误。
我尝试了在定义键时不使用静态关键字的解决方案,它解决了导航错误,但我无法访问抽屉,因为随后我收到另一个错误“方法‘openDrawer’被调用为空”。
这是一个单独的类,我在其中定义了 Key:
class AppKeys {
final GlobalKey<ScaffoldState> homeKey = GlobalKey<ScaffoldState>();
}
这是基本屏幕:
class Base extends StatefulWidget {
@override
_BaseState createState() => _BaseState();
}
class _BaseState extends State<Base> {
int selectedScreen = 0;
final screens = List<Widget>.unmodifiable([Home(), Cart(), Orders(), Help()]);
AppKeys appKeys = AppKeys();
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: MyDrawer(),
key: appKeys.homeKey,
body: screens[selectedScreen],
bottomNavigationBar: SizedBox(
height: 80,
child: BottomNavigationBar(
onTap: (val) {
setState(() {
selectedScreen = val;
});
},
currentIndex: selectedScreen,
selectedItemColor: AppColor.primary,
elevation: 20.0,
unselectedItemColor: Colors.grey,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
iconSize: 25,
selectedFontSize: 15,
unselectedFontSize: 15,
items: [
BottomNavigationBarItem(
icon: Icon(AnanasIcons.home), title: Text("Home")),
BottomNavigationBarItem(
icon: Icon(AnanasIcons.cart), title: Text("Cart")),
BottomNavigationBarItem(
icon: Icon(AnanasIcons.orders), title: Text("My Orders")),
BottomNavigationBarItem(
icon: Icon(AnanasIcons.help), title: Text("Help")),
],
),
),
);
}
}
这是我访问抽屉的主屏幕:
class Home extends StatelessWidget {
final AppKeys appKeys = AppKeys();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(
AnanasIcons.menu,
color: Colors.black,
),
onPressed: () {
appKeys.homeKey.currentState.openDrawer();
}),
backgroundColor: Theme.of(context).canvasColor,
title: Text("Hi"),
actions: [
IconButton(
icon: Icon(
Icons.person,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Profile(),
));
})
],
),
body: Container(),
);
}
}
【问题讨论】:
-
请在您的问题中包含代码。
-
@Mobina 完成。我已经添加了代码。
标签: flutter