gpt4 book ai didi

dart - 如何通过点击 BottomNavigationBarItem 以编程方式打开抽屉?

转载 作者:IT王子 更新时间:2023-10-29 06:38:02 24 4
gpt4 key购买 nike

我正在制作一个 flutter 应用程序,我需要能够通过点击 BottomNavigationBarItem 打开抽屉。有什么办法吗?

UX 设计师将抽屉菜单图标放在底部导航栏的索引 0 处。我试图在 Flutter 文档中找到答案,但没有找到任何相关内容。我实际上找到了一种以编程方式打开它的方法(如下所示),但在我的情况下它并不像那样工作。

class _HomeState extends State<Home> {
int _currentIndex = 1; // 0 = menu

final List<Widget> _children = [
PlaceholderWidget(Colors.deepPurple),
PlaceholderWidget(Colors.white),
DiagnosisWidget(),
FindUsWidget(),
];

_navItem(String text, IconData icon) {
return BottomNavigationBarItem(
/* Building Bottom nav item */
);
}

void onTabTapped(int index) {
setState(() {
if(index == 0) {
Scaffold.of(context).openDrawer(); // This is what I've tried
}
else {
_currentIndex = index;
}
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: MyDrawer(),
),
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed, // 4+ items in the bar
items: [
_navItem('MENU', Icons.menu),
_navItem('HOME', Icons.home),
_navItem('DIAGNOSIS', Icons.person),
_navItem('FIND US', Icons.location_on),
],
),
);
}
}

我没有显示抽屉,而是收到以下错误消息:

Scaffold.of() called with a context that does not contain a Scaffold.

最佳答案

这是因为在 onTabTapped 中,您使用的上下文不包含您创建的 Scaffold。

您在 build 中实例化脚手架,但在 onTabTapped 中,您正在寻找当前上下文(_HomeState 上下文)中的父脚手架。

您可以在 Scaffold 中使用 Builder 来获取正确的上下文,或者在您的 Scaffold 上使用 GlobalKey

参见 this answer了解更多详情。

编辑:在您的情况下,GlobalKey 更容易实现。

您可以执行以下操作:

class _HomeState extends State<Home> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(); // ADD THIS LINE
int _currentIndex = 1; // 0 = menu

final List<Widget> _children = [
PlaceholderWidget(Colors.deepPurple),
PlaceholderWidget(Colors.white),
DiagnosisWidget(),
FindUsWidget(),
];

_navItem(String text, IconData icon) {
return BottomNavigationBarItem(
/* Building Bottom nav item */
);
}

void onTabTapped(int index) {
setState(() {
if(index == 0) {
_scaffoldKey.currentState.openDrawer(); // CHANGE THIS LINE
}
else {
_currentIndex = index;
}
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey, // ADD THIS LINE
drawer: Drawer(
child: MyDrawer(),
),
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed, // 4+ items in the bar
items: [
_navItem('MENU', Icons.menu),
_navItem('HOME', Icons.home),
_navItem('DIAGNOSIS', Icons.person),
_navItem('FIND US', Icons.location_on),
],
),
);
}
}

关于dart - 如何通过点击 BottomNavigationBarItem 以编程方式打开抽屉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com