Is there a way to display the BottomNavigationBar on every View? - flutter

I am trying to display the BottomNavigationBar on every View I have, it's working but this is a "dumb" way to do that...
I have a custom BottomNavigationBar which I am inserting in every View.
var selectedIndex = 0;
class CustomBottombar extends StatefulWidget {
CustomBottombar({Key key}) : super(key: key);
#override
_CustomBottombarState createState() => _CustomBottombarState();
}
class _CustomBottombarState extends State<CustomBottombar> {
List _viewList = [FirstView(), SecondView()];
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
currentIndex: selectedIndex,
onTap: _onItemTapped,
items: _items,
);
}
void _onItemTapped(int index) {
setState(() {
selectedIndex = index;
Navigator.of(context).popUntil((route) => route.isFirst
);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => _viewList[index]),
);
});
}
final _items = [
BottomNavigationBarItem(
icon: Icon(
Icons.refresh,
color: Color(0xFFACACAC),
size: 35,
),
title: Text("first")),
BottomNavigationBarItem(
icon: Icon(
Icons.phone,
color: Color(0xFFACACAC),
size: 35,
),
title: Text("second"),
),
BottomNavigationBarItem(
icon: Icon(
Icons.add_shopping_cart,
color: Color(0xFFACACAC),
size: 35,
),
title: Text("thrid"),
),
];
}
in the _onItemTapped function I pop everything from the "Navigationstack" and then I am displaying the Screen that is in my Items.
in my FirstView() I have then this code
class FirstView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar(""),
bottomNavigationBar: CustomBottombar(),
endDrawer: CustomDrawer(),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ContactView()),
);
},
child: Text('First'),
),
),
);
}
}
Now I want to move to "ContactView" which is not an Item in the BottomNavigationBar
class ContactState extends State<ContactView> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppBar("title"),
endDrawer: CustomDrawer(),
bottomNavigationBar: CustomBottombar(),
body: SafeArea(
bottom: true,
child: SingleChildScrollView(
child: Container(child: Text("Contact"),),
)),
);
}
}
I'll also have a lot of other views which are not in the items array but I want to display the BottomNavigationBar on.
My Issue is really this function.
void _onItemTapped(int index) {
setState(() {
selectedIndex = index;
Navigator.of(context).popUntil((route) => route.isFirst
);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => _viewList[index]),
);
});
}
because here I'm deleting the navigation history to display the View which is in the Items Array.
Is there a standard way to do this, Hopefully, someone can help.
EDIT:
For clarification: I have like 10 Screens. Only 3 of those are navigatiable via BottomNavigationBar, Let's say the first 3 of those 10. now I want to Navigate to Screen4 from Screen1. The navigationbar disappears on screen4. I want Want to keep the Navigationbar on all Screens.
Edit 2
#Dhaval Kansara answer worked for me but I got a new Problem.
I have an enddrawer, before the fix it was above the BottomNavigationBar now the BottomNavigationBar is above.
but I want it like this

Use CupertinoTabBar as shown below for the static BottomNavigationBar.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mqttdemo/Screen2.dart';
import 'package:mqttdemo/Screen3.dart';
import 'Screen1.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex;
List<Widget> _children;
#override
void initState() {
_currentIndex = 0;
_children = [
Screen1(),
Screen2(),
Screen3(),
];
super.initState();
}
#override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
currentIndex: _currentIndex,
onTap: onTabTapped,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Screen 1"),
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Screen 2"),
),
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text("Screen 3")),
],
),
tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context) {
return SafeArea(
top: false,
bottom: false,
child: CupertinoApp(
home: CupertinoPageScaffold(
resizeToAvoidBottomInset: false,
child: _children[_currentIndex],
),
),
);
},
);
}
);
}
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
}
Navigate to screen4 from Screen3 as shown below:
class Screen3 extends StatefulWidget {
#override
_Screen3State createState() => _Screen3State();
}
class _Screen3State extends State<Screen3> {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.black,
child: Center(
child: RaisedButton(
child: Text("Click me"),
onPressed: () {
Navigator.of(context, rootNavigator: false).push(MaterialPageRoute(
builder: (context) => Screen4(), maintainState: false));
},
),
),
);
}
}

Related

I am trying to insert the bottom navigation bar which i have created into my main page which is the hunt view but its not working when i run the code

