Getx in not updating value in navigation rails flutter - flutter

I am using Obx in the navigation rails and updating the text widget. When I tap on the filter by source widget and select some values it does not update the length/count but when I tap on the filter by country widget the filter by a source shows the count. Same for the widget filter by country. It does not update the value in real-time. This is my rails widget
NavigationRail(
selectedIndex: homeController.rails.value,
onDestinationSelected: (int index) {
homeController.rails.value = index;
},
labelType: NavigationRailLabelType.all,
destinations: <NavigationRailDestination>[
const NavigationRailDestination(
icon: Icon(Icons.list_alt_sharp),
selectedIcon: Icon(Icons.list_alt),
label: Text('Layouts'),
),
const NavigationRailDestination(
icon: Icon(Icons.language_outlined),
selectedIcon: Icon(Icons.language),
label: Text('Filter by language'),
),
NavigationRailDestination(
icon: const Icon(Icons.source_outlined),
selectedIcon: const Icon(Icons.source),
label: Obx(() => Text(
'Filter by source ${homeController.filterSources.value.length}'))),
NavigationRailDestination(
icon: const Icon(FontAwesomeIcons.earthAsia),
selectedIcon:
const FaIcon(FontAwesomeIcons.earthAsia),
label: Obx(
() => Text(
'Filter by country ${homeController.filterCountry.value.length}'),
)),
],
),
This is my get controller
class HomeController extends GetxController {
var filterCountry = [].obs;
var filterSources = [].obs;
void filterCountryFunc(String e) {
if (filterCountry.value.contains(e)) {
filterCountry.value.remove(e);
} else {
filterCountry.value.add(e);
}
update();
}
void filterSourcesFunc(String e) {
if (filterSources.value.contains(e)) {
filterSources.value.remove(e);
} else {
filterSources.value.add(e);
}
update();
}
}
This is my complete dart stateful class
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:newsconnects/constants.dart';
import 'package:newsconnects/controllers/home_controller.dart';
import 'package:newsconnects/controllers/sources_controller.dart';
import 'package:newsconnects/translations/helper.dart';
import 'package:newsconnects/views/widgets/custom_checkBoxTile.dart';
import 'news_view.dart';
class HomeView extends StatefulWidget {
HomeView({Key? key}) : super(key: key);
#override
State<HomeView> createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView>
with SingleTickerProviderStateMixin {
late TabController controller;
late final List<String> _syncChannels = [];
HomeController homeController = Get.put(HomeController());
SourcesController sourcesController = Get.find<SourcesController>();
final List _screens = <Widget>[
const NewsView(),
Center(
child: Text(t.getText('notifications')),
),
const Center(
child: Text('Politics'),
),
];
#override
void initState() {
controller = TabController(length: 3, vsync: this);
super.initState();
print('Home');
_resources();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 75.0,
leadingWidth: 90,
leading: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
GestureDetector(
onTap: () {},
child: const Icon(
Icons.refresh,
size: 30.0,
),
),
InkWell(
onTap: () => _showModelSheet(context),
child: const Icon(
Icons.add_box_sharp,
size: 30.0,
),
),
const Icon(
Icons.search,
size: 30.0,
),
]),
centerTitle: true,
title: const Center(
child: Text('NewsConnect'),
),
actions: [
const Center(
child: Text(
'Options',
style: TextStyle(fontSize: 14),
),
),
IconButton(onPressed: () {}, icon: const Icon(Icons.more_vert))
],
bottom: PreferredSize(
preferredSize: const Size.fromHeight(30.0),
child: TabBar(
controller: controller,
isScrollable: true,
unselectedLabelColor: Colors.white.withOpacity(0.3),
indicatorColor: Colors.white,
tabs: const [
Tab(
child: Text('All News'),
),
Tab(
child: Text('Notifications'),
),
Tab(
child: Text('Politics'),
),
]),
),
),
body: TabBarView(
controller: controller,
children: <Widget>[..._screens],
),
);
}
_showModelSheet(BuildContext context) {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
),
builder: (context) {
return SizedBox(
height: 400.0,
child: Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0),
topRight: Radius.circular(10.0))),
child: Obx(
() => Column(
children: [
Expanded(
flex: 2,
child: Row(
children: <Widget>[
NavigationRail(
selectedIndex: homeController.rails.value,
onDestinationSelected: (int index) {
homeController.rails.value = index;
},
labelType: NavigationRailLabelType.all,
destinations: <NavigationRailDestination>[
const NavigationRailDestination(
icon: Icon(Icons.list_alt_sharp),
selectedIcon: Icon(Icons.list_alt),
label: Text('Layouts'),
),
const NavigationRailDestination(
icon: Icon(Icons.language_outlined),
selectedIcon: Icon(Icons.language),
label: Text('Filter by language'),
),
NavigationRailDestination(
icon: const Icon(Icons.source_outlined),
selectedIcon: const Icon(Icons.source),
label: Obx(() => Text(
'Filter by source ${homeController.filterSources.value.length}'))),
NavigationRailDestination(
icon: const Icon(FontAwesomeIcons.earthAsia),
selectedIcon:
const FaIcon(FontAwesomeIcons.earthAsia),
label: Obx(
() => Text(
'Filter by country ${homeController.filterCountry.value.length}'),
)),
],
),
const VerticalDivider(thickness: 1, width: 1),
// This is the main content.
Expanded(
child: IndexedStack(
index: homeController.rails.value,
children: [
_layouts(),
_language(),
_sources(),
_country(),
],
))
],
),
),
const Divider(thickness: 1, height: 1),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
TextButton(
onPressed: () {
homeController.filterSources.value.clear();
homeController.filterCountry.value.clear();
},
child: const Text('CLEAR All')),
ElevatedButton(
onPressed: () {}, child: const Text('APPLY'))
],
)
],
),
),
),
);
});
}
Widget _myRadioButton({required String title, required int index}) {
return GetBuilder<HomeController>(
builder: (_) => RadioListTile(
value: homeController.layout[index],
groupValue: homeController.isGrid.value,
onChanged: (newValue) =>
homeController.onClickRadioButton(int.parse(newValue.toString())),
title: Text(title),
activeColor: Consts.appMainColor,
),
);
}
_layouts() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_myRadioButton(
title: "List View",
index: 0,
),
_myRadioButton(
title: "Grid View",
index: 1,
),
],
);
}
_language() {
return Obx(
() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CustomCheckBoxListTile(
value: homeController.isEnglish.value,
title: const Text('English'),
onTap: (newVal) {
homeController.isEnglish.value = newVal ?? false;
}),
CustomCheckBoxListTile(
value: homeController.isArabic.value,
title: const Text('Arabic'),
onTap: (newVal) {
homeController.isArabic.value = newVal ?? false;
}),
],
),
);
}
_sources() {
return GetBuilder<HomeController>(builder: (_) {
return ListView(
children: _syncChannels
.map((e) => CustomCheckBoxListTile(
value: homeController.filterSources.value.contains(e),
title: Text(e),
onTap: (newVal) {
homeController.filterSourcesFunc(e);
}))
.toList());
});
}
_country() {
return GetBuilder<HomeController>(
builder: (_) => ListView(
children: sourcesController.mapSelectedChannelCheckList.keys
.map((e) => CustomCheckBoxListTile(
value: homeController.filterCountry.value.contains(e),
title: Text(e.toString()),
onTap: (newVal) {
homeController.filterCountryFunc(e);
}))
.toList()));
}
void _resources() {
List.generate(
sourcesController.mapSelectedChannelCheckList.values.length,
(index0) => List.generate(
sourcesController.mapSelectedChannelCheckList.values
.elementAt(index0)
.length,
(index1) => List.generate(
sourcesController.mapSelectedChannelCheckList.values
.elementAt(index0)
.elementAt(index1)
.values
.length,
(index2) => List.generate(
sourcesController.mapSelectedChannelCheckList.values
.elementAt(index0)
.elementAt(index1)
.values
.elementAt(index2)['channels']
.length,
(index3) => _syncChannels.add(sourcesController
.mapSelectedChannelCheckList.values
.elementAt(index0)
.elementAt(index1)
.values
.elementAt(index2)['channels'][index3]
.keys
.toString())))));
}
}

Related

how to change icon color when navigate to another page in flutter?

I made a BottomBar and make them enable to navigate to the other pages using onPressed function like below codes. but after navigating to other page that'd be can't change icon color because I think i made bottomnavigationbar: BottomBar in other page so that the page build BottomBar newly and 'int current Tab=0' is build again..
how can I change the way to can be change icon's color?
--BottomBar--
class BottomBar extends StatefulWidget {
const BottomBar({Key? key}) : super(key: key);
#override
State<BottomBar> createState() => BottomBarState();
}
class BottomBarState extends State<BottomBar> {
int currentTab = 0;
PageStorageBucket bucket = PageStorageBucket();
Widget currentScreen = HomePage();
final List<Widget> screens = [
HomePage(),
ShopPage(),
PeoplePage(),
WalletPage()
];
#override
Widget build(BuildContext context) {
return BottomAppBar(
shape: CircularNotchedRectangle(),
notchMargin: 10,
child: Container(
height: 60,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MaterialButton(
minWidth: 40,
onPressed: (){
setState(() {
currentScreen = HomePage();
currentTab = 0;
});
Navigator.push(
context, MaterialPageRoute(builder: (context)=> HomePage())
);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.home,
color: currentTab == 0? Colors.blue : Colors.grey,
),
],
),
),
MaterialButton(
minWidth: 40,
onPressed: (){
setState(() {
currentScreen = ShopPage();
});
Navigator.push(
context, MaterialPageRoute(builder: (context)=> const ShopPage())
);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.shop,
color: currentTab == 1? Colors.blue : Colors.grey,
),
],
),
),
],
),
//Right Tab Bar Icons
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MaterialButton(
minWidth: 40,
onPressed: (){
setState(() {
currentScreen = WalletPage();
currentTab = 2;
});
Navigator.push(
context, MaterialPageRoute(builder: (context)=> const WalletPage())
);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.wallet,
color: currentTab == 2? Colors.blue : Colors.grey,
),
],
),
),
MaterialButton(
minWidth: 40,
onPressed: (){
setState(() {
currentScreen = PeoplePage();
currentTab = 3;
});
Navigator.push(
context, MaterialPageRoute(builder: (context)=> PeoplePage())
);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.people,
color: currentTab == 3? Colors.blue : Colors.grey,
),
],
),
),
],
),
],
),
),
);
}
}
--the way I used BottomBar in the other page--
bottomNavigationBar: BottomBar(),
Consider trying this :
return SafeArea(
child: Scaffold(
extendBody: true,
body:pageOPtions[selectedPage]
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: const Color(0xff282828),
currentIndex: selectedPage, //let's say it's 0
selectedLabelStyle: cardSecondaryTextStyle,
unselectedLabelStyle: cardSecondaryTextStyle,
selectedItemColor: const Color(0xffc8332c),
unselectedItemColor: const Color(0xff707070),
selectedIconTheme: const IconThemeData(color: Color(0xffc8332c)),
onTap: (index) {
setState(() {
selectedPage = index;
});
},
items: [
const BottomNavigationBarItem(
icon: Icon(
Icons.person,
color: Color(0xff707070),
size: 16,
),
activeIcon: Icon(
Icons.person,
color: Color(0xffc8332c),
size: 22,
),
label: 'Profile',
),
const BottomNavigationBarItem(
icon: Icon(
Icons.history,
color: Color(0xff707070),
size: 16,
),
activeIcon: Icon(
Icons.history,
color: Color(0xffc8332c),
size: 22,
),
label: 'Orders',
),
where pageOptions can be your screens like :
final pageOptions = [
const GeneralSettingsForm(),
const OrdersAndDelivery(),
];

Flutter|Updating a ListView

everyone!
I have a HomeScreen, with this code:
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Padding(
padding: const EdgeInsets.only(left: 8, right: 8),
child: Column(children: [
ActiveTaskInfo(
task: tasks.first,
),
const TextWidget(),
Expanded(child: TasksList()),
const SizedBox(height: 80),
]),
),
BottomBarClass(),
],
),
),
);
TasksList() - ListView.
BottomBarClass() - It is a container with a button inside.
If you return the code itself to the main HomeScreen file, everything works, but if you put it in a separate class and when you add a new item to the list (through the button) nothing happens, but if you press Hot Reload, then the new item in the list is displayed.
Code BottomBarClass():
Positioned(
bottom: 0, left: 0,
child: ClipRRect(
borderRadius: const BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
child: Container(
height: 80, width: MediaQuery.of(context).size.width,
color: const Color(0xff070417),
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(Icons.watch_later, color: Colors.white.withOpacity(0.4)),
IconButton(icon: Icon(Icons.add, color: Colors.white.withOpacity(0.4),), iconSize: 32, onPressed: () async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
return TaskAdding();
}));
if (result == true) {
setState(() {
});
}
}),
Icon(Icons.pie_chart_rounded, color: Colors.white.withOpacity(0.4), size: 24,),
],),
),
));
Вот пример GIF: https://gifyu.com/image/Spp1O
TaskAdding():
import 'package:flutter/material.dart';
import '../expansions/task_tags_decorations.dart';
import '../expansions/tasks_data.dart';
class TaskAdding extends StatefulWidget {
const TaskAdding({Key? key}) : super(key: key);
#override
State<TaskAdding> createState() => _TaskAddingState();
}
class _TaskAddingState extends State<TaskAdding> {
late String _addField;
late Widget _selectedValue;
late bool _active;
late int _selectedIndex;
#override
void initState() {
_addField = 'Empty';
_active = false;
_selectedValue = tasks[0].icon;
_selectedIndex = 0;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Add'), backgroundColor: Colors.pink),
body: Column(children: [
Text('Add Task', style: TextStyle(color: Colors.white, fontSize: 24),),
TextField(onChanged: (String value) {
_addField = value;
}),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DropdownButton<Widget>(
value: _selectedValue,
onChanged: (newValue) {
setState(() {
_selectedValue = newValue!;
});
},
items: dropdownItems,
),
ElevatedButton(
onPressed: () {
setState(() {
tasks.addAll({
TaskData(
taskName: _addField,
tagOne: _active
? tasks[0].tagOne
: tasks[1].tagOne,
tagTwo: tagTwoContainer[_selectedIndex],
icon: _selectedValue,
taskTime: '00:32:10',
)
});
decorations.addAll({
TaskTagsDecorations(
iconColor: const Color(0xff7012CF))
});
});
Navigator.of(context).pop(true);
},
child: const Text('Add')),
],
),
Center(
child: ListTile(
title: _active
? Center(
child: tasks[0].tagOne,
)
: Center(child: tasks[1].tagOne),
selected: _active,
onTap: () {
setState(() {
_active = !_active;
});
},
),
),
SizedBox(
height: 52,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: tagTwoContainer.length,
itemBuilder: (context, index) {
var tagTwoList = tasks[index].tagTwo;
return SizedBox(
height: MediaQuery.of(context).size.height, width: 160,
child: ListTile(
visualDensity: VisualDensity.compact,
selected: index == _selectedIndex,
selectedTileColor: Colors.indigo.withOpacity(0.6),
title: Align(
alignment: Alignment.topCenter,
child: tagTwoList),
onTap: () {
setState(() {
_selectedIndex = index;
});
},
),
);
}),
),
],),
);
}
List<DropdownMenuItem<Widget>> get dropdownItems {
List<DropdownMenuItem<Widget>> menuItems = [
DropdownMenuItem(
child: const Icon(Icons.free_breakfast),
value: iconCircle[0],
),
DropdownMenuItem(
child: const Icon(Icons.grade_outlined), value: iconCircle[1]),
DropdownMenuItem(child: const Icon(Icons.gamepad), value: iconCircle[2]),
DropdownMenuItem(
child: const Icon(Icons.face_rounded), value: iconCircle[3]),
];
return menuItems;
}
}
You question is not clear. Try to add TasksList()
My solution:
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return HomeScreen();
}));

