flutter 如何传递ontap函数

vsikbqxv  于 2023-04-13  发布在  Flutter
关注(0)|答案(2)|浏览(148)

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

items: const <BottomNavigationBarItem>[

      BottomNavigationBarItem(

        icon: Icon(Icons.call),

        label: 'Calls',

      ),

      BottomNavigationBa

    ],

    onTap: (i) {

     

    },

How.do 我把它传递给每个项目

km0tfn4u

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
   };

},
d5vmydt9

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

相关问题