This is the main page where I have written the bottom bar navigation code. I have run the code, but the bar does not appear on my home page. It does not give me any errors. which means the code is fine and i just need to call it properly. How do I call the function so it displays across all other pages?
import 'package:thehunt/views/hunt/profile_view.dart';
import 'package:thehunt/views/hunt/settings_view.dart';
import 'package:thehunt/views/login_view.dart';
class HuntView extends StatelessWidget {
const HuntView({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return HomeView();
} else {
return AuthView();
}
},
),
);
}
}
//bottom navigation bar
class BottomNavView extends StatefulWidget {
const BottomNavView({super.key});
#override
State<BottomNavView> createState() => _BottomNavViewState();
}
class _BottomNavViewState extends State<BottomNavView> {
List views = [
const HomeView(),
const CurrentLocationView(),
const ProfileView(),
const SettingsView()
];
int currentIndex = 0;
void onTap(int index) {
currentIndex = index;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: views[currentIndex],
bottomNavigationBar: BottomNavigationBar(
unselectedFontSize: 0,
selectedFontSize: 0,
type: BottomNavigationBarType.fixed,
backgroundColor: Color.fromARGB(255, 198, 176, 235),
onTap: onTap,
currentIndex: currentIndex,
selectedItemColor: Colors.black54,
unselectedItemColor: Colors.grey.withOpacity(0.5),
showUnselectedLabels: false,
showSelectedLabels: false,
elevation: 0,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Home',
icon: Icon(Icons.home_outlined),
),
BottomNavigationBarItem(
label: 'Map',
icon: Icon(Icons.map),
),
BottomNavigationBarItem(
label: 'Settings',
icon: Icon(Icons.settings),
),
BottomNavigationBarItem(
label: 'Profile',
icon: Icon(Icons.person),
),
],
),
);
}
}
Below is my home page view where I want the bottom navigation bar to be displayed
class HomeView extends StatefulWidget {
const HomeView({super.key});
#override
State<HomeView> createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
final user = FirebaseAuth.instance.currentUser!;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(' Home'),
backgroundColor: Colors.deepPurple[200],
elevation: 0,
),
drawer: const NavigationDrawer(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Logged In as: ' + user.email!),
MaterialButton(
onPressed: () {
FirebaseAuth.instance.signOut();
},
color: Colors.deepPurple[200],
child: Text('sign out'),
),
MaterialButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return const CurrentLocationView();
},
),
);
},
color: Colors.deepPurple[200],
child: const Text('User location')),
],
),
),
);
}
}
Call BottomNavView in HuntView instead of HomeView as below code
class HuntView extends StatelessWidget {
const HuntView({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return BottomNavView(); <------- call here BottomNavView
} else {
return AuthView();
}
},
),
);
}
}

Flutter: Nested routing with persistent BottomNavigationBar but without building the unselected pages unnecessarily

Throughout the internet and stackoverflow I've searched and seen a lot of solutions to the problem of nested navigation with a persistent BottomNavigationBar for Flutter apps. Some of them using Navigators with IndexedStack or PageView and so on and so forth. All of them work just fine except that they will unnecessarily build the unselected tabs (sometimes even rebuilding all of them every time you switch tabs) thus making the solution not performatic. I did finally come up with a solution to that – as I was struggling with this problem myself.
The solution is very basic but hopefully you will be able to build upon it and adapt it. It achieves the following:
nests navigation while persisting the BottomNavigationBar
does not build a tab unless it has been selected
preserves the navigation state
preserves the scroll state (of a ListView, for example)
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Widget> _pages;
List<BottomNavigationBarItem> _items = [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.messenger_rounded),
label: "Messages",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: "Settings",
)
];
int _selectedPage;
#override
void initState() {
super.initState();
_selectedPage = 0;
_pages = [
MyPage(
1,
"Page 01",
MyKeys.getKeys().elementAt(0),
),
// This avoid the other pages to be built unnecessarily
SizedBox(),
SizedBox(),
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: WillPopScope(
onWillPop: () async {
return !await Navigator.maybePop(
MyKeys.getKeys()[_selectedPage].currentState.context,
);
},
child: IndexedStack(
index: _selectedPage,
children: _pages,
),
),
bottomNavigationBar: BottomNavigationBar(
items: _items,
currentIndex: _selectedPage,
onTap: (index) {
setState(() {
// now check if the chosen page has already been built
// if it hasn't, then it still is a SizedBox
if (_pages[index] is SizedBox) {
if (index == 1) {
_pages[index] = MyPage(
1,
"Page 02",
MyKeys.getKeys().elementAt(index),
);
} else {
_pages[index] = MyPage(
1,
"Page 03",
MyKeys.getKeys().elementAt(index),
);
}
}
_selectedPage = index;
});
},
),
);
}
}
class MyPage extends StatelessWidget {
MyPage(this.count, this.text, this.navigatorKey);
final count;
final text;
final navigatorKey;
#override
Widget build(BuildContext context) {
// You'll see that it will only print once
print("Building $text with count: $count");
return Navigator(
key: navigatorKey,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.text),
),
body: Center(
child: RaisedButton(
child: Text(this.count.toString()),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => MyCustomPage(count + 1, text)));
},
),
),
);
},
);
},
);
}
}
class MyCustomPage extends StatelessWidget {
MyCustomPage(this.count, this.text);
final count;
final text;
#override
Widget build(BuildContext parentContext) {
return Scaffold(
appBar: AppBar(
title: Text(this.text),
),
body: Column(
children: [
Expanded(
child: Container(
child: ListView.builder(
itemCount: 15,
itemBuilder: (context, index) {
return Container(
width: double.infinity,
child: Card(
child: Center(
child: RaisedButton(
child: Text(this.count.toString() + " pos($index)"),
onPressed: () {
Navigator.of(parentContext).push(MaterialPageRoute(
builder: (ctx) =>
MyCustomPage(count + 1, text)));
},
),
),
),
);
},
),
),
),
],
),
);
}
}
class MyKeys {
static final first = GlobalKey(debugLabel: 'page1');
static final second = GlobalKey(debugLabel: 'page2');
static final third = GlobalKey(debugLabel: 'page3');
static List<GlobalKey> getKeys() => [first, second, third];
}