Show drawer over bottom navigation bar in Flutter

I have a drawer in a appbar and need to show it over the bottom navigation bar but can't put both in the same view, I don't know exactly how to do this.
This is what it looks like now and this is what it needs to look like.
This is part of the code of the view where the appbar is
class ContactsPage extends StatefulWidget {
final String title;
final String token;
final String qr;
String code;
final String name;
ContactsPage({this.name, this.token, this.qr, this.code, Key key, this.title})
: super(key: key);
#override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
List<Contact> contactList;
bool showHorizontalBar = false;
bool ready = false;
#override
void initState() {
super.initState();
var userService = new UserService();
userService.getContacts(widget.token).then((value) => {
print(value),
if (value == '0')
{
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => LoginPage()))
}
else if (value == '3')
{
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => LoginPage()))
}
else
{
setState(() {
contactList = value;
ready = true;
})
},
print(contactList),
});
}
void showMessage(String message, [MaterialColor color = Colors.red]) {
_scaffoldKey.currentState..removeCurrentSnackBar();
_scaffoldKey.currentState.showSnackBar(
new SnackBar(backgroundColor: color, content: new Text(message)));
}
_navigateAndDisplaySelection(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scanner(
qr: widget.qr,
token: widget.token,
)),
);
if (result != null) {
showMessage('$result', Colors.red);
}
}
Widget _addPerson() {
return FloatingActionButton(
onPressed: () {
_navigateAndDisplaySelection(context);
},
child: Icon(Icons.group_add),
backgroundColor: Color(0xff83bb37),
);
}
Widget buildMenuIcon() {
return IconButton(
icon: Icon(showHorizontalBar ? Icons.close : Icons.more_horiz),
onPressed: () {
setState(() {
showHorizontalBar = !showHorizontalBar;
});
},
);
}
Widget _simplePopup() => PopupMenuButton<int>(
itemBuilder: (context) => [
PopupMenuItem(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(
Icons.delete,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.favorite,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.mail,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.calendar_today,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
IconButton(
icon: Icon(
Icons.call,
color: Color(0xff83bb37),
),
onPressed: () => {},
),
],
),
)
],
icon: Icon(
Icons.more_horiz,
size: 20,
color: Color(0xff4d4c48),
),
);
Widget _card(String first_name, String last_name, String email) {
return Card(
clipBehavior: Clip.antiAlias,
child: Column(
children: [
SizedBox(
height: 5.0,
),
ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(13.0),
child: Image.asset(
'assets/images/mujer.jpg',
width: 60.0,
height: 70.0,
fit: BoxFit.cover,
),
),
title: Row(
children: [
Text(
first_name,
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff4d4c48)),
),
SizedBox(width: 5.0),
Text(
last_name,
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff4d4c48)),
)
],
),
subtitle: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
email,
style: TextStyle(color: Color(0xff4d4c48)),
),
SizedBox(
height: 5.0,
),
Text(
'Prowebglobal',
style: TextStyle(
color: Color(0xff4d4c48), fontWeight: FontWeight.w600),
),
],
),
),
trailing: _simplePopup(),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ContactDetails(token: widget.token, email: email)));
},
),
SizedBox(
height: 20.0,
),
],
),
);
}
Widget textContainer(String string, Color color) {
return new Container(
child: new Text(
string,
style: TextStyle(
color: color, fontWeight: FontWeight.normal, fontSize: 16.0),
textAlign: TextAlign.start,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
margin: EdgeInsets.only(bottom: 10.0),
);
}
Widget _titulo() {
return new Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 20.0),
child: new Text(
'Contactos',
style: TextStyle(
color: Color(0xff83bb37),
fontWeight: FontWeight.bold,
fontSize: 25.0),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
drawer: NavDrawer(
token: widget.token,
),
appBar: AppBar(
centerTitle: true,
backgroundColor: Color(0xfff0f0f0),
title: Image.asset(
'assets/images/logo-iso.png',
height: 50.0,
fit: BoxFit.contain,
alignment: Alignment.center,
),
iconTheme: new IconThemeData(color: Color(0xff707070)),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
},
),
]),
body: Column(children: [
SizedBox(
height: 20.0,
),
Expanded(
flex: 2,
child: _titulo(),
),
Expanded(
flex: 20,
child: Container(
child: ready
? ListView(
children: contactList
.map(
(Contact contact) => _card("${contact.first_name}",
"${contact.last_name}", "${contact.email}"),
)
.toList())
: Center(
child: Image.asset(
"assets/images/logo-gif.gif",
height: 125.0,
width: 125.0,
),
),
),
),
]),
floatingActionButton: _addPerson(),
);
}
}
And this is where de bottom navigation menu is
class HomePage extends StatefulWidget {
HomePage({
this.token,
this.code,
Key key,
}) : super(key: key);
final String token;
final String code;
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String currentPage = 'contacts';
changePage(String pageName) {
setState(() {
currentPage = pageName;
});
}
#override
Widget build(BuildContext context) {
final Map<String, Widget> pageView = <String, Widget>{
"contacts": ContactsPage(
code: widget.code,
token: widget.token,
),
"profile": ProfilePage(
token: widget.token,
),
};
return Scaffold(
body: pageView[currentPage],
bottomNavigationBar: new BottomNavigationDot(
paddingBottomCircle: 21,
color: Colors.black.withOpacity(0.5),
backgroundColor: Colors.white,
activeColor: Colors.black,
items: [
new BottomNavigationDotItem(
icon: Icons.home,
onTap: () {
changePage("contacts");
}),
new BottomNavigationDotItem(icon: Icons.brush, onTap: () {}),
new BottomNavigationDotItem(icon: Icons.notifications, onTap: () {}),
new BottomNavigationDotItem(icon: Icons.favorite, onTap: () {}),
new BottomNavigationDotItem(
icon: Icons.person,
onTap: () {
changePage("profile");
}),
],
milliseconds: 400,
),
);
}
}
Edit:
I have thought on putting de appbar in the same level as de bottom navigation bar but I need to put different options on the appbar depending on the view so I thought on using diferent appbars, that's why I wanted it on the same level as the view.

