Skip to content

Instantly share code, notes, and snippets.

@NHuyHoang
Last active November 9, 2022 12:01
Show Gist options
  • Save NHuyHoang/39f1f1a03d6b504569e8318de1b55d9f to your computer and use it in GitHub Desktop.
Save NHuyHoang/39f1f1a03d6b504569e8318de1b55d9f to your computer and use it in GitHub Desktop.
Programmatically select BottomNavigationBar Tab in Flutter instead of built in onTap callback
class _BTMAppBarState extends State<BTMAppBar> {
int navigationIndex = 0;
GlobalKey globalKey = new GlobalKey(debugLabel: 'btm_app_bar');
@override
Widget build(BuildContext context) {
return new Scaffold(
bottomNavigationBar: new BottomNavigationBar(
key: globalKey,
items: [
new BottomNavigationBarItem(
title: new Text("Tap 1"), icon: new Icon(Icons.people)),
new BottomNavigationBarItem(
title: new Text("Tap 2"), icon: new Icon(Icons.build)),
new BottomNavigationBarItem(
title: new Text("Tap 3"), icon: new Icon(Icons.favorite)),
],
onTap: (int index) {
setState(() {
navigationIndex = index;
switch (navigationIndex) {
case 0:
print("navigate to screen 1");
break;
case 1:
print("navigate to screen 2");
break;
case 2:
print("navigate to screen 3");
break;
}
});
},
),
body: new Center(
child: new RaisedButton(onPressed: () {
final BottomNavigationBar navigationBar = globalKey.currentWidget;
navigationBar.onTap(2);
}),
),
);
}
}
@Leonardbd
Copy link

It would be possible by using for example Provider package with the ChangeNotifierProvider

@vasudevsoni
Copy link

vasudevsoni commented Nov 6, 2022

Is there any way to change tab from another page

You can follow these steps to achieve the required purpose:

  1. Create a file MainProvider.dart with the following code -
import 'package:flutter/material.dart';

class MainProvider with ChangeNotifier {
  int currentPageIndex = 0;

  switchToPage(int index) {
    currentPageIndex = index;
    notifyListeners();
  }
}
  1. Where you want to change the tab use the code -
final mainProv = Provider.of<MainProvider>(context, listen: false);
CustomButtonWithoutIcon(
                          text: 'Explore Products',
                          onPressed: () {
                            setState(() {
                              mainProv.switchToPage(0);
                            });
                          },
                          bgColor: blueColor,
                          borderColor: blueColor,
                          textIconColor: whiteColor,
                        ),

@Riya-Singhal15
Copy link

Hi @vasudevsoni, I'm new at flutter, I'm new at flutter and I'm trying to change the page through the same page but from a different file. I tried to pass the global key in the widget argument but it didn't work. Can you please help me with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment