Flutter - using routes in bottomnavigationbar - flutter

Im trying to navigate to next page via switch index, but it doesn't work.
Does anyone knows how should I use switch case? thank you
Below is my code:
child: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: _selectedIndex == 0
? SvgPicture.asset('assets/icons/home_colored.svg')
: SvgPicture.asset('assets/icons/home.svg'),
title: Text('Home', style: bottomTextStyle),
),
BottomNavigationBarItem(
icon: _selectedIndex == 1
? SvgPicture.asset('assets/icons/order_colored.svg')
: SvgPicture.asset('assets/icons/order.svg'),
title: Text(
'My Card',
style: bottomTextStyle,
),
),
BottomNavigationBarItem(
icon: _selectedIndex == 2
? SvgPicture.asset('assets/icons/watch_colored.svg')
: SvgPicture.asset('assets/icons/watch.svg'),
title: Text(
'Watch List',
style: bottomTextStyle,
),
),
BottomNavigationBarItem(
icon: _selectedIndex == 3
? SvgPicture.asset('assets/icons/account_colored.svg')
: SvgPicture.asset('assets/icons/account.svg'),
title: Text(
'Account',
style: bottomTextStyle,
),
),

In the below code "HomeScreen()" and "NotificationHome()" are the class name to which we need to navigate on tap."
class Bottom_Nav extends StatefulWidget {
const Bottom_Nav({Key? key}) : super(key: key);
#override
_Bottom_NavState createState() => _Bottom_NavState();
}
class _Bottom_NavState extends State<Bottom_Nav> {
int selectedPage = 0;
final _pageOptions = [
const HomeScreen(),
//const searchHome(),
NotificationHome(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: _pageOptions[selectedPage],
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home, size: 30), label: ('Home')),
BottomNavigationBarItem(
icon: Badge(
badgeContent: Text('3'),
child: Icon(Icons.notifications, size: 30)),
label: ("Notification")),
],
selectedItemColor: bottomBarSelected,
elevation: 5.0,
unselectedItemColor: bottomBarNotSelected,
currentIndex: selectedPage,
backgroundColor: Colors.white,
onTap: (index) {
setState(() {
selectedPage = index;
});
},
));
}
}
Comment if you have any doubt,
Thank you.

Try below code hope its help to you just add your images or icons instead of my answer Icons :
Go for documentation here
BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: _selectedIndex == 0 ? Icon(Icons.home) : Icon(Icons.add),
label: 'Home',
),
BottomNavigationBarItem(
icon: _selectedIndex == 1 ? Icon(Icons.business) : Icon(Icons.person),
label: 'Business',
),
BottomNavigationBarItem(
icon: _selectedIndex == 2 ? Icon(Icons.school) : Icon(Icons.close),
label: 'School'
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
Your result screen when your index is 0 ->
Your result screen when your index is 1 ->

Solution!
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyNavigationBar (),
);
}
}
class MyNavigationBar extends StatefulWidget {
MyNavigationBar ({Key key}) : super(key: key);
#override
_MyNavigationBarState createState() => _MyNavigationBarState();
}
class _MyNavigationBarState extends State<MyNavigationBar> {
int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
Text('Home Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
Text('Search Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
Text('Profile Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
if(__selectedIndex == 0){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => secondPage()),
);
} else if (__selectedIndex == 1){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => thirdPage()),
);
} else if (__selectedIndex == 2){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => fourthPage()),
);
} else if (__selectedIndex == 3){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => firstPage()),
);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter BottomNavigationBar Example'),
backgroundColor: Colors.green
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[l̥
BottomNavigationBarItem(
icon: _selectedIndex == 0
? SvgPicture.asset('assets/icons/home_colored.svg')
: SvgPicture.asset('assets/icons/home.svg'),
title: Text('Home', style: bottomTextStyle),
),
BottomNavigationBarItem(
icon: (_selectedIndex == 1)
? SvgPicture.asset('assets/icons/order_colored.svg')
: SvgPicture.asset('assets/icons/order.svg'),
title: Text(
'My Card',
style: bottomTextStyle,
),
),
BottomNavigationBarItem(
icon: (_selectedIndex == 2)
? SvgPicture.asset('assets/icons/watch_colored.svg')
: SvgPicture.asset('assets/icons/watch.svg'),
title: Text(
'Watch List',
style: bottomTextStyle,
),
),
BottomNavigationBarItem(
icon: (_selectedIndex == 3)
? SvgPicture.asset('assets/icons/account_colored.svg')
: SvgPicture.asset('assets/icons/account.svg'),
title: Text(
'Account',
style: bottomTextStyle,
),
),
],
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
selectedItemColor: Colors.black,
iconSize: 40,
onTap: _onItemTapped,
elevation: 5
),
);
}
}
Replace secondPage(), thirdPage(), fourthPage(), firstPage() with class names to which you want to navigate and provide arguments if you have any?..
example: secondPage('Second Page Title')
Comment if you have any doubts, Thank you.

