Why the Set State in Textfield doesn't work? - flutter

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;
});
},
),
);
}
}

Related

bottomNavigationBar OnTap does not trigger for navigate to another page

#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:

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,
),
);
}
}

what is the best way to implement this home screen?

I would like to create a home page for my flutter app. I used templates from the network, but unfortunately I don't get it the way I sketched it in the picture. maybe someone can help me with that
sketch / result
Unfortunately, I'm sure that I can't do it better: - /, would like to have it exactly like the one on the left (icons and colors are not so important)
I used this link from the forum as a template for the appbar, and I had difficulties in inserting it ^^
Custom AppBar Flutter
I also got the code for the BottomNavigationBar from somewhere in the forum, but I think this is not suitable for my purposes anyway. Since I don't like this shrink effect when clicking on it, the two arrow buttons at the edge should snap back when pressed and not stay in the pressed state, as they should stand for the front and back function ...
here is my complete main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
Color _getBgColor(int index) =>
_selectedIndex == index ? _selectedBgColor : _unselectedBgColor;
Color _getItemColor(int index) =>
_selectedIndex == index ? _selectedItemColor : _unselectedItemColor;
Widget _buildIcon(IconData iconData, String text, int index) => Container(
width: double.infinity,
height: kBottomNavigationBarHeight,
child: Material(
color: _getBgColor(index),
child: InkWell(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(iconData),
Text(text,
style: TextStyle(fontSize: 9, color: _getItemColor(index))),
],
),
onTap: () => _onItemTapped(index),
),
),
);
_appBar(height) => PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, height+80 ),
child: Stack(
children: <Widget>[
Container(
child: Center(
child: Text("TEXT", style: TextStyle(fontSize: 15.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
color:Theme.of(context).primaryColor,
height: height+75,
width: MediaQuery.of(context).size.width,
),
Container(
),
Positioned( // To take AppBar Size only
top: 100.0,
left: 20.0,
right: 20.0,
child: AppBar(
backgroundColor: Color(0xFF293749),
leading: Icon(Icons.menu, color: Colors.white),
primary: false,
title: Container(
margin: EdgeInsets.only(top: 4.0, bottom: 4.0, right: 0.0, left: 0.0),
color: Colors.white,
child: Container(
margin: EdgeInsets.only(top: 0.0, bottom: 0.0, right: 5.0, left: 5.0),
child: TextField(
decoration: InputDecoration(
hintText: "Suchen",
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey))),
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.white), onPressed: () {},),
],
),
)
],
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(AppBar().preferredSize.height),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_back_ios_rounded, 'ZURÜCK', 0),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.favorite, 'FAVORITEN', 1),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.comment, 'KOMMENTARE', 2),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.info_outline_rounded, 'ÜBER UNS', 3),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: _buildIcon(Icons.arrow_forward_ios_rounded, 'WEITER', 4),
title: SizedBox.shrink(),
),
],
currentIndex: _selectedIndex,
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
),
);
}
}
I have modified your code with some commentaries to support you in building the UI.
For the AppBar, you are going in the right direction of using PreferredSize with Stack, just some minor adjustments.
For the BottomNavigationBar, since the provided BottomNavigationBarItem has the icon and title attributes already, we can use that and modify the color from their parents. The 2 arrows buttons can be placed together within the Row.
Here's the full example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.light,
theme: ThemeData(
primaryColor: Color(0xFF34445c),
primaryColorBrightness: Brightness.light,
brightness: Brightness.light,
primaryColorDark: Colors.black,
canvasColor: Color(0xFFCECECE),
appBarTheme: AppBarTheme(brightness: Brightness.light)),
darkTheme: ThemeData(
primaryColor: Colors.black,
primaryColorBrightness: Brightness.dark,
primaryColorLight: Colors.black,
brightness: Brightness.dark,
primaryColorDark: Colors.black,
indicatorColor: Colors.white,
canvasColor: Colors.black,
appBarTheme: AppBarTheme(brightness: Brightness.dark)),
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> {
final _selectedItemColor = Colors.white;
final _unselectedItemColor = Colors.white30;
final _selectedBgColor = Color(0xFF293749);
final _unselectedBgColor = Color(0xFF34445c);
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 15, fontWeight: FontWeight.normal);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: ZURÜCK',
style: optionStyle,
),
Text(
'Index 1: FAVORITES',
style: optionStyle,
),
Text(
'Index 2: KOMMENTARE / LÖSCHEN',
style: optionStyle,
),
Text(
'Index 3: ABOUT-US',
style: optionStyle,
),
Text(
'Index 4: WEITER',
style: optionStyle,
),
];
_appBar() => PreferredSize(
preferredSize: Size.fromHeight(300),
child: Container(
height: 300,
child: Stack(
children: <Widget>[
Container(
color: Color(0xFF34445D),
height: 180,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"APP TITLE",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w600,
color: Colors.white),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(
4,
(index) => Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Icon(Icons.people, color: Colors.white), // Sample icons for demonstration
),
),
)
],
),
),
Positioned(
top: 150.0,
left: 20.0,
right: 20.0,
child: Container(
color: Color(0xFF293749),
child: Row(
children: [
IconButton(
icon: Icon(Icons.menu, size: 40, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(vertical: 3),
padding: EdgeInsets.only(left: 3),
color: Colors.white,
height: 30,
child: TextField(
style: TextStyle(color: Colors.black, fontSize: 12),
decoration: InputDecoration(
hintText: 'Search...',
border: InputBorder.none),
),
),
),
IconButton(
icon: Icon(Icons.search, size: 30, color: Colors.white),
padding: EdgeInsets.zero,
onPressed: () {},
),
],
),
),
),
],
),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: Container(
color: _selectedBgColor,
child: Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex <= 0 ? _selectedIndex : _selectedIndex - 1;
});
},
),
Expanded(
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed, // Add the type here to avoid auto resize
backgroundColor: _selectedBgColor, // You can also set the unselectedBackgroundColor
currentIndex: _selectedIndex,
onTap: (index) => setState(() => _selectedIndex = index), // Update the selected index
selectedItemColor: _selectedItemColor,
unselectedItemColor: _unselectedItemColor,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.favorite), title: Text('FAVORITEN')),
BottomNavigationBarItem(
icon: Icon(Icons.comment), title: Text('KOMMENTARE')),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline_rounded),
title: Text('ÜBER UNS')),
],
),
),
IconButton(
icon: Icon(Icons.arrow_forward_ios, color: Colors.white),
onPressed: () {
setState(() {
_selectedIndex =
_selectedIndex >= 2 ? _selectedIndex : _selectedIndex + 1;
});
},
),
],
),
),
);
}
}

