bottomNavigationBar OnTap does not trigger for navigate to another page - flutter

#override
void initState() {
super.initState();
}
int selectedPage = 0;
void changePage(int index) {
setState(() {
selectedPage = index;
});
}
bottomNavigationBar: BottomNavigationBar(
showUnselectedLabels: true,
currentIndex: selectedPage,
onTap: showPage,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Main',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.category_outlined),
label: 'Category',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.book_online),
label: 'Photos',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.video_call),
label: 'Video',
backgroundColor: Colors.blue),
],
Widget showPage(int selectedPage) {
if (selectedPage == 0) {
return NewsViewDetail(id: '0');
} else if (selectedPage == 1) {
return NewsLoading(text: 'load');
}
return NewsLoading(text: '1');
}
When I tap first or second item on the there is no reaction from UI. It seems onTap does not navigate to different pages.
Could you please help me why this code is not working?
Edit: I think the problem causing Scaffold body. Current Scaffold body is:
body: TabBarView(
children: [
for (final tab in filteredList)
NewsView(
id: tab.id!,
),
],
),
How can I integrate showPage(_selectedIndex), into Scaffold Body without hurt the TabbarView?
here is the TabBarController
return DefaultTabController(
// length: snapshot.data!.data!.length,
length: filteredList.length,
child: Scaffold(
appBar: AppBar(
backgroundColor: (Colors.white),
iconTheme: const IconThemeData(color: Colors.black),
title: Transform.translate(
offset: const Offset(-24.0, 0.0),
child: Image.asset("assets/images/lo.png",
fit: BoxFit.contain, height: 22),
),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(30.00),
child: ColoredBox(
color: Colors.white,
child: TabBar(
labelColor: Colors.purple[100],
indicatorColor: Colors.purple,
isScrollable: true,
labelPadding:
const EdgeInsets.symmetric(horizontal: 8.0),
tabs: tabs),
),
),
),
```

Check it, it will be helped you to solve your solution
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
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>
with TickerProviderStateMixin {
int _selectedIndex = 0;
void changePage(int index) {
setState(() {
_selectedIndex = index;
});
}
Widget showPage(int selectedPage) {
if (selectedPage == 0) {
return Container(
child: Text('Main Page',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
);
} else if (selectedPage == 1) {
return Container(
child: Text('Category page',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
);
} else if (selectedPage == 2) {
return Container(
child: Text('Photo page',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
);
}
return Container(
child: Text('video Page',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),
);
}
TabController tabController;
#override
void initState() {
// TODO: implement initState
super.initState();
tabController = TabController(initialIndex: 0, length: 2, vsync: this);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.0),
//This is for bottom border that is needed
border:
Border(bottom: BorderSide(color: Colors.grey, width: 0.8))),
child: TabBar(
indicatorWeight: 2,
controller: tabController,
indicatorColor: Colors.purple,
labelColor: Colors.purple,
unselectedLabelColor: Color(0xff002540).withOpacity(0.7),
tabs: [
Tab(
child: Text(
"First",
),
),
Tab(
child: Text(
"Second",
),
),
],
),
),
backgroundColor: Colors.green,
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height,
child: TabBarView(controller: tabController, children: [
Container(
child: Center(
child: showPage(_selectedIndex),
),
),
Container(
child: Center(
child: showPage(_selectedIndex),
),
),
]),
),
],
)),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Main',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.category_outlined),
label: 'Category',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.book_online),
label: 'Photos',
backgroundColor: Colors.blue),
BottomNavigationBarItem(
icon: Icon(Icons.video_call),
label: 'Video',
backgroundColor: Colors.blue),
],
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
selectedItemColor: Colors.black,
iconSize: 40,
onTap: changePage,
elevation: 5),
);
}
}
Output:

Related

navigation bar issue after clicking on card flutter

[![When I click on any card the navigation bar doesn't work anymore ][2]][2]
the 1st image shows my navigation bar which works very well. The moment I click on a card the navigation bar doesn't work anymore and I didn't find out what is the reason
**This is my navigation bar Widget code that I'm using after clicking on the card **
class MenuBarWidget extends StatefulWidget {
#override
_State createState() => _State();
}
class _State extends State<MenuBarWidget> {
int _index = 0;
#override
Widget build(BuildContext context) {
return Container(
height: 70,
decoration: BoxDecoration(
gradient: AppGradients.linear,
),
child: BottomNavigationBar(
onTap: (newIndex) => setState(() => _index = newIndex),
currentIndex: _index,
unselectedItemColor: Colors.white70,
selectedItemColor: Colors.white,
elevation: 0,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
label: 'Principal',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.assignment_outlined),
label: 'Pedidos',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.chat_outlined),
label: 'Chat',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
label: 'Perfil',
backgroundColor: Colors.transparent,
),
],
),
);
}
}
this is my code after clicking on the card
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: MenuBarWidget(),
appBar: PreferredSize(
preferredSize: Size.fromHeight(100),
child: Stack(children: [
Container(
height: 128,
decoration: BoxDecoration(
color: AppColors.green,
border: Border(
bottom: BorderSide(
color: AppColors.blueButton,
width: 2,
),
),
image: DecorationImage(
image: AssetImage(AppImages.dots),
fit: BoxFit.cover,
),
),
),
Align(
alignment: Alignment(-0.7, -0.3),
child: RichText(
text: TextSpan(
text: serviceName,
style: TextStyle(
color: AppColors.white,
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
),
Align(
alignment: Alignment(-0.6, 0.4),
child: RichText(
text: TextSpan(
text: 'Confira abaixo todos os profissionais desta categoria',
style: TextStyle(
color: AppColors.white,
fontSize: 9,
fontWeight: FontWeight.bold,
),
),
),
),
]),
),
**Any help is appreciated thanks **
create a new list of screens and add the screens you created as the list items
List screens = [
HomeScreen();
CarpentryScreen();
...
...
];
then make the body of your MenuBarWidget() return screens[_index]
class MenuBarWidget extends StatefulWidget {
#override
_State createState() => _State();
}
class _State extends State<MenuBarWidget> {
int _index = 0;
// new list of your screens
List<Widget> screens = [
PrincipalScreen(),
PedidosScreen(),
Chatscreen(),
Perfilscreen(),
];
#override
Widget build(BuildContext context) {
// return the screens
return Scaffold(
body: screens[_index],
bottomNavigationBar: BottomNavigationBar(
onTap: (newIndex) => setState(() => _index = newIndex),
currentIndex: _index,
unselectedItemColor: Colors.white70,
selectedItemColor: Colors.white,
elevation: 0,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined),
label: 'Principal',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.assignment_outlined),
label: 'Pedidos',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.chat_outlined),
label: 'Chat',
backgroundColor: Colors.transparent,
),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline),
label: 'Perfil',
backgroundColor: Colors.transparent,
),
],
),
);
}
}
then you don't have to add bottomNavigationBar to the screens individually, this way, the screen is persistent across all screens

Flutter - Open Modal Bottom Sheet on Bottom navigation bar item click

How do i open bottom sheet from bottom navigation bar item click. This is my current code for the page, this is what i have tried so far but it does not seem to be working. I have created the bottom navigation bar successfully and with the functions Page1(), Page2(), Page3(), i can successfully migrate to other pages, now i need the forth item to just open a bottom sheet where i can do more items. The function showBottomSheet() should be able to open a bottom sheet
class _MyNavigationBarState extends State<MyNavigationBar > {
int _currentTabIndex = 0;
#override
Widget build(BuildContext context) {
final _kTabPages = <Widget>[
Page1(),
Page2(),
Page3(),
showBottomSheet()
];
final _kBottmonNavBarItems = <BottomNavigationBarItem>[
const BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
const BottomNavigationBarItem(icon: Icon(Icons.network_cell), label: 'Prices'),
const BottomNavigationBarItem(icon: Icon(Icons.add_circle), label: 'Trade'),
const BottomNavigationBarItem(icon: Icon(Icons.account_balance_wallet), label: 'Wallet'),
];
assert(_kTabPages.length == _kBottmonNavBarItems.length);
final bottomNavBar = BottomNavigationBar(
items: _kBottmonNavBarItems,
currentIndex: _currentTabIndex,
type: BottomNavigationBarType.fixed,
onTap: (int index) {
setState(() {
_currentTabIndex = index;
});
},
);
return Scaffold(
body: _kTabPages[_currentTabIndex],
bottomNavigationBar: bottomNavBar,
),
);
}
}
showBottomSheet(){
Container _buildBottomSheet(BuildContext context) {
return Container(
height: 300,
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2.0),
borderRadius: BorderRadius.circular(8.0),
),
child: ListView(
children: <Widget>[
const ListTile(title: Text('Bottom sheet')),
const TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
icon: Icon(Icons.attach_money),
labelText: 'Enter an integer',
),
),
Container(
alignment: Alignment.center,
child: ElevatedButton.icon(
icon: const Icon(Icons.save),
label: const Text('Save and close'),
onPressed: () => Navigator.pop(context),
),
)
],
),
);
}
}
try this:
class _MyNavigationBarState extends State<MyNavigationBar > {
int _currentTabIndex = 0;
#override
Widget build(BuildContext context) {
final _kTabPages = <Widget>[
Page1(),
Page2(),
Page3(),
Container(),
];
final _kBottmonNavBarItems = <BottomNavigationBarItem>[
const BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
const BottomNavigationBarItem(icon: Icon(Icons.network_cell), label: 'Prices'),
const BottomNavigationBarItem(icon: Icon(Icons.add_circle), label: 'Trade'),
const BottomNavigationBarItem(icon: Icon(Icons.account_balance_wallet), label: 'Wallet'),
];
assert(_kTabPages.length == _kBottmonNavBarItems.length);
final bottomNavBar = BottomNavigationBar(
items: _kBottmonNavBarItems,
currentIndex: _currentTabIndex,
type: BottomNavigationBarType.fixed,
onTap: (int index) {
if(index == 3){
showBottomSheet();
return;
}
setState(() {
_currentTabIndex = index;
});
},
);
return Scaffold(
body: _kTabPages[_currentTabIndex],
bottomNavigationBar: bottomNavBar,
),
);
}
}
showBottomSheet(){
Container _buildBottomSheet(BuildContext context) {
return Container(
height: 300,
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2.0),
borderRadius: BorderRadius.circular(8.0),
),
child: ListView(
children: <Widget>[
const ListTile(title: Text('Bottom sheet')),
const TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
icon: Icon(Icons.attach_money),
labelText: 'Enter an integer',
),
),
Container(
alignment: Alignment.center,
child: ElevatedButton.icon(
icon: const Icon(Icons.save),
label: const Text('Save and close'),
onPressed: () => Navigator.pop(context),
),
)
],
),
);
}
}
implement like this
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> 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,
),
Text(
'Index 3: Settings',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
color: Colors.amber,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('BottomSheet $index'),
ElevatedButton(
child: Text('Close BottomSheet $index'),
onPressed: () => Navigator.pop(context),
)
],
),
),
);
},
);
}
#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',
backgroundColor: Colors.red,
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
backgroundColor: Colors.green,
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
backgroundColor: Colors.purple,
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
backgroundColor: Colors.pink,
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

I am getting two appBar in flutter app. I am trying to add Drawer widget and TabBar widget in flutter app

main.dart
import 'package:flutter/material.dart';
import 'package:stray_animal_emergencyrescue/signUpPage.dart';
import './commons/commonWidgets.dart';
import 'package:stray_animal_emergencyrescue/loggedIn.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
//title: 'Flutter login UI',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//String showPasswordText = "Show Password";
bool obscurePasswordText = true;
#override
Widget build(BuildContext context) {
final passwordField = TextField(
obscureText: obscurePasswordText,
decoration: InputDecoration(
//contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintText: "Password",
//border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
suffixIcon: IconButton(
icon: new Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
this.obscurePasswordText = !obscurePasswordText;
});
},
)),
);
final loginButon = Material(
//elevation: 5.0,
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LogIn()),
);
},
child: Text('Login', textAlign: TextAlign.center),
),
);
final facebookContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Facebook', textAlign: TextAlign.center),
),
);
final googleContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Google ', textAlign: TextAlign.center),
),
);
final signUpButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => FormScreen()),
);
//print(MediaQuery.of(context).size.width);
},
child: Text('Sign Up ', textAlign: TextAlign.center),
),
);
return Scaffold(
appBar: AppBar(
title: Text("Animal Emergency App"),
),
body: Center(
child: Container(
//color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//SizedBox(height: 45.0),
getTextFieldWidget(),
SizedBox(height: 15.0),
passwordField,
sizedBoxWidget,
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
facebookContinueButton,
SizedBox(width: 5),
googleContinueButton,
SizedBox(width: 5),
loginButon
],
),
/*loginButon,
signUpButton,*/
sizedBoxWidget,
const Divider(
color: Colors.black,
height: 20,
thickness: 1,
indent: 20,
endIndent: 0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
signUpButton
],
),
],
),
),
),
),
);
}
}
loggedIn.dart
import 'package:flutter/material.dart';
import './tabbarviews/emergencyresue/EmergencyHome.dart';
import './tabbarviews/animalcruelty/animalCrueltyHome.dart';
import './tabbarviews/bloodbank/bloodBankHome.dart';
class LogIn extends StatefulWidget {
#override
_LogInState createState() => _LogInState();
}
class _LogInState extends State<LogIn> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions = <Widget>[
EmergencyHome(),
AnimalCrueltyHome(),
BloodBankHome()
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First app bar appearing'),
actions: <Widget>[
GestureDetector(
onTap: () {},
child: CircleAvatar(
//child: Text("SC"),
backgroundImage: AssetImage('assets/images/760279.jpg'),
//backgroundImage: ,
),
),
IconButton(
icon: Icon(Icons.more_vert),
color: Colors.white,
onPressed: () {},
),
],
),
drawer: Drawer(
child: ListView(
children: <Widget>[
new ListTile(title: Text("Primary")),
MyListTile(
"Home",
false,
"Your customized News Feed about people you follow, ongoing rescues, nearby activities, adoptions etc.",
3,
Icons.home,
true,
() {}),
MyListTile(
"News & Media Coverage",
false,
"News about incidents which need immediate action, changing Laws",
3,
Icons.home,
false,
() {}),
MyListTile(
"Report",
true,
"Report cases with evidences anonymously",
3,
Icons.announcement,
false,
() {}),
MyListTile(
"Blood Bank",
true,
"Details to donate blood ",
3,
Icons.medical_services,
false,
() {}),
],
),
),
body: _widgetOptions[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.pets),
label: 'Emergency Rescue',
),
BottomNavigationBarItem(
icon: Icon(Icons.add_alert),
label: 'Report Cruelty',
),
BottomNavigationBarItem(
icon: Icon(Icons.medical_services),
label: 'Blood Bank',
),
/*BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'Safe Hands',
backgroundColor: Colors.blue),*/
],
onTap: _onItemTapped,
),
);
}
}
//Safe Hands
class MyListTile extends StatelessWidget {
final String title;
final bool isThreeLine;
final String subtitle;
final int maxLines;
final IconData icon;
final bool selected;
final Function onTap;
MyListTile(this.title, this.isThreeLine, this.subtitle, this.maxLines,
this.icon, this.selected, this.onTap);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(title),
isThreeLine: isThreeLine,
subtitle:
Text(subtitle, maxLines: maxLines, style: TextStyle(fontSize: 12)),
leading: Icon(icon),
selected: selected,
onTap: onTap);
}
}
EmergencyHome.dart
import 'package:flutter/material.dart';
import './finishedAnimalEmergencies.dart';
import './reportAnimalEmergency.dart';
import './ongoingAnimalEmergencies.dart';
class EmergencyHome extends StatefulWidget {
#override
_EmergencyHomeState createState() => _EmergencyHomeState();
}
class _EmergencyHomeState extends State<EmergencyHome> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Second appBar appearing"),
bottom: TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
}
}
The issue I am facing is two appBar, I tried removing appBar from loggedIn.dart but Drawer hamburger icon is not showing, and I cannot remove appBar from emergencyHome.dart as I wont be able to add Tab bar. What is viable solution for this? Please help how to Structure by app and routes to easily manage navigation within app
Remove the appbar from EmergencyHome.dart
this will remove the second app title. But there will be that shadow from the first app bar so put elvation:0
so, this will look like one appbar now your drawer will also work.
you can use flexibleSpace in EmergencyHome.dart
DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
flexibleSpace: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
You don't want to make two appbar to get the drawer property. Use DefaultTabController then inside that you can use scaffold.so, you can have drawer: Drawer() inside that you can also get a appbar with it with TabBar as it's bottom.
This is most suitable for you according to your use case.
i will put the full code below so you can copy it.
void main() {
runApp(const TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
const TabBarDemo({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
drawer: Drawer(),
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(
text: "report",
),
Tab(text: "ongoing"),
Tab(text: "completed"),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
OUTPUT

Why the Set State in Textfield doesn't work?

I want to work with textfields but it doesn't work. Visual Studio always shows an error and I don't know why. The string userText is static because Visual Studio Code wanted this. I even don't know what static means.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: Home()));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
double mph;
int _currentIndex = 0;
static String userText = '';
final _pageOptions = [
Center(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
margin: EdgeInsets.only(bottom: 20.0),
child: Text(
'Km/h',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Colors.blue[400],
),
),
),
TextField(
decoration: InputDecoration(
hintText: 'Km/h',
focusColor: Colors.green[400],
),
onSubmitted: (String e){
setState(() {
userText = e;
});
},
),
Container(
margin: EdgeInsets.only(top: 10.0),
child: Text(
userText,
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 20.0,
)
),
)
]
)
),
Text('Suche'),
Text('Kamera'),
Text('Profil'),
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test"),
backgroundColor: Colors.green[400],
),
body: _pageOptions[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
iconSize: 30,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Home"),
backgroundColor: Colors.blue[400],
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text("Suche"),
backgroundColor: Colors.green[400],
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text("Kamera"),
backgroundColor: Colors.orange[400]
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("Profile"),
backgroundColor: Colors.purple[400]
),
],
onTap: (index){
setState(() {
_currentIndex = index;
});
},
),
);
}
}
Short answer:
You're initialising it as instance variable, so you can't use setState in it.
final _pageOptions = [...]; // incorrect way
You can simply use getter and setState works in it. Like:
List<Widget> get _pageOptions => [...]; // correct way
Full answer:
void main() => runApp(MaterialApp(home: Home()));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
double mph;
int _currentIndex = 0;
static String userText = '';
List<Widget> get _pageOptions => [
Center(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
margin: EdgeInsets.only(bottom: 20.0),
child: Text(
'Km/h',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Colors.blue[400],
),
),
),
TextField(
decoration: InputDecoration(
hintText: 'Km/h',
focusColor: Colors.green[400],
),
onSubmitted: (String e){
setState(() {
userText = e;
});
},
),
Container(
margin: EdgeInsets.only(top: 10.0),
child: Text(
userText,
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 20.0,
)
),
)
]
)
),
Text('Suche'),
Text('Kamera'),
Text('Profil'),
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test"),
backgroundColor: Colors.green[400],
),
body: _pageOptions[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
iconSize: 30,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Home"),
backgroundColor: Colors.blue[400],
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text("Suche"),
backgroundColor: Colors.green[400],
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text("Kamera"),
backgroundColor: Colors.orange[400]
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text("Profile"),
backgroundColor: Colors.purple[400]
),
],
onTap: (index){
setState(() {
_currentIndex = index;
});
},
),
);
}
}

Flutter: How can I keep to my selected navigator when I'll go to a new screen and go back

I'm having a problem right now in my bottom navigation in flutter.
I have four navigation "Community, Feeds, Activity, Profile".
In my "Feeds" navigation I have a button named "View Profile" everytime I click that button it directs me to a new screen using
"Navigator.push(context, MaterialPageRoute())"
and I notice it auto generates a "<-" or "back arrow" icon on the appbar.
The problem is everytime I click that "back arrow", it redirects me to the first option on my navigation bar.
Not on the "Feeds" navigation.
Any tips how to fix this?
Here is my bottom navigation code:
_getPage(int page) {
switch (page) {
case 0:
return NewsFeed();
case 1:
return OrgAndNews();
case 2:
return MyActivity();
case 3:
return Profile();
}
}
int currentPage = 0;
void _onBottomNavBarTab(int index) {
setState(() {
currentPage = index;
});
}
return Scaffold(
body: Container(
child: _getPage(currentPage),
),
bottomNavigationBar: Container(
height: _height * .09,
child: BottomNavigationBar(
backgroundColor: Color(0xFFFFFFFF),
fixedColor: Color(0xFF121A21),
unselectedItemColor: Color(0xFF121A21),
currentIndex: currentPage,
onTap: _onBottomNavBarTab,
items: [
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.users),
title: Padding(
padding: const EdgeInsets.only(top: 3.0),
child: Text('Community', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(35),
fontWeight: FontWeight.w800),
),
),
),
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.newspaper),
title: Padding(
padding: const EdgeInsets.only(top: 3.0),
child: Center(
child: Text('Feeds', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(35),
fontWeight: FontWeight.w800),),
),
),
),
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.listUl),
title: Padding(
padding: const EdgeInsets.only(top: 3.0),
child: Text('My Activity', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(35),
fontWeight: FontWeight.w800),),
),
),
BottomNavigationBarItem(
icon: Icon(FontAwesomeIcons.userAlt),
title: Padding(
padding: const EdgeInsets.only(top: 3.0),
child: Text('Profile', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(35),
fontWeight: FontWeight.w800),),
),
),
],
),
),
);
My code for the page when you click the "View Profile":
class OrgProfile extends StatefulWidget {
OrgProfile(this.orgName) : super();
final String orgName;
#override
_OrgProfileState createState() => _OrgProfileState();
}
class _OrgProfileState extends State<OrgProfile> {
#override
final db = Firestore.instance;
Container buildItem(DocumentSnapshot doc) {
return Container(
child: Column(
children: <Widget>[
Center(
child: Padding(
padding: const EdgeInsets.only(top: 20.0),
child: CircleAvatar(
radius: 70,
),
),
),
Text(
'${doc.data['Email']}',
style: TextStyle(color: Colors.black),
)
],
),
);
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.orgName),
),
body: StreamBuilder<QuerySnapshot>(
stream: db
.collection('USERS')
.where('Name of Organization', isEqualTo: widget.orgName)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data.documents
.map((doc) => buildItem(doc))
.toList());
} else {
return SizedBox();
}
}),
);
}
}
My code when i click the "View Profile" button:
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => new
OrgProfile(
doc.data['Name of Organization'])));
},
My feeds UI:
My View Profile UI:
Have you used MaterialPage Route With Builder Like This?
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => new MyToDoThunder(),
),
)
Homepage Code :-
class HomePage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
//
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
var db = DatabaseHelper();
int _selectedIndex = 0;
List<bool> textColorChange = [true, false, false, false];
final _widgetOptions = [
StatusPageRedux(),
RequestPage(),
NotificationPage(),
DashboardPage(),
];
_bottomNavigationView() {
return new Theme(
isMaterialAppTheme: true,
data: Theme.of(context)
.copyWith(canvasColor: Theme.of(context).primaryColor),
child: new BottomNavigationBar(
type: BottomNavigationBarType.fixed,
onTap: _onItemTapped,
currentIndex: _selectedIndex,
fixedColor: Colors.white,
items: [
new BottomNavigationBarItem(
activeIcon: ThunderSvgIcons(
path: 'assets/icons/Status.svg', height: 20.0, color: Colors.white),
icon: ThunderSvgIcons(
path: 'assets/icons/Status.svg', height: 20.0, color: Colors.white30),
title: new Text(
'Status',
style: TextStyle(
color: textColorChange[0] ? Colors.white : Colors.white30),
),
),
new BottomNavigationBarItem(
title: new Text(
'Requests',
style: TextStyle(
color: textColorChange[1] ? Colors.white : Colors.white30),
),
activeIcon: ThunderSvgIcons(
path: 'assets/icons/Requests.svg', height: 20.0, color: Colors.white),
icon: ThunderSvgIcons(
path: 'assets/icons/Requests.svg',
height: 20.0,
color: Colors.white30),
),
new BottomNavigationBarItem(
activeIcon: ThunderSvgIcons(
path: 'assets/icons/Notifications.svg',
height: 20.0,
color: Colors.white),
icon: ThunderSvgIcons(
path: 'assets/icons/Notifications.svg',
height: 20.0,
color: Colors.white30),
title: new Text(
'Notifications',
style: TextStyle(
color: textColorChange[2] ? Colors.white : Colors.white30),
),
),
new BottomNavigationBarItem(
activeIcon: ThunderSvgIcons(
path: 'assets/icons/dashboard.svg',
height: 20.0,
color: Colors.white),
icon: ThunderSvgIcons(
path: 'assets/icons/dashboard.svg',
height: 20.0,
color: Colors.white30),
title: new Text(
'Dashboard',
style: TextStyle(
color: textColorChange[3] ? Colors.white : Colors.white30),
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(child: _widgetOptions.elementAt(_selectedIndex)),
bottomNavigationBar: _bottomNavigationView(),
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
for (int i = 0; i < textColorChange.length; i++) {
if (index == i) {
textColorChange[i] = true;
} else {
textColorChange[i] = false;
}
}
});
}
}
You will have to add your way back to the stack.
Try the below appbar in you 'tuloung duloung' title page, it should do the trick.
Note if your homescreen has tabs its advised to pass the index of the page you want to reach on exiting 'tuloung duloung'.
Let me know if it helps.
AppBar(
backgroundColor: Colors.transparent,
centerTitle: false,
brightness: Brightness.dark,
title: Container(
width: 150,
child: Row(
children:[
IconButton(icon:Icons.back_arrow,
onpressed:() =>
Navigator.pushReplacementNamed(context, '/Your Home_Screen');
),
Text('tuloung duloung',
style: TextStyle(
fontWeight: FontWeight.w400,
color: theme.primaryColor,
)),
]
),
),
automaticallyImplyLeading: false,
iconTheme: IconThemeData(
color: theme.primaryColor,
),
actions:[ Container(
width: 150,
child: FlatButton.icon(
label: Text('Done'),
icon: Icon(Icons.check_circle),
onPressed: () => {
setState(() {
takingsnap = true;
_captureImage();
})
}),
),
]
),