颤振动态导航条:识别点击了哪个图标/按钮



我正在创建一个动态的BottomNavigationBarItem列表,并将其分配给'items'的BottomNavigationBar。所以基于一个条件(这是我的例子),检查并添加一个更多的BottomNavigationBarItem,如果它没有计费。因此显示的图标数量发生了变化。通常对于固定数量的项目,ontap提供所点击图标的索引。随着图标顺序的改变,它们的索引也不同。

现在我如何读取选定的BottomNavigationBarItem的标签,并在onTap处理程序响应,而不是点击索引值?

(当然,在这种特殊情况下,我可以添加额外的按钮作为最后一个,并完成。需要一个更好的解决方案

List<BottomNavigationBarItem> getNavbarItems() {
List<BottomNavigationBarItem> navItems = [];
navItems.add(
const BottomNavigationBarItem(
icon: Icon(Icons.delete_outline,), label: 'Delete',),
);
if (widget.invStatus.isBilled == 0) {
navItems.add(
const BottomNavigationBarItem(
icon: Icon(Icons.receipt), label: 'Bill it ?'),
);
}
navItems.add(
const BottomNavigationBarItem(
icon: Icon(Icons.category_rounded), label: 'Add a Product !'),
);
return navItems;
}

谢谢。

如果我理解正确的话,您可以使用以下方法来获取"标签"。

调用:

getNavbarItems()[index].label

并有一个按钮来动态切换isBilled

完整的示例:

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Nav(),
),
),
);
}
}
class Nav extends StatefulWidget {
@override
createState() => NavState();
}
class NavState extends State<Nav> {
var _selectedIndex = 0;
var billIt = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Nav'),
),
body: Center(
child: TextButton(
child: Text('Toggle `billIt`'),
onPressed: () {
setState(() {
billIt = !billIt;
});
},
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
items: getNavbarItems(),
onTap: (int index) {
setState(() {
_selectedIndex = index;
print('label: ${getNavbarItems()[index].label}');
});
},
),
);
}
List<BottomNavigationBarItem> getNavbarItems() {
List<BottomNavigationBarItem> navItems = [];
navItems.add(
const BottomNavigationBarItem(
icon: Icon(
Icons.delete_outline,
),
label: 'Delete',
),
);
if (billIt) {
navItems.add(
const BottomNavigationBarItem(
icon: Icon(Icons.receipt), label: 'Bill it ?'),
);
}
navItems.add(
const BottomNavigationBarItem(
icon: Icon(Icons.category_rounded), label: 'Add a Product !'),
);
return navItems;
}
}

最新更新