TextEditController clears the text field's text

I am trying to make an application about to do. But there is an issue. I write some text to the text field. But When I add a new text field it clears the text filed's text. And when I delete the TextEditingController it fixes the issue. But then when I try to slide it right or left it clears the text again.
Here is the code
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
void main() => runApp(MaterialApp(
home: Home(),
));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int today=1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("Takveam"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
"$today",
style: TextStyle(
fontSize: 20.0,
color: Colors.lightGreenAccent[700],
letterSpacing: 1,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Todo()),
);
},
icon: Icon(Icons.featured_play_list),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today-=1;
if(today<1)
today=31;
});
},
icon: Icon(Icons.calendar_today),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today=31;
});
},
icon: Icon(Icons.access_alarms),
color: Colors.lightGreenAccent[700],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
today+=1;
if(today>31)
{
today=1;
}
});
},
child: Text("Dıkla"),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
class Todo extends StatefulWidget {
#override
_TodoState createState() => _TodoState();
}
class _TodoState extends State<Todo> {
int i=1;
List<Column> todoos = [
Column(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("To do"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: ListView.builder(
itemCount: i,
itemBuilder: (context,index){
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
height: 60,
child: Card(
color: Colors.lightGreenAccent[700],
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
controller: new TextEditingController(),
style: TextStyle(
fontSize: 20,
color: Colors.white
),
onChanged: (text) {
print(i);
},
),
],
),
),
),
actions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.check_circle,
)
],
secondaryActions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.more_horiz
)
],
),
],
);
}
),
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
i+=1;
});
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
You can copy paste run full code below
Each item need a TextEditingController
For demo purpose, I remove background color
Step 1: declare a List<TextEditingController> listTexttCtrl = [TextEditingController()];
Step 2: In FloatingActionButton, add listTexttCtrl.add(TextEditingController());
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
i += 1;
listTexttCtrl.add(TextEditingController());
});
},
Step 3: TextField controller attribute use listTexttCtrl[index]
TextField(
controller: listTexttCtrl[index],
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
void main() => runApp(MaterialApp(
home: Home(),
));
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int today = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("Takveam"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
"$today",
style: TextStyle(
fontSize: 20.0,
color: Colors.lightGreenAccent[700],
letterSpacing: 1,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Todo()),
);
},
icon: Icon(Icons.featured_play_list),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today -= 1;
if (today < 1) today = 31;
});
},
icon: Icon(Icons.calendar_today),
color: Colors.lightGreenAccent[700],
),
IconButton(
onPressed: () {
setState(() {
today = 31;
});
},
icon: Icon(Icons.access_alarms),
color: Colors.lightGreenAccent[700],
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
today += 1;
if (today > 31) {
today = 1;
}
});
},
child: Text("Dıkla"),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}
class Todo extends StatefulWidget {
#override
_TodoState createState() => _TodoState();
}
class _TodoState extends State<Todo> {
int i = 1;
List<Column> todoos = [
Column(),
];
List<TextEditingController> listTexttCtrl = [TextEditingController()];
#override
Widget build(BuildContext context) {
return Scaffold(
//backgroundColor: Colors.lightGreenAccent[100],
appBar: AppBar(
title: Text("To do"),
centerTitle: true,
backgroundColor: Colors.lightGreenAccent[700],
),
body: ListView.builder(
itemCount: i,
itemBuilder: (context, index) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
height: 60,
child: Card(
color: Colors.lightGreenAccent[700],
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
controller: listTexttCtrl[index],
style: TextStyle(fontSize: 20, color: Colors.white),
onChanged: (text) {
print(i);
},
),
],
),
),
),
actions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.check_circle,
)
],
secondaryActions: <Widget>[
IconSlideAction(
color: Colors.lightGreenAccent[200],
icon: Icons.more_horiz)
],
),
],
);
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
i += 1;
listTexttCtrl.add(TextEditingController());
});
},
child: Icon(
Icons.add,
),
backgroundColor: Colors.lightGreenAccent[700],
),
);
}
}

