如何传递ontap函数

问题描述 投票:0回答:2

如何将 ontap 函数传递给每个图标

    items: const <BottomNavigationBarItem>[

      BottomNavigationBarItem(

        icon: Icon(Icons.call),

        label: 'Calls',

      ),

      BottomNavigationBa

    ],

    onTap: (i) {

     

    },

我如何将它传递给每个项目

flutter flutter-dependencies flutter-animation
2个回答
0
投票
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
   };

},

0
投票

您可以使用基于点击的回调方法更新小部件,

您可以按照此示例代码进行操作。

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示例

© www.soinside.com 2019 - 2024. All rights reserved.