Related

Flutter- how to navigate different pages by curved navigation bar

i am creating a flutter app and want help on how to navigate to different pages. Also, when i tap on buttons of curved navigation bar nothing happens the icons not changing.
can u please help me out?
here is my code for the curved navigation bar
Thank u
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
class BAR extends StatefulWidget {
const BAR({super.key});
#override
State<BAR> createState() => _BARState();
}
class _BARState extends State<BAR> {
#override
Widget build(BuildContext context) {
return CurvedNavigationBar(
backgroundColor: HexColor("#F7ECCD"),
color: HexColor("#AE621C"),
items: [
Icon(
Icons.home,
color: Colors.white,
size: 30,
),
Icon(
Icons.favorite,
color: Colors.white,
size: 30,
),
Icon(
Icons.settings,
color: Colors.white,
size: 30,
)
],
onTap: (index){
setState(() {
if (index == 0) {
Navigator.pushNamed(context, '/');
}
if (index == 1) {
Navigator.pushNamed(context, '/one');
}
if (index == 2) {
Navigator.pushNamed(context, '/two');
}
});
},);
}
}
import 'package:flutter/cupertino.dart';
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.business),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.school),
title: Text('School'),
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
backgroundColor: CupertinoColors.systemGrey,
activeColor: CupertinoColors.black,
),
tabBuilder: (BuildContext context, int index) {
return CupertinoTabView(
builder: (BuildContext context) {
return CupertinoPageScaffold(
child: Center(
child: _widgetOptions.elementAt(index),
),
);
},
);
},
);
}
}

How to add scroll into bottom navigation bar items

