Navigation rail with flutter - flutter

The material design guidelines includes a component called Navigation rail.
How to create Navigation rail with flutter?

NavigationRail
A material widget that is meant to be displayed at the left or right of an app to navigate between a small number of views, typically between three and five.
SAMPLE CODE
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
debugShowCheckedModeBanner: false,
home: HomeWidget(),
);
}
}
class HomeWidget extends StatefulWidget {
HomeWidget({Key key}) : super(key: key);
#override
_HomeWidgetState createState() => _HomeWidgetState();
}
class _HomeWidgetState extends State<HomeWidget> {
int _selectedIndex = 0;
bool showNavigationBar = false;
var list = [
HomePage(),
WalkPage(),
LocationPage(),
NotificationPage(),
SettingsPage(),
SearchPage()
];
var title = [
"HomePage",
'WalkPage',
'LocationPage',
'NotificationPage',
'SettingsPage',
'SearchPage'
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title[_selectedIndex]),
centerTitle: false,
leading: IconButton(
icon: Icon(
Icons.menu,
color: Colors.white,
),
onPressed: () {
setState(() {
showNavigationBar = !showNavigationBar;
});
}),
),
body: Container(
child: SafeArea(
child: Stack(
children: <Widget>[
list[_selectedIndex],
Positioned(
top: 0,
left: 0,
child: Visibility(
visible: showNavigationBar,
child: Container(
height: MediaQuery.of(context).size.height,
child: NavigationRail(
selectedIndex: _selectedIndex,
elevation: 10,
backgroundColor: Colors.white,
leading: Container(
child: Center(child: Text('leading')),
),
trailing: Container(
child: Center(child: Text('trailing')),
),
selectedIconTheme: IconThemeData(color: Colors.purple, size: 30),
unselectedIconTheme: IconThemeData(color: Colors.grey, size: 20),
selectedLabelTextStyle:
TextStyle(color: Colors.purple, fontWeight: FontWeight.bold),
unselectedLabelTextStyle:
TextStyle(color: Colors.grey, fontWeight: FontWeight.normal),
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
showNavigationBar = !showNavigationBar;
});
},
labelType: NavigationRailLabelType.none,
destinations: [
NavigationRailDestination(
icon: Icon(Icons.home),
selectedIcon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.directions_walk),
selectedIcon: Icon(Icons.directions_walk),
label: Text('Walk'),
),
NavigationRailDestination(
icon: Icon(Icons.location_on),
selectedIcon: Icon(Icons.location_on),
label: Text('Location'),
),
NavigationRailDestination(
icon: Icon(Icons.notifications),
selectedIcon: Icon(Icons.notifications),
label: Text('Notifications'),
),
NavigationRailDestination(
icon: Icon(Icons.settings),
selectedIcon: Icon(Icons.settings),
label: Text('Settings'),
),
NavigationRailDestination(
icon: Icon(Icons.search),
selectedIcon: Icon(Icons.search),
label: Text('Search'),
),
],
),
),
),
),
],
)),
),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
child: Center(
child: Text('Home Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
class WalkPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
child: Center(
child: Text('Walk Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
class LocationPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.orange,
child: Center(
child: Text('Location Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
class NotificationPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: Center(
child: Text('Notification Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
class SettingsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.amber,
child: Center(
child: Text('Settings Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
class SearchPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.teal,
child: Center(
child: Text('Search Page',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0))),
);
}
}
Let us understand some of its important properties
selectedIndex - The index into destinations for the current selected NavigationRailDestination.
selectedIconTheme - The visual properties of the icon in the selected destination.
unselectedIconTheme
- The visual properties of the icon in the unselected destination.
selectedLabelTextStyle - The TextStyle of a destination's label when it is selected.
unselectedLabelTextStyle - The TextStyle of a destination's label when it is unselected.
backgroundColor - Sets the color of the container that holds all of the NavigationRail's contents.
leading - The leading widget in the rail that is placed above the destinations
trailing - The trailing widget in the rail that is placed below the destinations.
labelType
labelType: NavigationRailLabelType.all,
labelType: NavigationRailLabelType.selected,
labelType: NavigationRailLabelType.none,
OUTPUT
For more information please read the documentation of NavigationRail
You can test live demo here on NavigationRail demo

The latest version of Flutter 1.17 includes a built in NavigationRail component.
What is Navigation rail?
The rail is a side navigation component that displays three to seven app destinations and, optionally, a Floating Action Button. Each destination is represented by an icon and a text label. The rail can function on its own at larger screen sizes, such as desktop and tablet. When users transition between screen sizes and devices, the rail can also complement other navigation components, such as bottom navigation.
Example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
});
},
labelType: NavigationRailLabelType.selected,
destinations: [
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('First'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.book),
label: Text('Second'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),
],
),
VerticalDivider(thickness: 1, width: 1),
// This is the main content.
Expanded(
child: Center(
child: Text('selectedIndex: $_selectedIndex'),
),
)
],
),
);
}
}
Find a live demo here.
Here is the official documentation.

