为什么我的代码BottomNavigationBarItem中没有key属性
时间: 2024-03-18 16:38:36 浏览: 19
如果你使用的是最新版本的 `BottomNavigationBarItem`,则它已经不再支持 `key` 属性了。这是因为 `BottomNavigationBarItem` 现在是一个不可变类,其属性必须在构造函数中指定。
如果你想要获取 BottomNavigationBar 的每个子项的中心坐标,你可以尝试使用 `IndexedStack` 和 `Visibility` 来实现。具体步骤如下:
1. 给每个子项的 icon 添加 `GlobalKey`:
```
BottomNavigationBarItem(
icon: Icon(Icons.home, key: GlobalKey()),
label: 'Home',
),
```
2. 在 `BottomNavigationBar` 的 `onTap` 回调中,设置相应的 `index` 并调用 `setState` 更新界面。
3. 在 `IndexedStack` 中使用 `Visibility` 包裹每个子项的界面,并根据当前选中的 `index` 来设置相应的 `visible`。
4. 在每个子项的界面中,使用 `LayoutBuilder` 获取 icon 的中心坐标。
完整示例代码如下:
```
class MyBottomNavigationBar extends StatefulWidget {
@override
_MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}
class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {
final List<GlobalKey> _itemKeys = List.generate(4, (_) => GlobalKey());
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: [
_buildPage(0),
_buildPage(1),
_buildPage(2),
_buildPage(3),
],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home, key: _itemKeys[0]),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search, key: _itemKeys[1]),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person, key: _itemKeys[2]),
label: 'Profile',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings, key: _itemKeys[3]),
label: 'Settings',
),
],
),
);
}
Widget _buildPage(int index) {
return Visibility(
visible: _currentIndex == index,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final RenderBox iconRenderBox =
_itemKeys[index].currentContext.findRenderObject();
final Offset iconPosition =
iconRenderBox.localToGlobal(iconRenderBox.size.center(Offset.zero),
ancestor: context.findRenderObject());
return Center(
child: Text('Icon position: $iconPosition'),
);
},
),
);
}
}
```
这样,当你点击 BottomNavigationBar 的某个子项时,就会在对应的页面上显示该子项 icon 的中心坐标。