I have implemented an app that navigates through a few screens. I have added the bottom navigation bar and 1st tab I add a page with list view items with sqlflite data.I can't scroll list view data. other tabs I have added to show another screen.
code is below.
//this is my homepage screen
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late List<LeaveModel> _leaveList = [];
final _userService = LeaveService();
int _selectedIndex = 0;
#override
void initState() {
getAllUserDetails();
super.initState();
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
I have create botom navigation bar with 4 item.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {},
),
title: const Text('Leave Tracker'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.add_box),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AddLeave()))
.then((data) {
if (data != null) {}
getAllUserDetails();
});
},
)
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.man),
label: 'All',
),
BottomNavigationBarItem(
icon: Icon(Icons.sick_rounded),
label: 'Sick',
),
BottomNavigationBarItem(
icon: Icon(Icons.holiday_village),
label: 'Casual',
),
BottomNavigationBarItem(
icon: Icon(Icons.weekend),
label: 'Other',
),
],
),
From this 4 items goto different 3 screens.1st item link to same page.(HomePage())
body: Center(
child: _selectedIndex == 0
? myListView(context)
: _selectedIndex == 1
? AllSickLeave()
: _selectedIndex == 2
? AllCasualLeave()
: ViewOtherLeave(),
),
);
}
In HomePage() i have add listview and data taking from sqlflite database.
getAllUserDetails() async {
var users = await _userService.readAllLeave();
_leaveList = <LeaveModel>[];
users.forEach((leave) {
setState(() {
var leaveModel = LeaveModel();
leaveModel.id = leave['id'];
leaveModel.leaveType = leave['leaveType'];
leaveModel.leaveStartDate = leave['leaveStartDate'];
leaveModel.leaveEndDate = leave['leaveEndDate'];
leaveModel.reason = leave['reason'];
leaveModel.leaveDays = leave['leaveDays'];
_leaveList.add(leaveModel);
});
});
}
Widget myListView(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 5.0,
),
Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
ListView.builder(
shrinkWrap: true,
itemCount: _leaveList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
'Leave Type : ${_leaveList[index].leaveType ?? ''}'),
subtitle: Text('Reason : ${_leaveList[index].reason}'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: () {},
icon: Icon(
Icons.edit,
color: Colors.teal,
)),
IconButton(
onPressed: () {},
icon: Icon(
Icons.delete,
color: Colors.red,
)),
],
),
),
);
}),
],
),
),
);
}
}
You dont need to have multiple scaffold, and try this format
Widget myListView(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.only(top: 25),
itemCount: _leaveList.length + 1,
itemBuilder: (context, index) {
if (index == 0)
return Text(
'All Leave Details',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
);
return Card(
child: ListTile(

Flutter BottomNavigationBar stackoverflow

i'm starting with Flutter and i'm struggling with the navigationBar, if i add the body i keep getting a stackOverflow.
If i don't add the body everything is fine.
Error:
The following StackOverflowError was thrown building DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(blackMountainView bodyText2), inherit: false, color: Color(0xdd000000), family: Roboto, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip):
Stack Overflow
The relevant error-causing widget was:
Scaffold Scaffold:file:///Users/salvatorelafiura/git/energy_flutter/lib/screen/main.dart:104:12
When the exception was thrown, this was the stack:
#0 new Uint8List (dart:typed_data-patch/typed_data_patch.dart:2201:3)
#1 _createTables.<anonymous closure> (dart:core/uri.dart:3872:60)
#2 new _GrowableList.generate (dart:core-patch/growable_array.dart:133:28)
Code of the current widget, 3 screens one bottomNavigation.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widgetTitle.elementAt(selectedIndex)),
actions: <Widget>[
IconButton(
icon: const Icon(
Icons.logout,
color: Colors.white,
),
onPressed: () {
signOut();
},
)
],
),
body: Center(
child: IndexedStack(index: selectedIndex, children: tabPages),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), label: "Pratica"),
BottomNavigationBarItem(icon: Icon(Icons.mail), label: "Messages"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "Profilo"),
],
currentIndex: selectedIndex,
onTap: onItemTapped,
backgroundColor: Colors.white,
fixedColor: Colors.blue,
selectedLabelStyle: const TextStyle(color: Colors.red, fontSize: 20),
unselectedFontSize: 16,
selectedIconTheme:
const IconThemeData(color: Colors.blue, opacity: 1.0, size: 30.0),
unselectedItemColor: Colors.grey,
unselectedLabelStyle: const TextStyle(fontSize: 18, color: Colors.pink),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Create a Separate Class "Bottom" and Place the whole code of your Bottomnavigationbar inside that class then at every Screen just Call inside the Scaffold like:
bottomNavigationBar: Bottom();
Then Declare your int selectedIndex = 0; Globally
it will works fine.
Modify the Given code:
import 'package:flutter/material.dart';
int _selectedIndex = 0;
class Bottom extends StatefulWidget {
#override
_BottomState createState() => _BottomState();
}
class _BottomState extends State<Bottom> {
#override
Widget build(BuildContext context) {
return BottomNavigationBar(
showSelectedLabels: true, // <-- HERE
showUnselectedLabels: true,
backgroundColor: Color(0xff38547C),
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
selectedItemColor: Color(0xFF1C2834),
unselectedItemColor: Colors.white,
items: [
BottomNavigationBarItem(
icon: const Icon(
Icons.home,
),
label: "Home",
),
BottomNavigationBarItem(
icon: ImageIcon(
AssetImage("assets/images/ball.png"),
),
label: "Matches",
),
BottomNavigationBarItem(
icon: const Icon(
Icons.live_tv,
),
label: "Live"),
BottomNavigationBarItem(
icon: Icon(
Icons.poll,
),
label: "Ranking"),
BottomNavigationBarItem(
icon: Icon(
Icons.more_horiz,
),
label: "More"),
],
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
if (_selectedIndex == 0) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Home());
Navigator.of(context).push(route);
} else if (_selectedIndex == 1) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Matches());
Navigator.of(context).push(route);
} else if (_selectedIndex == 2) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Live());
Navigator.of(context).push(route);
} else if (_selectedIndex == 3) {
var route =
MaterialPageRoute(builder: (BuildContext context) => Ranking());
Navigator.of(context).push(route);
} else if (_selectedIndex == 4) {
var route =
MaterialPageRoute(builder: (BuildContext context) => More());
Navigator.of(context).push(route);
}
});
}
}