How to navigate to page based on condition in Flutter

I want to navigate to a page based on a condition. When I select 'license' and press the next button it should redirect to license page. When I select 'unlicensed' and press next button it should redirect me to unlicensed page.
After selecting the 'licence'/'unlicensed' value from drop-down it should use that value to determine which page to redirect to.
Here is some code I've tried so far:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
class BspSignupPage extends StatefulWidget {
#override
_BspSignupPageState createState() => _BspSignupPageState();
}
class _BspSignupPageState extends State<BspSignupPage> {
bool bspcheck = false;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _dropdownError;
File _image;
List<String> _colors = <String>[
'',
'Licensed / Register',
'Unregistered',
];
List<DropdownMenuItem<String>> _dropDownItem() {
List<String> ddl = ["License/Registered", "UN-Registered"];
return ddl
.map((value) => DropdownMenuItem(
value: value,
child: Text(value),
))
.toList();
}
Widget _buildbusinesstype() {
String _selectedGender;
return new FormBuilder(
autovalidate: true,
child: FormBuilderCustomField(
attribute: "Business Type",
validators: [
FormBuilderValidators.required(),
],
formField: FormField(
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: InputDecoration(
prefixIcon: Icon(Icons.merge_type),
errorText: field.errorText),
//isEmpty: _color == '',
child: new DropdownButtonHideUnderline(
child: new DropdownButton(
value: _selectedGender,
items: _dropDownItem(),
onChanged: (value) {
_selectedGender = value;
},
hint: Text('Select Business Type'),
),
),
);
},
),
));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("BSP Signup"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.pop(context);
},
),
centerTitle: true,
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.close),
label: Text('Clear'),
// color: Colors.redAccent,
textColor: Colors.black,
// padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {},
),
new FlatButton.icon(
icon: Icon(Icons.ac_unit),
label: Text('Next'),
color: Colors.amber,
textColor: Colors.white,
//padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () async {
if (_formKey.currentState.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BspSignupPage()));
}
}),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Form(
autovalidate: true,
key: _formKey,
child: Stack(
children: <Widget>[
SingleChildScrollView(
padding: const EdgeInsets.all(30.0),
child: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildbusinesstype(),
],
),
),
),
],
),
),
),
);
}
}
You can get the value of dropdown using a state variable,
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
class BspSignupPage extends StatefulWidget {
#override
_BspSignupPageState createState() => _BspSignupPageState();
}
class _BspSignupPageState extends State<BspSignupPage> {
bool bspcheck = false;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _dropdownError;
String _dropDownValue = '';
File _image;
List<String> _colors = <String>[
'',
'Licensed / Register',
'Unregistered',
];
List<DropdownMenuItem<String>> _dropDownItem() {
List<String> ddl = ["License/Registered", "UN-Registered"];
return ddl
.map((value) => DropdownMenuItem(
value: value,
child: Text(value),
))
.toList();
}
Widget _buildbusinesstype() {
String _selectedGender;
return new FormBuilder(
autovalidate: true,
child: FormBuilderCustomField(
attribute: "Business Type",
validators: [
FormBuilderValidators.required(),
],
formField: FormField(
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: InputDecoration(
prefixIcon: Icon(Icons.merge_type),
errorText: field.errorText),
//isEmpty: _color == '',
child: new DropdownButtonHideUnderline(
child: new DropdownButton(
value: _selectedGender,
items: _dropDownItem(),
onChanged: (value) {
_dropDownValue = value;
},
hint: Text('Select Business Type'),
),
),
);
},
),
));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("BSP Signup"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.pop(context);
},
),
centerTitle: true,
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.close),
label: Text('Clear'),
// color: Colors.redAccent,
textColor: Colors.black,
// padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {},
),
new FlatButton.icon(
icon: Icon(Icons.ac_unit),
label: Text('Next'),
color: Colors.amber,
textColor: Colors.white,
//padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () async {
if (_formKey.currentState.validate()) {
// Now use if statement here to decide which route you want to go
if(_dropdDown == "SOME_VALUE"){
// Go to this route
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BspSignupPage()));
}
}),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Form(
autovalidate: true,
key: _formKey,
child: Stack(
children: <Widget>[
SingleChildScrollView(
padding: const EdgeInsets.all(30.0),
child: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildbusinesstype(),
],
),
),
),
],
),
),
),
);
}
}
Unfortunately, I do not have access to Flutter to actually test the code at the moment, but the idea would be as follows.
Keep a state variable that tracks which type of page the app should show. For example, bool license = false. If license is true, navigate to one page. If false, the other. You can code the dropdown list to change that variable.
Once a user has selected one or the other value, use it to navigate to a page based on it. In pseudo code:
FlatButton(
...<styling>...
onPressed: () {
if (_formKey.currentState.validate()) {
if (license) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LicensePage()),
);
} else {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => UnlicensedPage()),
);
}
}
}
)