Flutter: value of currentIndex property in BottomNavigationBar doesn't update when the state updates

I have a BottomNavigationBar that navigates to other pages when pressing an icon. This works fine, except the value of the currentIndex property in BottomNavigationBar doesn't update when the state updates, which means there is no change on the acual BottomNavigationBar. enter image description here
I'm using a vaiable (_selectedPage) to keep track of the selected index in the BottomNavigationBar, and the value changes when tapping an item, but it's not updating the currentIndex property when the state updates.. why is that?
import 'package:flutter/material.dart';
import 'package:independentproject/pages/home_page.dart';
import 'package:independentproject/pages/cook_recipe.dart';
class PageNavigationBar extends StatefulWidget {
#override
_PageNavigationBarState createState() => _PageNavigationBarState();
}
class _PageNavigationBarState extends State<PageNavigationBar> {
//default page showing in bottom navigation bar will be CookRecipe()
int _selectedPage = 1;
//all pages optional in bottom navigation bar
final List<Widget> _pageOptions = [
HomePage(),
CookRecipe(),
];
void onTapped(int pageTapped) {
setState(() {
//print(pageTapped);
_selectedPage = pageTapped;
Navigator.push(context, MaterialPageRoute(builder: (context) => _pageOptions[pageTapped]));
//print(_selectedPage);
});
}
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
//TODO: currentIndex: doesn't update when the state updates, why?
currentIndex: _selectedPage,
//items showing in bottom navigation bar
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
);
}
}
import 'package:flutter/material.dart';
import 'package:independentproject/page_navigation_bar.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home page'),
),
body: Center(
child: Text('Home page'),
),
bottomNavigationBar: PageNavigationBar(),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:independentproject/page_navigation_bar.dart';
class CookRecipe extends StatefulWidget {
#override
_CookRecipeState createState() => _CookRecipeState();
}
class _CookRecipeState extends State<CookRecipe> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Search recipe'),
),
body: Center(
child: Text('Search recipes'),
),
bottomNavigationBar: PageNavigationBar(),
),
);
}
}
I would advise you to create a widget that will contain the BottomNavigationBar and also PageView that would allow you to switch pages with PageController.
For example:
class _MainScreenState extends State<MainScreen> {
PageController _pageController;
int _page = 1;
Duration pageChanging = Duration(milliseconds: 300);//this is for page animation-not necessary
Curve animationCurve = Curves.linear;//this is for page animation-not necessary
_MainScreenState();
#override
void initState() {
super.initState();
_pageController = PageController(initialPage: 1);
}
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
controller: _pageController,
onPageChanged: onPageChanged,
children: <Widget>[
//here are all the pages you need:
//CookRecipe(),
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.message,
),
title: Container(height: 0.0),
),
BottomNavigationBarItem(
icon: Icon(
Icons.home,
),
title: Container(height: 0.0),
),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
),
title: Container(height: 0.0),
),
],
onTap: navigationTapped,
selectedItemColor: Theme.of(context).backgroundColor,
currentIndex: _page,
),
),
);
}
void navigationTapped(int page) {
_pageController.animateToPage(page,duration: pageChanging,
curve: animationCurve,);
}
#override
void dispose() {
super.dispose();
_pageController.dispose();
}
void onPageChanged(int page) {
if (this.mounted){
setState(() {
this._page = page;
});
}}
You can also do this without the PageView,and use only the controller to switch pages.
BTW-you create new instance of the navigation bar when you load a page which is bad practice
it is because PageNavigationBar is a own class, when you call there a setstate only this class updates
take a look at the Provider
a very usefull state management Package
or you can also handle your Page, when the NavBar is your Main Page and you have only one Page
return MaterialApp(
home: Scaffold(
appBar: ownAppBar(_selectedPage),
body: _bodyOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedPage,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
)
),
);
final List<Widget> _bodyOptions = [
HomePage(),
CookRecipe(),
];
You don't need to use Navigator to change pages, I modified your code just try.
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(home: PageNavigationBar()));
}
class PageNavigationBar extends StatefulWidget {
#override
_PageNavigationBarState createState() => _PageNavigationBarState();
}
class _PageNavigationBarState extends State<PageNavigationBar> {
//default page showing in bottom navigation bar will be CookRecipe()
int _selectedPage = 1;
//all pages optional in bottom navigation bar
final List<Widget> _pageOptions = [
HomePage(),
CookRecipe(),
];
void onTapped(int pageTapped) {
setState(() {
//print(pageTapped);
_selectedPage = pageTapped;
// Navigator.push(context, MaterialPageRoute(builder: (context) => _pageOptions[pageTapped]));
//print(_selectedPage);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _pageOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
//TODO: currentIndex: doesn't update when the state updates, why?
currentIndex: _selectedPage,
//items showing in bottom navigation bar
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Homepage'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search recipe'),
),
],
onTap: (int pageTapped) {
onTapped(pageTapped);
},
),
);
}
}
class CookRecipe extends StatefulWidget {
#override
_CookRecipeState createState() => _CookRecipeState();
}
class _CookRecipeState extends State<CookRecipe> {
#override
Widget build(BuildContext context) {
return Center(
child: Text('Search recipes'),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Center(
child: Text('Home page'),
);
}
}

Flutter/Dart: Navigator routes always take me to home screen with the selectedIndex = 0

I am having an issue within my app where when I navigate to a screen within my HomeScreen, e.g Navigator.of(context).push_________(Screen.routeName) and click back on the app bar, it always takes me to the HomeScreen with the selectedIndex of the HomeScreen equal to 0. This might be an easy solution I'm fairly new to programming. I believe it has something to do with the fact that selectedValue is initialized to 0 in my HomeScreen<State> class.
Here's my code. I think I just need to make that value depends on where I navigate BACK from..(I want to go back to whatever index I Navigated from.
For example, if I am on _selectedIndex = 2, and I click to go into a screen within _selectedIndex = 2 when I click the back button, I want to go back to the HomeScreen but with _selectedIndex = 2
class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0; <--------------------------
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions = <Widget>[
Screen1(), //index 0
Screen2(), //index 1
Screen3(), //index 2
Screen4(), //index 3
Screen5(), //index 4
];
#override
Widget build(BuildContext context) {
final authData = Provider.of<Auth>(context, listen: true);
final filters = Provider.of<Filters>(context, listen: true);
return Scaffold(
appBar: AppBar(
body: Center(
child:
_widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.black,
elevation: 0,
iconSize: 22,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home,
color: _selectedIndex == 0 ? Colors.greenAccent : Colors.grey,),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.home,
color: _selectedIndex == 1 ? Colors.greenAccent : Colors.grey,),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.home,
color: _selectedIndex == 2 ? Colors.greenAccent : Colors.grey,),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.home,
color: _selectedIndex == 3 ? Colors.greenAccent : Colors.grey,),
title: Text(''),
),
BottomNavigationBarItem(
icon: Icon(Icons.home,
color: _selectedIndex == 4 ? Colors.greenAccent : Colors.grey,),
title: Text(''),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.greenAccent,
onTap: _onItemTapped,
),
I navigate from _selectedIndex = 2 (the third tab) to a screen within _selectedIndex = 2 like this
Navigator.of(context).pushNamed(ChatScreen.routeName);
And then from that screen when I click the back button on the appBar which onPressed is defined as
leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: () {
Navigator.pop(context);
} ),
It takes me back to the HomeScreen but with selectedIndex = 0. I want to go back to selectedIndex = 2.
Can you please share us your _onItemTapped method?
If you're just using Navigator.push, Navigator.pushNamed or navigating without disposing the previous route, then using Navigator.pop() alone should do the job. Exiting the current route whilst persisting the previous route's state.
However, since you are already using provider, I suggest using it all the way for handling screen wide or global states.
Here's an example how you can achieve that:
main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class AppNotifier extends ChangeNotifier {
var selectedIndex = 0;
void changeSelectedIndexPage(int index) {
selectedIndex = index;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => AppNotifier(),
),
],
child: MaterialApp(
home: HomeScreen(),
),
);
}
}
class HomeScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _HomeScreenState();
}
}
class _HomeScreenState extends State<HomeScreen> {
static List<Widget> _childWidgets = <Widget>[
HomePage(),
SettingsPage(),
];
#override
Widget build(BuildContext context) {
AppNotifier _appNotifier = Provider.of<AppNotifier>(context);
return Scaffold(
body: _childWidgets.elementAt(_appNotifier.selectedIndex),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _appNotifier.selectedIndex,
onTap: (int index) {
_appNotifier.changeSelectedIndexPage(index);
},
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
),
title: Text("Home"),
),
BottomNavigationBarItem(
icon: Icon(
Icons.settings,
),
title: Text("Settings"),
),
],
),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => JustAnotherNewScreen(),
),
);
},
child: Text("Open new page"),
),
),
);
}
}
class SettingsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Settings"),
),
body: Center(
child: RaisedButton(
onPressed: () {
// Let's create a new instance of the other screen
// And destroy home's screen instance
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => JustAnotherNewScreen(),
),
);
},
child: Text("Open new page"),
),
),
);
}
}
class JustAnotherNewScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
// Navigator.pop(context);
// Let's create a new instance of the home page
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => HomeScreen(),
),
);
},
),
),
body: Center(
child: Text("Just another new page"),
),
);
}
}