How to toggle visibility of TabBar with Bottom Navigation Items in Flutter

I have a bottomNavigationBar and an AppBar in my flutter app. At the bottom of the AppBar is a TabBar consisting of two items. So I want the TabBar to be invisible when some items of the BottomNavigationBar is clicked. I tried to assign the Visibility class to my TabBar with a Boolean variable but it doesn't work. It seems like I can't handle the TabBar widget separately.
How do resolve this?
class DashBoardPage extends StatefulWidget {
#override
_DashBoardPageState createState() => _DashBoardPageState();
}
class _DashBoardPageState extends State<DashBoardPage> {
SharedPreferences sharedPreferences;
bool showTabs = false;
int tabsIndex = 0;
int _currentIndex = 0;
String _appBarText = "Welcome, User";
Widget callPage(int currentIndex) {
switch (currentIndex) {
case 0:
showTabs = true;
_appBarText = "Welcome, User";
return TabBarView(
children:[
new HomePage(),
new SchedulePage()
]
);
break;
case 1:
showTabs = false;
break;
case 2:
showTabs = false;
break;
default:
return HomePage();
}
}
#override
void initState() {
super.initState();
checkLoginState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MAF Mentor',
debugShowCheckedModeBanner: false,
home: DefaultTabController(
length: choices.length,
child: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFFFFFFFF),
title: Text(
_appBarText,
style: TextStyle(
color: Color(0xFF1C2447),
fontFamily: 'Muli',
fontSize: 16.0,
),
),
bottom: showTabs? TabBar(
isScrollable: true,
tabs: choices.map<Widget>((Choice choice) {
return Tab(
text: choice.title,
icon: Icon(choice.icon),
);
}).toList(),
labelColor: Color(0xFF1C2447),
):null,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.account_circle,
color: Color(0xFF1C2447),
),
onPressed: () {
Navigator.of(context).pushNamed('/profile_page');
},
),
IconButton(
icon: Icon(
Icons.notifications,
color: Color(0xFF1C2447),
),
onPressed: () {
// do something
},
),
],
), //AppBar
body: callPage(_currentIndex),
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
fixedColor: Color(0xFF1C2447),
currentIndex: _currentIndex,
onTap: (value) {
_currentIndex = value;
callPage(_currentIndex);
setState(() {
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text("Bar 1")),
BottomNavigationBarItem(
icon: Icon(Icons.people), title: Text("Bar 2")),
BottomNavigationBarItem(
icon: Icon(Icons.history), title: Text("Bar 3"))
],
),
),
),
);
}
bottom requires a PreferredSizeWidget so you can not use the Visibility widget there. You can use a boolean variable to do that. You can see the whole code below. Since I don't know your choices and tabs I randomly put something. But the idea is if you want to show TabBar when user tap BottomNavigationBarItem
number 1 you just update your boolean variable as true. Otherwise make it false.
class TabBarExample extends StatefulWidget {
#override
_TabBarExampleState createState() => _TabBarExampleState();
}
class _TabBarExampleState extends State<TabBarExample> {
bool showTabs = false;
int selectedIndex = 0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFFFFFFFF),
title: Text(
'_appBarText',
style: TextStyle(
color: Color(0xFF1C2447),
fontFamily: 'Muli',
fontSize: 16.0,
),
),
bottom: showTabs
? TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(
text: 'Choice1',
icon: Icon(Icons.add_circle_outline),
),
Tab(
text: 'Choice1',
icon: Icon(Icons.add_circle),
),
],
labelColor: Color(0xFF1C2447),
)
: null,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text('first')),
BottomNavigationBarItem(
icon: Icon(Icons.favorite), title: Text('second')),
],
onTap: (index) {
if (index == 1) {
setState(() => showTabs = true);
} else {
setState(() => showTabs = false);
}
setState(() => selectedIndex = index);
},
),
),
);
}
}

Flutter: selected Icon on BottomNavigationBar doesn't change when tap

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