It was released on the 7th of May, 2020 with the Flutter 1.17 release. A quick search for "navigation rail flutter" would have done the trick.
The documentation includes a live demo and example code.
int _selectedIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
});
},
labelType: NavigationRailLabelType.selected,
destinations: [
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('First'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.book),
label: Text('Second'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),
],
),
VerticalDivider(thickness: 1, width: 1),
// This is the main content.
Expanded(
child: Center(
child: Text('selectedIndex: $_selectedIndex'),
),
)
],
),
);
}
To upgrade, run flutter upgrade, which will download the latest version from github.

Note: The navigation rail is meant for layouts with wide viewports, such as a desktop web or tablet landscape layout. For smaller layouts, like mobile portrait, a BottomNavigationBar should be used instead.
int _index = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: _index,
onDestinationSelected: (index) => setState(() => _index = index),
extended: true,
destinations: [
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
label: Text('First'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
label: Text('Second'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
label: Text('Third'),
),
],
),
// This is the main content.
Expanded(child: Center(child: Text('Index: $_index')))
],
),
);
}

NavigationRail looks neat. But I noticed there is no way to save the widget state so it always gets recreated. Not even AutomaticKeepAliveClientMixin works.

Related

Flutter : How to format the elements of the Bottom Navigation Bar and add colors and borders with radius

I want to make such a design, but I could not design the shopping cart icon in this format, how can I do it?
import 'package:flutter/material.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart ,), label:'',
backgroundColor: Colors.red,
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), label:''),
],
),
),
);
}
}
This is the code I tried to do, I couldn't format the basket icon as shown in the figma design image
Create and empty text with widget option list (_widgetOptions)
Create a BottomNavigationBarItem with empty label and in the icon widget, place container with BoxShape.circle decoration and use a custom icon of container child
Use selected and unselected item color property
In the _onItemTapped set a condition for the middle selection icon
See the full codes
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
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(
'',
),
Text(
'Index 3: School',
style: optionStyle,
),
Text(
'Index 4: Settings',
style: optionStyle,
),
];
void _onItemTapped(int index) {
if (index != 2) {
setState(() {
_selectedIndex = index;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
const BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
const BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Container(
height: 65,
width: 65,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
child: const Icon(
Icons.shopping_cart,
color: Colors.white,
),
),
label: '',
),
const BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
const BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue[800],
unselectedItemColor: Colors.black,
onTap: _onItemTapped,
),
);
}
}
I modified your code for the first BottomNavigationBarItem so it has red circular background:
BottomNavigationBarItem(
icon: Container(
height: 50,
width: 50,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: Icon(
Icons.shopping_cart,
color: Colors.white,
),
),
label: '',
),
You can change the values of height, width and color to match your needs.
Also, I would recommend adding these parameters to your BottomNavigationBar to center the icons (use it only if you are going to keep all of the labels as empty strings):
showSelectedLabels: false,
showUnselectedLabels: false,

How to put one image and text in one screen and leave the other screens with icons