Is it possible for me to choose to show or hide bottom navigation bar when I move to new page with navigator in flutter?

everyone.
I'm making an app which has bottom navigation bar with two items, and each item has buttons to move new pages.
Let's say each of those item is called for A and B.
A has a button for moving to new Page C. C shows today's weather. And I want to see bottom navigation bar in C as well.
B also has a button for moving to new Page D. D is login page. And I don't want to see bottom navigation bar in D.
I tried to use IndexedStack and GlobalKey, and it did work for showing bottom navigation bar in C. But I failed to hide bottom navigation bar with it in D.
I also read many articles here and there but never worked.
Can anybody help me?
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _currentTab;
List<Widget> _tabList = [
FirstTab(),
SecondTab()
];
#override
void initState() {
super.initState();
_currentTab = 0;
}
void onItemTapped(int index) {
setState(() {
_currentTab = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _tabList[_currentTab],
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today),
title: Text('Weather')
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Login')
)
],
onTap: onItemTapped,
currentIndex: _currentTab,
),
);
}
}
class FirstTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => WeatherPage()));
},
child: Text('To see the weather today'),
),
),
);
}
}
class SecondTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()));
},
child: Text('To Login'),
),
),
);
}
}
class WeatherPage extends StatelessWidget { // This page needs bottom navigation bar
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Rainy'),
),
);
}
}
class LoginPage extends StatelessWidget { // There is no bottom navigation bar on this page
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Click to login'),
),
);
}
}
Edit:
Have a new bottomNavbar in the WeatherPage (first solution in comment section):
import 'package:flutter/material.dart';
class StackOverflow2 extends StatefulWidget {
#override
_StackOverflow2State createState() => _StackOverflow2State();
}
class _StackOverflow2State extends State<StackOverflow2> {
int _currentTab;
List<Widget> _tabList = [FirstTab(), SecondTab()];
#override
void initState() {
super.initState();
_currentTab = 0;
}
void onItemTapped(int index) {
setState(() {
_currentTab = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _tabList[_currentTab],
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today), title: Text('Weather')),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Login'))
],
onTap: onItemTapped,
currentIndex: _currentTab,
),
);
}
}
class WeatherPage extends StatefulWidget {
// Th
#override
_WeatherPageState createState() => _WeatherPageState();
}
class _WeatherPageState extends State<WeatherPage> {
int _currentTab;
Widget myCenter = Center(
child: Text('Rainy'),
);
List<Widget> _tabList;
#override
void initState() {
super.initState();
_tabList = [myCenter, SecondTab()];
_currentTab = 0;
}
void onItemTapped(int index) {
setState(() {
_currentTab = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _tabList[_currentTab],
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.calendar_today), title: Text('Weather')),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Login'))
],
onTap: onItemTapped,
currentIndex: _currentTab,
),
);
}
}
class FirstTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => WeatherPage()));
},
child: Text('To see the weather today'),
),
),
);
}
}
class SecondTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginPage()));
},
child: Text('To Login'),
),
),
);
}
}
class LoginPage extends StatelessWidget {
// There is no bottom navigation bar on this page
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Click to login'),
),
);
}
}