如何将ontap函数传递给每个图标
items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.call), label: 'Calls', ), BottomNavigationBa ], onTap: (i) { },
How.do 我把它传递给每个项目
km0tfn4u1#
items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.call), label: 'Calls', ), BottomNavigationBarItem( icon: Icon(Icons.contacts), label: 'Contacts', ), ], onTap: (i) { // call if( i == 0 ){ // do somethings }; // contacts if( i == 1 ){ // do somethings }; },
d5vmydt92#
您可以使用回调方法更新基于tap的widget,您可以遵循此示例代码。
void main() => runApp(MaterialApp(home: MyApp())); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int currentIndex = 0; @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: MyBottomNavBar( currentIndex: currentIndex, onTap: (index) { setState(() { currentIndex = index; }); }), body: Center( child: [Text('1'), Text('2'), Text('3')][currentIndex], ), ); } } class MyBottomNavBar extends StatelessWidget { const MyBottomNavBar({ super.key, required this.onTap, required this.currentIndex, }); final Function(int) onTap; final int currentIndex; @override Widget build(BuildContext context) { return BottomNavigationBar( currentIndex: currentIndex, onTap: onTap, items: const [ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), ], ); } }
如果您正在使用相同的小部件,请关注doc example
2条答案
按热度按时间km0tfn4u1#
d5vmydt92#
您可以使用回调方法更新基于tap的widget,
您可以遵循此示例代码。
如果您正在使用相同的小部件,请关注doc example