how to make BottomNavigationBar with number and text flutter

I need to build a BottomNavigationBar with a text and a number as the photo below :
the name of the tab is will shown just when the app is active
how to do it ??
Basically this is exactly what you want: https://flutterawesome.com/a-modern-google-style-nav-bar-for-flutter/
I recomend you extracting this code and build it to your fits.
import 'package:flutter/material.dart';
import 'package:google_nav_bar/google_nav_bar.dart';
import 'package:line_icons/line_icons.dart';
void main() => runApp(MaterialApp(
title: "GNav",
theme: ThemeData(
primaryColor: Colors.grey[800],
),
home: Example()));
class Example extends StatefulWidget {
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
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: Likes',
style: optionStyle,
),
Text(
'Index 2: Search',
style: optionStyle,
),
Text(
'Index 3: Profile',
style: optionStyle,
),
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(blurRadius: 20, color: Colors.black.withOpacity(.1))
]),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 8),
child: GNav(
gap: 8,
activeColor: Colors.white,
iconSize: 24,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
duration: Duration(milliseconds: 800),
tabBackgroundColor: Colors.grey[800],
tabs: [
GButton(
icon: LineIcons.home,
text: 'Home',
),
GButton(
icon: LineIcons.heart_o,
text: 'Likes',
),
GButton(
icon: LineIcons.search,
text: 'Search',
),
GButton(
icon: LineIcons.user,
text: 'Profile',
),
],
selectedIndex: _selectedIndex,
onTabChange: (index) {
setState(() {
_selectedIndex = index;
});
}),
),
),
),
);
}
}
Link to repository and full code:
https://github.com/sooxt98/google_nav_bar

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();
})
}),
),
]
),