skip to Main Content

How can I pass the ontap function to each icons

    items: const <BottomNavigationBarItem>[

      BottomNavigationBarItem(

        icon: Icon(Icons.call),

        label: 'Calls',

      ),

      BottomNavigationBa

    ],

    onTap: (i) {

     

    },

How.do i pass it to each items

2

Answers


  1. 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
       };
    
    },
    
    Login or Signup to reply.
  2. You can use callback method update widget based on tap,

    You can follow this example code.

    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',
            ),
          ],
        );
      }
    }
    

    If you are using on same widget, Follow doc example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search