I'm learning Flutter now and I'm not very handy yet. I have this problem:
basically I have created more screens and I can navigate through them thanks to a "bottomNavigationBar". Now the problem is I just don't know how to put an image and text on the Home screen but at the same time leave the icons on the other screens. I'm doing a project and now I need to do this thing.
I also need to know how to adjust this image (https://images.unsplash.com/photo-1604357209793-fca5dca89f97?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bWFwfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60") to the screen so that it stays between the AppBar and the bottomNavigationBar. (I now how to add images, I only need to know can it be fitted in the way I want).
(I leave here all the code that I written until now).
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Start Pages';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: StartPages(),
);
}
}
class StartPages extends StatefulWidget {
const StartPages({super.key});
#override
State<StartPages> createState() => StartPagesState();
}
class StartPagesState extends State<StartPages> {
int _selectedIndex = 2;
//static const TextStyle optionStyle =
//TextStyle(fontSize: 30, fontWeight: FontWeight.bold, color: Colors.white);
static const List<Widget> _widgetOptions = <Widget>[
Icon(
Icons.calendar_month,
size:150,
color: Colors.white,
),
Icon(
Icons.location_on,
size:150,
color: Colors.white,
),
Image(
image: NetworkImage('https://images.unsplash.com/photo-1604357209793-fca5dca89f97?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bWFwfGVufDB8fDB8fA%3D%3D&auto=format&fit=crop&w=500&q=60'),
),
Icon(
Icons.group,
size:150,
color: Colors.white,
),
Icon(
Icons.groups,
size:150,
color: Colors.white,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('FindASpot'),
backgroundColor: Colors.grey[900],
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
backgroundColor: Colors.grey[700],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedIconTheme: IconThemeData(color: Colors.amberAccent),
selectedLabelStyle: TextStyle(fontWeight: FontWeight.bold),
selectedItemColor: Colors.amberAccent,
items: const <BottomNavigationBarItem>[BottomNavigationBarItem(
icon: Icon(Icons.calendar_month),
label: 'Events',
backgroundColor: Colors.black45,
),
BottomNavigationBarItem(
icon: Icon(Icons.location_on),
label: 'Map',
backgroundColor: Colors.black45,
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.black45,
),
BottomNavigationBarItem(
icon: Icon(Icons.group),
label: 'Friends',
backgroundColor: Colors.black45,
),
BottomNavigationBarItem(
icon: Icon(Icons.groups),
label: 'Groups',
backgroundColor: Colors.black45,
),
],
currentIndex: _selectedIndex,
//selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

Change Container widget background color on press

I am trying to change the background color of my container widget inside the Expanded when a button is pressed in BottomNavigationBar.
I am using a list of color and a variable index to traverse the list front and back.
Even though I used setState(() {}), the color is not changing.
h(double x) and w(double x) are the methods that return the height or width of the screen times x using a media query.
Here is my code: the list:
List<Color> col = [Colors.grey, Colors.red, Colors.pink];
int index = 0;
BottomNavigationBar:
bottomNavigationBar: BottomAppBar(
child: Container(
color: Colors.orange,
height: h(0.07),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.white,
onPressed: () {
if (index == 0) {
} else {
setState(() {
index--;
});
}
},
),
Icon(
Icons.color_lens_rounded,
color: Colors.white,
),
IconButton(
icon: Icon(Icons.arrow_forward_ios),
color: Colors.white,
onPressed: () {
if (index == col.length - 1) {
} else {
setState(() {
index++;
});
}
},
),
],
),
),
),
Widget whose color has to be changed
Expanded(
child: Container(
color: col[index],
child: Column(
children: [],
),
),
)
run this code, then hope so you can modify as you want
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
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 Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

How to create a vertical fixed custom tab bar using container in flutter

I have to create a vertical left side fixed vertical bar, something like this
I have created using TabBar but there is a lot extra work that needs to be done. Like I have to remove the blur hover effect on it and then on click of tabBar item should display its corresponding content in the center and it should be scrollable, if content is more.
You can copy paste run full code below
You can use NavigationRail
You can change NavigationRailDestination's icon and selectedIcon
icon and selectedIcon accept widget, so you can use Column wrap icon and Text per your request
code snippet
NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
});
},
labelType: NavigationRailLabelType.selected,
destinations: [
NavigationRailDestination(
icon: Column(
children: [Icon(Icons.favorite_border), Text('Button 1')],
),
selectedIcon: Container(
color: Colors.green,
child: Column(
children: [Icon(Icons.favorite_border), Text('Button 1')],
),
),
label: Text(""),
),
NavigationRailDestination(
icon: Column(
children: [Icon(Icons.bookmark_border), Text('Button 2')],
),
selectedIcon: Column(
children: [Icon(Icons.book), Text('2 clicked')],
),
label: Text(''),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),
],
),
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
});
},
labelType: NavigationRailLabelType.selected,
destinations: [
NavigationRailDestination(
icon: Column(
children: [Icon(Icons.favorite_border), Text('Button 1')],
),
selectedIcon: Container(
color: Colors.green,
child: Column(
children: [Icon(Icons.favorite_border), Text('Button 1')],
),
),
label: Text(""),
),
NavigationRailDestination(
icon: Column(
children: [Icon(Icons.bookmark_border), Text('Button 2')],
),
selectedIcon: Column(
children: [Icon(Icons.book), Text('2 clicked')],
),
label: Text(''),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),
],
),
VerticalDivider(thickness: 1, width: 1),
// This is the main content.
Expanded(
child: Center(
child: Text('selectedIndex: $_selectedIndex'),
),
)
],
),
);
}
}

