I am trying to apply persistent_bottom_nav_bar but I keep getting error. I got similar answers and tried to follow https://pub.dev/packages/persistent_bottom_nav_bar
These are the errors that I keep getting.
The method '_BottomBarState' isn't defined for the type 'BottomBar'. & 1 positional argument(s) expected, but 0 found.
class BottomBar extends StatefulWidget {
const BottomBar({Key? key}) : super(key: key);
#override
State<BottomBar> createState() => _BottomBarState();
}
PersistentTabController _controller = PersistentTabController(initialIndex: 0);
//Screens for each nav items.
List<Widget> _NavScreens() {
return [
HomeScreen(),
const Text("History"),
];
}
List<PersistentBottomNavBarItem> _navBarsItems() {
return [
PersistentBottomNavBarItem(
icon: Icon(FluentSystemIcons.ic_fluent_home_regular),
title: "Home",
activeColorPrimary: Colors.blueGrey,
),
PersistentBottomNavBarItem(
icon: Icon(Icons.favorite),
title: ("History"),
activeColorPrimary: CupertinoColors.activeGreen,
),
];
}
#override
Widget build(BuildContext context) {
return Center(
child: PersistentTabView(
controller: _controller,
screens: _NavScreens(),
items: _navBarsItems(),
confineInSafeArea: true,
backgroundColor: Colors.white,
handleAndroidBackButtonPress: true,
resizeToAvoidBottomInset: true,
hideNavigationBarWhenKeyboardShows: true,
decoration: NavBarDecoration(
borderRadius: BorderRadius.circular(10.0),
),
popAllScreensOnTapOfSelectedTab: true,
navBarStyle: NavBarStyle.style9,
),
);
}
This is the original bottom bar that I want to keep fixed in all screens
class _BottomBarState extends State<BottomBar> {
int _selectedIndex = 0;
static final List<Widget> _widgetOptions = <Widget>[
HomeScreen(),
const Text("History"),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
//print('Tapped index is: ${_selectedIndex}');
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions[_selectedIndex],
),
bottomNavigationBar: Column(
mainAxisSize: MainAxisSize.min,
children: [
BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: _onItemTapped,
...............................
items: const [
BottomNavigationBarItem(
icon: Icon(FluentSystemIcons.ic_fluent_home_regular),
label: "Home"),
BottomNavigationBarItem(
icon: Icon(FluentSystemIcons.ic_fluent_history_regular),
label: "History"),
],),],),);}}
How to apply presistent bottom bar to my project without changing the design? Why am I reciving this error and how to fix it.
persistent_bottom_nav_bar.dart
import 'package:flutter/material.dart';
import 'bottom_nav_bar.dart';
class MyPersistentBottomNavBar extends StatelessWidget {
const MyPersistentBottomNavBar({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Persistent Bottom Nav Bar',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple),
home: const BottomNavBar(),
);
}
}
bottom_nav_bar.dart :
import 'package:flutter/material.dart';
import 'package:persistent_bottom_nav_bar_v2/persistent-tab-view.dart';
import 'pages/home_page.dart';
import 'pages/explore_page.dart';
import 'pages/add_page.dart';
import 'pages/inbox_page.dart';
import 'pages/shopping_page.dart';
class BottomNavBar extends StatelessWidget {
const BottomNavBar({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
PersistentTabController controller;
controller = PersistentTabController(initialIndex: 0);
List<Widget> _buildScreens() {
return [
const HomePage(),
const ExplorePage(),
const AddPage(),
const InboxPage(),
const ShoppingPage(),
];
}
List<PersistentBottomNavBarItem> _navBarsItems() {
return [
PersistentBottomNavBarItem(
icon: const Icon(Icons.home),
title: ("Home"),
activeColorPrimary: Colors.deepPurple,
inactiveColorPrimary: Colors.grey,
),
PersistentBottomNavBarItem(
icon: const Icon(Icons.explore),
title: ("Explore"),
activeColorPrimary: Colors.deepPurple,
inactiveColorPrimary: Colors.grey,
),
PersistentBottomNavBarItem(
icon: const Icon(Icons.add, color: Colors.white),
activeColorPrimary: Colors.deepPurple,
inactiveColorPrimary: Colors.grey,
),
PersistentBottomNavBarItem(
icon: const Icon(Icons.email),
title: ("Inbox"),
activeColorPrimary: Colors.deepPurple,
inactiveColorPrimary: Colors.grey,
),
PersistentBottomNavBarItem(
icon: const Icon(Icons.shopping_bag),
title: ("Shop"),
activeColorPrimary: Colors.deepPurple,
inactiveColorPrimary: Colors.grey,
),
];
}
return PersistentTabView(
context,
controller: controller,
screens: _buildScreens(),
items: _navBarsItems(),
confineInSafeArea: true,
backgroundColor: Colors.white, // Default is Colors.white.
handleAndroidBackButtonPress: true, // Default is true.
resizeToAvoidBottomInset:
true, // This needs to be true if you want to move up the screen when keyboard appears. Default is true.
stateManagement: true, // Default is true.
hideNavigationBarWhenKeyboardShows:
true, // Recommended to set 'resizeToAvoidBottomInset' as true while using this argument. Default is true.
decoration: NavBarDecoration(
borderRadius: BorderRadius.circular(10.0),
colorBehindNavBar: Colors.white,
),
popAllScreensOnTapOfSelectedTab: true,
popActionScreens: PopActionScreensType.all,
itemAnimationProperties: const ItemAnimationProperties(
// Navigation Bar's items animation properties.
duration: Duration(milliseconds: 200),
curve: Curves.ease,
),
screenTransitionAnimation: const ScreenTransitionAnimation(
// Screen transition animation on change of selected tab.
animateTabTransition: true,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
),
navBarStyle:
NavBarStyle.style15, // Choose the nav bar style with this property.
);
}
}
Please see code for other pages from the GitHub URL below:
https://github.com/md-siam/package_of_the_day/tree/master/lib/51_persistent_bottom_nav_bar/pages
I have tried this code.It runs fine, can you please try?
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:minawill/ui/home/home.dart';
class BottomBar extends StatefulWidget {
const BottomBar({Key? key}) : super(key: key);
#override
State<BottomBar> createState() => _BottomBarState();
}
class _BottomBarState extends State<BottomBar> {
int _selectedIndex = 0;
static final List<Widget> _widgetOptions = <Widget>[
HomeScreen(),
const Text("History"),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
//print('Tapped index is: ${_selectedIndex}');
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions[_selectedIndex],
),
bottomNavigationBar: Column(
mainAxisSize: MainAxisSize.min,
children: [
BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: "Home"),
BottomNavigationBarItem(
icon: Icon(Icons.phone),
label: "History"),
],),],),);}
}
i have added a photo of my output.Please check
Related
I have a homepage that includes an AppBar a bottomnavbar and a body to which I pass a list of widgets (pages) I want the navbar to navigate to when I click on its icons. I want to be able to display my bottomnavbar even in pages that are not included in the list .
Example when I click on a list tile it takes me to another details page , my navbar disappears I want the whole home page (appbar, bottomnavbar,...) to be static throughout the whole app without having to call each component on its own in my pages just like instagram style.
Here's my home page
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
var pages = [
MyQrqc(),
NoDataUI(),
];
int index = 0;
var _appPageController = PageController();
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: PreferredSize(
preferredSize: Size.fromHeight(70.0), child: CustomAppBar()),
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"),
fit: BoxFit.cover,
),
),
child: PageView(
children: pages,
onPageChanged: (index) {
setState(() {
index = index;
});
},
controller: _appPageController,
),
),
bottomNavigationBar: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(17.0),
topRight: Radius.circular(17.0),
),
child: BottomAppBar(
clipBehavior: Clip.antiAlias, //bottom navigation bar on scaffold
color: Colors.transparent,
shape: CircularNotchedRectangle(), //shape of notch
notchMargin:
5, //notche margin between floating button and bottom appbar
child: Mainmenu(currentIndex: index, appPageController: _appPageController,),
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: kPrimaryLightColor,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyQrqc()),
);
},
child: const Icon(Icons.add),
),
),
);
}
}
and this is my main menu page :
import 'package:deepnrise/Screens/qrqc/mes_qrqc_view.dart';
import 'package:deepnrise/constants/colors.dart';
import 'package:deepnrise/services/auth_services.dart';
import 'package:deepnrise/utils/size_config.dart';
import 'package:flutter/material.dart';
import 'package:deepnrise/services/settings/settings_service.dart';
import 'package:flutter_svg/flutter_svg.dart';
class Mainmenu extends StatefulWidget {
int currentIndex = 0;
var appPageController = PageController();
Mainmenu({Key? key, required this.currentIndex,required this.appPageController}) : super(key: key);
#override
CustomNavBar createState() => CustomNavBar();
}
class CustomNavBar extends State<Mainmenu> {
#override
Widget build(BuildContext context) {
setBottomBarIndex(index) {
setState(() {
widget.currentIndex = index;
});
widget.appPageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
}
SizeConfig.init(context);
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [kPrimaryColor, kPrimaryLightColor],
begin: Alignment.topLeft,
end: Alignment.topRight,
stops: [0.1, 0.8],
tileMode: TileMode.clamp,
),
),
child: Wrap(
//children inside bottom appbar
alignment: WrapAlignment.spaceAround,
children: <Widget>[
const SizedBox(
width: 30,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon2.png"),
onPressed: () {
setBottomBarIndex(0);
},
),
const SizedBox(
width: 20,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon1.png"),
onPressed: () {
setBottomBarIndex(1);
},
),
const SizedBox(
width: 50,
),
IconButton(
icon: const Icon(
Icons.person,
color: Colors.white,
),
onPressed: () {
setBottomBarIndex(2);
},
),
const SizedBox(
width: 20,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon3.png"),
onPressed: () {
setBottomBarIndex(3);
},
),
const SizedBox(
width: 20,
),
],
),
);
}
}
Here, First you need to create one file for BottomNavigationBar,
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
//For changing the screen
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
//This is a screens list which you want to navigate through BottomNavigationBar
final List<Widget> _children = [
const HomeScreen(),
const ProfileScreen()
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
iconSize: 32.0,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white54,
currentIndex: _selectedIndex,
backgroundColor: Colors.black,
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
label: "Home",
icon: Icon(Icons.list),
),
BottomNavigationBarItem(
label: "Profile",
icon: Icon(Icons.person),
),
],
onTap: _onItemTapped,
),
);
}
}
Then, You can create another screens like HomeScreen, ProfileScreen etc.
So, By using this code HomePage to be static throughout the whole app without having to call each component in any screen.
To show the bottom navbar on all screens, one way is to use PageView with the bottom navbar. Another way is to use persistent_bottom_nav_bar
I have used NestedScrollView and SliverAppBar to hide app bar when scrolling. In the body of NestedScrollView, I have CustomScrollView with a PageStorageKey but when I have switched back to events tab, scroll position is lost. I cannot understand it. Could you please help me?
home_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:liveitup/app/screens/HomeScreen/drawer_icon.dart';
import 'package:liveitup/app/screens/HomeScreen/drawer_page.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/bottom_navigation.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/tab_item.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/tab_navigators/event_tab_navigator.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/tab_navigators/message_tab_navigator.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/tab_navigators/notification_tab_navigator.dart';
import 'package:liveitup/blocs/UserBloc/bloc.dart';
import '../../../constants.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var _currentTab = TabItem.events;
void _selectTab(TabItem tabItem) {
setState(() => _currentTab = tabItem);
}
#override
Widget build(BuildContext context) {
var scaffoldKey = GlobalKey<ScaffoldState>();
UserBloc _userBloc = BlocProvider.of<UserBloc>(context);
return Scaffold(
backgroundColor: Colors.blue,
drawer: DrawerPage(),
key: scaffoldKey,
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 0,
pinned: false,
floating: true,
forceElevated: innerBoxIsScrolled,
backgroundColor: Colors.green,
leading: GestureDetector(
onTap: () => scaffoldKey.currentState?.openDrawer(),
child: const DrawerIcon()),
title: const Center(
child: Text(app_name),
),
actions: [
//Icon(Icons.search),
(_currentTab == TabItem.events)
? Icon(Icons.filter)
: Container(),
],
),
];
},
body: Builder(builder: (BuildContext context) {
if (_currentTab == TabItem.events) {
return CustomScrollView(
key: const PageStorageKey<TabItem>(TabItem.events),
slivers: [
SliverList(
delegate: SliverChildListDelegate([
for (var index = 1; index < 1000; index++)
Text(
index.toString(),
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 40.0,
letterSpacing: 2.0,
wordSpacing: 100.0,
),
),
])),
],
);
} else if (_currentTab == TabItem.messages) {
return const Center(
child: Text('message list'),
);
} else if (_currentTab == TabItem.notifications) {
return const Center(
child: Text('notitifcatiion list'),
);
}
return Text('notitifcatiion list');
}),
),
bottomNavigationBar: BottomNavigation(
currentTab: _currentTab,
onSelectTab: _selectTab,
),
);
}
}
tab_item.dart
import 'package:flutter/material.dart';
enum TabItem { events, messages, notifications }
const Map<TabItem, String> tabName = {
TabItem.events: 'events',
TabItem.messages: 'messages',
TabItem.notifications: 'notifications',
};
botom_navigation.dart
import 'package:flutter/material.dart';
import 'package:liveitup/app/screens/HomeScreen/tabs/tab_item.dart';
class BottomNavigation extends StatelessWidget {
BottomNavigation({required this.currentTab, required this.onSelectTab});
final TabItem currentTab;
final ValueChanged<TabItem> onSelectTab;
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: currentTab == TabItem.events ? Colors.black : Colors.grey,
),
label: tabName[TabItem.events],
),
BottomNavigationBarItem(
icon: Icon(
Icons.message,
color: currentTab == TabItem.messages ? Colors.black : Colors.grey,
),
label: tabName[TabItem.messages],
),
BottomNavigationBarItem(
icon: Icon(
Icons.notifications,
color: currentTab == TabItem.notifications
? Colors.black
: Colors.grey,
),
label: tabName[TabItem.notifications],
),
],
onTap: (index) => onSelectTab(
TabItem.values[index],
),
currentIndex: currentTab.index,
//selectedItemColor: Colors.black,
);
}
}
This is the code without error messages:
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => BottomNavigation();
}
/// This is the private State class that goes with MyStatefulWidget.
class BottomNavigation extends State<MyStatefulWidget> {
int _selectedIndex = 0;
List<Widget> _widgetOptions= <Widget>[
Text('Home'),
Text('Message')
];
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
void _onItemTapped(int index) {
setState(() {
_selectedIndex=index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {}),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage("assets/OptimizeYourFood/OptimizeYourFood2.png"),
fit: BoxFit.cover,
),
color: Colors.transparent)
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.local_dining),
label: 'Reduce',
),
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.recycle),
label: 'Reuse and recycle',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
[Nothing comes out of bottom navigation bar items][1]
..................................................................................................................................................................................................This is the end. This is the end. This is the end. This is the end. This is the end.
New Code
New Picture
You are changing the index but not the UI. use _widgetOptions on body. You can directly use body:_widgetOptions[_selectedIndex ] .
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => BottomNavigation();
}
/// This is the private State class that goes with MyStatefulWidget.
class BottomNavigation extends State<MyStatefulWidget> {
int _selectedIndex = 0;
List<Widget> _widgetOptions = <Widget>[Text('Home'), Text('Message')];
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
void _onItemTapped(int index) {
print("tapped $index");
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: Icon(Icons.search), onPressed: () {}),
],
),
body: Column(
children: [
_widgetOptions[_selectedIndex]
// Container(
// decoration: BoxDecoration(
// image: DecorationImage(
// image:
// AssetImage("assets/OptimizeYourFood/OptimizeYourFood2.png"),
// fit: BoxFit.cover,
// ),
// color: Colors.transparent)),
],
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.local_dining),
label: 'Reduce',
),
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
// Icon(FontAwesomeIcons.recycle),
label: 'Reuse and recycle',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
It will use the items array index.
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem( // <- index 0
icon: Icon(Icons.local_dining),
label: 'Reduce',
),
BottomNavigationBarItem( // <- index 1
icon: Icon(FontAwesomeIcons.recycle),
label: 'Reuse and recycle',
),
...
],
I am using footer menu to navigate som page aside the main home page which already has AppBar with a title, I want it to be overridden.
I want it, if I navigate from Home page to meditation page, I want the menu to overridden to "MEDITATION".
Here's my footer menu:
class Footer extends StatefulWidget {
// Footer({Key? key}) : super(key: key);
#override
_FooterState createState() => _FooterState();
}
class _FooterState extends State<Footer> {
var _selectedIndex = 0;
final pages = [
Dashboard(),
Health(),
Meditation(),
Sleep(),
Sounds(),
];
#override
void initState() {
super.initState();
_selectedIndex = 0;
}
#override
Widget build(BuildContext context) {
// return GestureDetector(
return Scaffold(
bottomNavigationBar: Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: dbShadowColor,
offset: Offset.fromDirection(3, 1),
spreadRadius: 1,
blurRadius: 5)
]),
child: Db5BottomNavigationBar(
items: <Db5BottomNavigationBarItem>[
Db5BottomNavigationBarItem(icon: db5_ic_home),
Db5BottomNavigationBarItem(icon: db5_ic_heart),
Db5BottomNavigationBarItem(icon: db5_ic_meditate),
Db5BottomNavigationBarItem(icon: db5_ic_sleep),
Db5BottomNavigationBarItem(icon: db5_ic_sounds),
],
currentIndex: _selectedIndex,
unselectedIconTheme: IconThemeData(color: db5_icon_color, size: 24),
selectedIconTheme: IconThemeData(color: db5_colorPrimary, size: 24),
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
},
type: Db5BottomNavigationBarType.fixed,
),
),
body: SafeArea(
child: pages[_selectedIndex],
),
);
// );
}
}
Here's my Meditation Page code:
class Meditation extends StatefulWidget {
Meditation({Key? key}) : super(key: key);
#override
_MeditationState createState() => _MeditationState();
}
class _MeditationState extends State<Meditation> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: appStore.scaffoldBackground,
centerTitle: true,
title: Text(
"Meditate",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20,
),
)),
body: Container(
alignment: Alignment.topLeft,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(),
child: text(
meditation_text_title,
),
)
],
),
),
),
);
}
}
This is how I rendered my footer on the main HOME PAGE:
return Scaffold(
appBar: AppBar(
backgroundColor: db5_white,
iconTheme: IconThemeData(color: sh_textColorPrimary),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
title: text(title,
textColor: sh_colorPrimary,
fontFamily: fontBold,
fontSize: textSizeNormal),
),
body: Stack(
children: <Widget>[
Dashboard(),
Footer(),
],
),
);
Am I doing it wrongly?
Here's how you should implement your screens.
// Name the class whatever you like
class ScreensController extends StatefulWidget {
const ScreensController({Key? key}) : super(key: key);
#override
_ScreensControllerState createState() => _ScreensControllerState();
}
class _ScreensControllerState extends State<ScreensController> {
int _selectedIndex = 0;
List<String> mainScreensTitles = [
'Dashboard',
'Health',
'Meditation',
'Sleep',
'Sounds'
];
List<Widget> screens= [
Dashboard(),
Health(),
Meditation(),
Sleep(),
Sounds(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
// Indexed stack is used to prevent page rebuilds when navigating between the
//screens
body: IndexedStack(
index: _selectedIndex,
children: screens,
),
bottomNavigationBar: BottomNavigationBar(
//Toggle these booleans if needed
showSelectedLabels: false,
showUnselectedLabels: false,
onTap: (newScreenIndex) {
setState(() {
_selectedIndex = newScreenIndex;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
label: mainScreensTitles[0],
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite_outline),
label: mainScreensTitles[1],
),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
label: mainScreensTitles[2],
),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
label: mainScreensTitles[3],
),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
label: mainScreensTitles[4],
),
],
currentIndex: _selectedIndex,
),
);
}
}
Implementation of some of your screens:
Dashboard & Meditation:
class Dashboard extends StatelessWidget {
const Dashboard({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dashboard'),
),
body: Center(child: Text('Dashboard coming soon')),
);
}
}
class Meditation extends StatelessWidget {
const Meditation({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Meditation'),
),
body: Center(child: Text('Meditation coming soon')),
);
}
}
I work on flutter and I make an app with 5 tabs, using a BottomNavigationBar, who change the currently displayed content.
When I tap on a tab, the content updates to the new content, but the tabs icon doesn't change.
I have tried to change the BottomNavigationBarType but that changes nothing...
here is base page widget:
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
#override
_Home createState() => _Home();
}
class _Home extends State<Home> {
int _selectedIndex = 0;
static List<Widget> _widgetOptions = <Widget>[
HomePage(),
CreateTrain(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
print(_selectedIndex);
return Scaffold(
body: _widgetOptions.elementAt(_selectedIndex),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0, // this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.assignment),
title: new Text('Training'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.play_arrow),
title: new Text('start'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.insert_chart),
title: new Text('Stats'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Profile'))
],
selectedFontSize: 12,
unselectedFontSize: 12,
selectedItemColor: Colors.amber[800],
unselectedItemColor: Colors.grey[500],
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
onTap: _onItemTapped,
),
);
}
}
Here is HomePage widget:
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: true,
title: const Text(
'Home',
style: TextStyle(
color: Colors.black,
fontSize: 30,
),
),
backgroundColor: _bgColor,
),
body: Text('data'),
);
}
}
Thanks for your help.
In your code
currentIndex: 0, // this will be set when a new tab is tapped
This should be
currentIndex: _selectedIndex, // this will be set when a new tab is tapped