Flutter - Multi Page Navigation using bottom navigation bar icons

I'm trying to navigate to different pages within my app using the icons in my bottom navigation bar. I have tried many tutorials and can't seem to work out the best way to achieve this. I have created my Homepage (code below) and 2 additional pages, Inbox and Signin, both return simple scaffolds.
Firstly i'm interested to know if this is the best way to do what i'm trying to achieve and second, how can my code be altered to allow me to navigate to different pages depending on which icon is tapped. I'm aware that the code below doesn't execute, i'm just trying to show what i've tried.
My code:
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
_onTap(int index) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return _children[_currentIndex];
}));}
final List<Widget> _children = [
HomePage(),
InboxPage(),
SignInPage()
];
int _currentIndex = 0;
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
appBar: PreferredSize(preferredSize: Size(double.infinity, 75),
child: AppBar(
elevation: 0.0,
centerTitle: false,
title: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text(
currentDate,
textAlign: TextAlign.left,
style: TextStyle(
color: titleTextColor,
fontWeight: subTitleFontWeight,
fontFamily: titleFontFamily,
fontSize: subTitleFontSize),
),
),
SizedBox(
height: 15,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
'Some text here',
style: TextStyle(
color: titleTextColor,
fontWeight: titleTextFontWeight,
fontFamily: titleFontFamily,
fontSize: titleFontSize),
),
),
],
),
backgroundColor: kPrimaryColor,
shape: titleBarRounding
),
),
body: BodyOne(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Inbox'),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Account'),
)
],
onTap: () => _onTap(_currentIndex),
),);
}
}
Thanks in advance.
The screen you are in can't be part of the Screens you're navigating to and you don't need to push a new screen each time you just have to change selectedPage, this is an example of how it should look:
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int selectedPage = 0;
final _pageOptions = [
HomeScreen(),
InboxScreen(),
SignInScreen()
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: _pageOptions[selectedPage],
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home, size: 30), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.mail, size: 30), title: Text('Inbox')),
BottomNavigationBarItem(icon: Icon(Icons.account_circle, size: 30), title: Text('Account')),
],
selectedItemColor: Colors.green,
elevation: 5.0,
unselectedItemColor: Colors.green[900],
currentIndex: selectedPage,
backgroundColor: Colors.white,
onTap: (index){
setState(() {
selectedPage = index;
});
},
)
);
}
}
Let me know if you need more explanation.
The input parameter of the _onTap function is unused and needs to be deleted.
_onTap() {
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) => _children[_currentIndex])); // this has changed
}
In the onTap of the BottomNavigationBar you need to change the _currentIndex and then call the _onTap function which navigates to the selected screen.
onTap: (index) {
setState(() {
_currentIndex = index;
});
_onTap();
},
You can add this BottomNavigationBar to all of the screens, but pay attention to the initial value of the _currentIndex that changes according to the screen you're putting the BottomNavigationBar in.
Full code:
_onTap() { // this has changed
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) => _children[_currentIndex])); // this has changed
}
final List<Widget> _children = [
HomePage(),
InboxPage(),
SignInPage()
];
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
appBar: PreferredSize(
preferredSize: Size(double.infinity, 75),
child: AppBar(
elevation: 0.0,
centerTitle: false,
title: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text(
currentDate,
textAlign: TextAlign.left,
style: TextStyle(
color: titleTextColor,
fontWeight: subTitleFontWeight,
fontFamily: titleFontFamily,
fontSize: subTitleFontSize),
),
),
SizedBox(
height: 15,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
'Some text here',
style: TextStyle(
color: titleTextColor,
fontWeight: titleTextFontWeight,
fontFamily: titleFontFamily,
fontSize: titleFontSize),
),
),
],
),
backgroundColor: kPrimaryColor,
shape: titleBarRounding
),
),
body: BodyOne(),
body: Container(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Inbox'),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Account'),
)
],
onTap: (index) { // this has changed
setState(() {
_currentIndex = index;
});
_onTap();
},
),
);
}
The best way to do it is creating a wrapper to your screens. Like this:
class Wrapper extends StatefulWidget {
Wrapper();
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
int _currentIndex = 0;
final List<Widget> _children = [
HomePage(),
InboxPage(),
SignInPage()
];
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
items:[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
title: Text('Inbox'),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Account'),
)
],
),
);
}
}