How can I create form modal with dropdown select in flutter - flutter

I am new to flutter and this is my first application. I have been trying to create a form modal with dropdown select would receive its data from the server. but for now I am using the values in array I created but it not setting the value after I select an item. I tried to add a setState() but is showing error. Please can someone help me?
Here is my code blow
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:erg_app/ProfilePage.dart';
void main() => runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: StockPage(),
)
);
class StockPage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inventory Data',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: StockInventory(),
);
}
}
class StockInventory extends StatefulWidget {
StockInventory({Key key}) : super(key: key); //Find out meaning
#override
_StockInventoryState createState() => _StockInventoryState();
}
class _StockInventoryState extends State<StockInventory> {
List<Products> products;
List<Products> selectedProducts;
bool sort;
#override
void initState() {
sort = false;
selectedProducts = [];
products = Products.getProducts();
super.initState();
}
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
products.sort((a, b) => a.name.compareTo(b.name));
} else {
products.sort((a, b) => b.name.compareTo(a.name));
}
}
}
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: new Center(child: new Text('Daily Stock Taking', textAlign: TextAlign.center)),
automaticallyImplyLeading: false,
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,),
body: Container(
child: ListView(
children: <Widget>[
Container(
margin: const EdgeInsets.only(right: 20, top: 20),
child: Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
padding: EdgeInsets.fromLTRB(14, 10, 14, 10),
color: Colors.green,
child: Text("Take Inventory", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14), ),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
showSimpleCustomDialog(context);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
Container(
padding: EdgeInsets.only(top: 30, bottom: 30),
child: DataTable(
sortAscending: sort,
sortColumnIndex: 0,
columns: [
DataColumn(
label: Text("S/No", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Item", style: TextStyle(fontSize: 16)),
numeric: false,
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
DataColumn(
label: Text("QtyInStock", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Unit", style: TextStyle(fontSize: 16)),
numeric: false,
),
],
rows: products
.map(
(product) => DataRow(
selected: selectedProducts.contains(product),
cells: [
DataCell(
Text(product.count),
onTap: () {
print('Selected ${product.count}');
},
),
DataCell(
Text(product.name),
onTap: () {
print('Selected ${product.name}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
]),
).toList(),
),
),
Container(
child: Center(
child: RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: Text("Post Inventory", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14), ),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
],
),
),
);
}
}
class Products {
String count;
String name;
String measuringunit;
String itemqty;
Products({this.count, this.name, this.itemqty, this.measuringunit});
static List<Products> getProducts() {
return <Products>[
Products(count:"1", name: "NPK Fertilizer", itemqty: "50", measuringunit: "bag",),
Products(count:"2", name: "Urea Fertilizer", itemqty: "560", measuringunit: "bag",),
Products(count:"3", name: "Spray", itemqty: "150", measuringunit: "bottles",),
];
}
}
void showSimpleCustomDialog(BuildContext context) {
String dropdownValue = 'SelectItem';
// TextEditingController _controller = TextEditingController(text: dropdownValue);
Dialog simpleDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: Container(
height: 300.0,
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top:20, bottom: 20, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(child:
Text(
'Item',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, ),
),
),
Container(width: 2,),
Container(
child:DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
// This set state is trowing an error
setState((){
dropdownValue = newValue;
});
},
items: <String>['Fertilizers', 'Bags', 'Spray', 'Equipments']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
})
.toList(),
),
),
],
)),
Padding(
padding: EdgeInsets.only(top:5, bottom: 5, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(child:
Text(
'Quantity',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, ),
),
),
Container(width: 2,),
Expanded(child: TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Quantity',
hintText: 'Enter Cost Quantity',
border:OutlineInputBorder(borderRadius: BorderRadius.circular(5.0))
),
)),
],
)),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Add',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
SizedBox(
width: 20,
),
RaisedButton(
color: Colors.red,
onPressed: () {
Navigator.pop(context);
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => StockPage()));
},
child: Text(
'Cancel!',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
)
],
),
),
],
),
),
);
showDialog(context: context, builder: (BuildContext context) => simpleDialog);
}
// Dropdown Menu Class below

Maybe I think that using the Statefulbuilder for the dialog. So you can change the state there just check the sample example.
Change as per you needs :
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: StockPage(),
));
class StockPage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inventory Data',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: StockInventory(),
);
}
}
class StockInventory extends StatefulWidget {
StockInventory({Key key}) : super(key: key); //Find out meaning
#override
_StockInventoryState createState() => _StockInventoryState();
}
class _StockInventoryState extends State<StockInventory> {
List<Products> products;
List<Products> selectedProducts;
bool sort;
#override
void initState() {
super.initState();
sort = false;
selectedProducts = [];
products = Products.getProducts();
}
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
products.sort((a, b) => a.name.compareTo(b.name));
} else {
products.sort((a, b) => b.name.compareTo(a.name));
}
}
}
void showSimpleCustomDialog(BuildContext context) {
String dropdownValue ;
// TextEditingController _controller = TextEditingController(text: dropdownValue);
AlertDialog simpleDialog1 = AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
content: StatefulBuilder(
builder :(BuildContext context, StateSetter setState) {
return Container(
height: 300.0,
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding:
EdgeInsets.only(top: 20, bottom: 20, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'Item',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: 2,
),
Container(
child: DropdownButton<String>(
hint: Text('Enter value'),
value: dropdownValue,
onChanged: (String newValue) {
// This set state is trowing an error
setState(() {
dropdownValue = newValue;
});
},
items: <String>[
'Fertilizers',
'Bags',
'Spray',
'Equipments'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
),
),
],
)),
Padding(
padding:
EdgeInsets.only(top: 5, bottom: 5, left: 30, right: 10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'Quantity',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: 2,
),
Expanded(
child: TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Quantity',
hintText: 'Enter Cost Quantity',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
)),
],
)),
Padding(
padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.blue,
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Add',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
SizedBox(
width: 20,
),
RaisedButton(
color: Colors.red,
onPressed: () {
Navigator.pop(context);
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => StockPage()));
},
child: Text(
'Cancel!',
style: TextStyle(fontSize: 18.0, color: Colors.white),
),
)
],
),
),
],
),
);
}
),
);
/* Dialog simpleDialog = Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child:
); */
showDialog(
context: context, builder: (BuildContext context) => simpleDialog1);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Center(
child: new Text('Daily Stock Taking', textAlign: TextAlign.center)),
automaticallyImplyLeading: false,
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
child: ListView(
children: <Widget>[
Container(
margin: const EdgeInsets.only(right: 20, top: 20),
child: Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
padding: EdgeInsets.fromLTRB(14, 10, 14, 10),
color: Colors.green,
child: Text(
"Take Inventory",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (context) => ProfilePage()));
showSimpleCustomDialog(context);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
Container(
padding: EdgeInsets.only(top: 30, bottom: 30),
child: DataTable(
sortAscending: sort,
sortColumnIndex: 0,
columns: [
DataColumn(
label: Text("S/No", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Item", style: TextStyle(fontSize: 16)),
numeric: false,
onSort: (columnIndex, ascending) {
setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
DataColumn(
label: Text("QtyInStock", style: TextStyle(fontSize: 16)),
numeric: false,
),
DataColumn(
label: Text("Unit", style: TextStyle(fontSize: 16)),
numeric: false,
),
],
rows: products
.map(
(product) => DataRow(
selected: selectedProducts.contains(product),
cells: [
DataCell(
Text(product.count),
onTap: () {
print('Selected ${product.count}');
},
),
DataCell(
Text(product.name),
onTap: () {
print('Selected ${product.name}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
DataCell(
Text(product.itemqty),
onTap: () {
print('Selected ${product.itemqty}');
},
),
]),
)
.toList(),
),
),
Container(
child: Center(
child: RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: Text(
"Post Inventory",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => ProfilePage()));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
],
),
),
);
}
}
class Products {
String count;
String name;
String measuringunit;
String itemqty;
Products({this.count, this.name, this.itemqty, this.measuringunit});
static List<Products> getProducts() {
return <Products>[
Products(
count: "1",
name: "NPK Fertilizer",
itemqty: "50",
measuringunit: "bag",
),
Products(
count: "2",
name: "Urea Fertilizer",
itemqty: "560",
measuringunit: "bag",
),
Products(
count: "3",
name: "Spray",
itemqty: "150",
measuringunit: "bottles",
),
];
}
}
class ProfilePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container();
}
}
Just check the code.
Let me know if it works

Related

Flutter complains about undefined var, however i defined it

I created 2 pages, in first one i have TextField to pass data to second one.
In second file i created class and Text class to output the phone number, but compiler says it's undefined. Both Class and Text() are in same dart file.
Class with constructor:
class ProfilePage extends StatefulWidget {
final String phonenum;
const ProfilePage({Key? key, required this.phonenum}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
Text Class that must output name
Text(phonenum),
Function in first file to pass the phone number
void _submit() {
Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,)); // (constructors name: class member)
Navigator.push(context, route);
}
Page 1 code:
import 'package:flutter/material.dart';
import 'package:untitled/pages/ProfilePage.dart';
import 'package:untitled/pages/StadiumPage.dart';
void main() {
runApp(LogInPage());
}
class LogInPage extends StatefulWidget {
const LogInPage({Key? key}) : super(key: key);
#override
_LogInPageState createState() => _LogInPageState();
}
class _LogInPageState extends State<LogInPage> {
String _phonenumber = '';
#override
Widget build(BuildContext context) {
double _wid = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 180,
),
Container(
margin: EdgeInsets.only(left: 40),
width: _wid,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'stadion.kg',
style: TextStyle(
fontSize: 35,
color: Colors.redAccent,
fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Text(
'Добро пожаловать!',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
SizedBox(height: 50),
Text(
'Номер телефона:',
style: TextStyle(fontSize: 15, color: Colors.redAccent),
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 40),
child: TextField(
keyboardType: TextInputType.phone,
onChanged: (value) {
_phonenumber = value;
},
maxLength: 9,
decoration: InputDecoration(
prefixIcon: Icon(Icons.phone), prefixText: '+996'))),
SizedBox(height: 45),
ElevatedButton(
onPressed: _submit,
child: Text('Войти'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 140, vertical: 15),
primary: Colors.redAccent),
),
SizedBox(height: 10),
TextButton(
onPressed: _submitnoregist,
child: Text(
'Продолжить без регистрации!',
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
))
],
),
),
);
}
void _submitnoregist() {
Route route = MaterialPageRoute(builder: (context) => HomePage()); // (constructors name: class member)
Navigator.push(context, route);
}
void _submit() {
Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,)); // (constructors name: class member)
Navigator.push(context, route);
}
}
Page 2 Code:
import 'package:flutter/material.dart';
import 'package:untitled/pages/FavoritesPage.dart';
import 'package:untitled/pages/MapPage.dart';
import 'package:untitled/pages/StadiumPage.dart';
class ProfilePage extends StatefulWidget {
final String phonenum;
const ProfilePage({Key? key, required this.phonenum}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
int _selind = 0;
List<Widget> _widgetopt = <Widget>[
Text('Index 4'),
Text('Index 2'),
Text('Index 3'),
Text('Index 4'),
];
void OnBeingTapped(int index) {
setState(() {
_selind = index;
if (index == 0) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
} else if (index == 1) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => MapPage()));
} else if (index == 2) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => FavoritesPage()));
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.indigo[50],
appBar: AppBar(
title: Text('Профиль', style: TextStyle(color: Colors.black)),
backgroundColor: Colors.white,
toolbarHeight: 80,
centerTitle: true,
),
body: Column(
children: [
SizedBox(
height: 20,
),
Center(
child: Column(
children: [
CircleAvatar(
backgroundImage: AssetImage('lib/assets/ava.jpg'),
maxRadius: 60,
),
SizedBox(
height: 20,
),
Text(
'Неизвестный\nпользователь',
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 25),
),
SizedBox(
height: 10,
),
Text(phonenum,
style: TextStyle(color: Colors.redAccent, fontSize: 20)),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 1.5,
offset: Offset(
1.5, // horizontal, move right 10
1.5, // vertical, move down 10
),
)
],
color: Colors.white,
border: Border.all(color: Colors.white70),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: ButtonBar(
alignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text('Пользовательское соглашение',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
]),
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Пригласить друзей',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
],
),
),
TextButton(
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Выйти',
style: TextStyle(
color: Colors.black, fontSize: 20)),
Icon(
Icons.arrow_forward_ios_rounded,
color: Colors.black,
)
],
),
),
SizedBox(
height: 30,
),
],
),
),
)
],
),
)
],
),
bottomNavigationBar: SizedBox(
height: 80,
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.white,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.add_box_outlined,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.location_on_outlined,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.favorite_outline,
color: Colors.black,
),
label: ''),
BottomNavigationBarItem(
icon: Icon(
Icons.person_outline_outlined,
color: Colors.black,
),
label: ''),
],
currentIndex: _selind,
selectedItemColor: Colors.yellow,
onTap: OnBeingTapped,
),
),
),
title: 'Stadium',
);
}
}
phonenum is a class variable of ProfilePage and _ProfilePageState cannot access it directly. Because _ProfilePageState is a State class of ProfilePage you have a property called widget that you can use to access variables of ProfilePage class.
So your code should be like that:
Text(
widget.phonenum,
...
...
)

Flutter: Whenever I pressed on Home button I redirect to Login Screen

I made a simple app where I am using firebase authentication
I used Side drawer in this app
The app work fine on all other tabs but when ever I pressed home button from side drawer instead of going to home screen(initial page route) Login Page comes out and If on the same time I Hot Reload the app then I automatically re-direct to home Screen
2 days ago the app is working currently fine but today this is happening.
Here is my Main.dart file:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
static const myApproute = 'myapproue';
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final screen = [
const HomePage(),
AnnoucementScreen(),
const AdminScreen(),
const SettingsScreen(),
];
int currentIndex = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
pageTransitionsTheme: PageTransitionsTheme(
builders: {
TargetPlatform.android: CustomPageTransitionBuilder(),
},
),
),
home: StreamBuilder(
stream: Login().firebaseAuth.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
body: screen[currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showUnselectedLabels: false,
selectedItemColor: Colors.black,
unselectedItemColor: Colors.grey,
currentIndex: currentIndex,
// onTap: (value) => setState(() => currentIndex = value),
onTap: (value) {
setState(() {
currentIndex = value;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(Icons.event), label: 'Announcement'),
BottomNavigationBarItem(
icon: Icon(Icons.admin_panel_settings), label: 'Admin'),
BottomNavigationBarItem(
icon: Icon(Icons.settings_accessibility_sharp),
label: 'Profile'),
],
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const LoginScreen();
}),
routes: {
MyApp.myApproute: (context) => const MyApp(),
LoginScreen.rout: (context) => const LoginScreen(),
SignUpScreen.signUpRout: (context) => const SignUpScreen(),
BabaHassanLifeIntroScreen.babaHassanPageRout: (context) =>
const BabaHassanLifeIntroScreen(),
BabahafizIqbalLifeIntroScreen.babaHafizIqbalRout: (context) =>
const BabahafizIqbalLifeIntroScreen(),
BabaHassanMizajScreen.babaSaiMijazRout: (context) =>
const BabaHassanMizajScreen(),
BabaHassanLifeIncident.babaHassanLifeincident: (context) =>
const BabaHassanLifeIncident(),
BabaHafizIqbalMizajScreen.babaHafizIqbalMizajScreenRoute: (context) =>
const BabaHafizIqbalMizajScreen(),
BabaHafizIqbalLifeIncidentScreen.babaHafizIqbalLifeIncidentScreenRoute:
(context) => const BabaHafizIqbalLifeIncidentScreen(),
TasheerActivitiesScree.tasheerActivitiesScreeRoute: (context) =>
const TasheerActivitiesScree(),
DarbarIntroScreen.darbarIntroScreenRoute: (context) =>
const DarbarIntroScreen(),
ShujraShareefScreen.shujraShareefScreenRoute: (context) =>
const ShujraShareefScreen(),
MusabaEelaafScreen.musabaEelaafScreenRoute: (context) =>
const MusabaEelaafScreen(),
MusabaEelaafBunyadScreen.musbaEelaafBunyadScreenRoute: (context) =>
const MusabaEelaafBunyadScreen(),
BooksScreen.booksScreenRoute: (context) => const BooksScreen(),
SettingMenu.settingMenuRoute: (context) => SettingMenu(),
AdminHome.adminHomeRoute: (context) => AdminHome(),
CreateEvent.createEventRoute: (context) => const CreateEvent(),
SettingMenuAccount.settingMenuAccountRoute: (context) =>
const SettingMenuAccount(),
FeedBackForm.feedBackFormRoute: (context) => const FeedBackForm(),
HomePage.homeRout: (context) => const HomePage(),
},
);
}
}
Here is my sideDrawer.dart file:
class SideDrawer extends StatefulWidget {
const SideDrawer({super.key});
#override
State<SideDrawer> createState() => _SideDrawerState();
}
class _SideDrawerState extends State<SideDrawer> {
var _expanded = false;
var _expandedTwo = false;
//var _expandedThree = false;
var _expandedFive = false;
#override
Widget build(BuildContext context) {
MediaQueryData mediaQueryData;
mediaQueryData = MediaQuery.of(context);
return Drawer(
width: mediaQueryData.size.width * 0.7,
child: ListView(
children: <Widget>[
DrawerHeader(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
gradient: LinearGradient(colors: [
Colors.black,
Color.fromRGBO(255, 243, 18, 3),
], begin: Alignment.topLeft, end: Alignment.bottomRight),
),
child: Padding(
padding: const EdgeInsets.only(top: 70),
child: Column(
children: const [
Text(
"Musaba-Tul-Eelaad",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
textAlign: TextAlign.justify,
),
Text(
"مثابۃ ایلاف",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
textAlign: TextAlign.justify,
),
],
),
),
),
ListTile(
title: const Text(
"Home Page",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
onTap: () {
Navigator.of(context).pushReplacementNamed('/');
},
),
const Divider(),
ListTile(
title: const Text(
"Introduction (تعارف)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expanded = !_expanded;
});
},
),
if (_expanded)
Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'شجرہ شریف',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
ShujraShareefScreen.shujraShareefScreenRoute);
},
),
),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'مثابۃ ایلاف',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
MusabaEelaafScreen.musabaEelaafScreenRoute);
},
),
),
],
),
const Divider(),
ListTile(
title: const Text(
"About Ourself (ہمارے بارے میں)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing:
Icon(_expandedTwo ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expandedTwo = !_expandedTwo;
});
},
),
if (_expandedTwo)
Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: ListTile(
title: const Text(
'باباسائیں حسن الدینؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onTap: () {
Navigator.of(context).pushReplacementNamed(
BabaHassanLifeIntroScreen.babaHassanPageRout);
},
),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: ListTile(
title: const Text(
'حافظ سائیں محمداقبالؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onTap: () {
Navigator.of(context).pushReplacementNamed(
BabahafizIqbalLifeIntroScreen.babaHafizIqbalRout);
}),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'تشہیر اور سرگرمیاں',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
TasheerActivitiesScree.tasheerActivitiesScreeRoute);
},
),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'دربار باباسائیں حسن الدینؒ و حافظ سائیں محمد اقبالؒ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.center,
),
onPressed: () {
Navigator.of(context).pushReplacementNamed(
DarbarIntroScreen.darbarIntroScreenRoute);
},
),
),
],
),
const Divider(),
ListTile(
title: const Text(
"Gallery (گیلری)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
// trailing:
// Icon(_expandedThree ? Icons.expand_less : Icons.expand_more),
onTap: () {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Attention Required"),
content: const Text(
"The gallery content is currently Under-Development.You will be notified when its ready for you. Please make sure you enable notification to get Future updates"),
actions: [
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text("Okay"))
],
),
);
// setState(() {
// _expandedThree = !_expandedThree;
// });
},
),
const Divider(),
ListTile(
title: const Text(
"Books (قطب)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
onTap: () {
Navigator.of(context)
.pushReplacementNamed(BooksScreen.booksScreenRoute);
},
),
const Divider(),
ListTile(
title: const Text(
"Cermony (تقریب)",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 18),
),
trailing:
Icon(_expandedFive ? Icons.expand_less : Icons.expand_more),
onTap: () {
setState(() {
_expandedFive = !_expandedFive;
});
},
),
if (_expandedFive)
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 20),
child: TextButton(
child: const Text(
'۱۳رجب۱۴۴۱۔۲۰۱۹',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16),
textAlign: TextAlign.right,
),
onPressed: () => {},
),
)
],
),
],
),
);
}
}
Here is my Login Screen File:
class LoginScreen extends StatefulWidget {
static const rout = '/login-screen';
const LoginScreen({super.key});
#override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final Map<String, String> _loginData = {'email': '', 'password': ''};
GlobalKey topWidgetKey = GlobalKey();
GlobalKey bottomWidgetKey = GlobalKey();
double topWidgetHeight = 0.0;
double bottomWidgetHeight = 0.0;
double spacer = 0.0;
var isLoading = false;
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() {
final topWidgetKeyContextt = topWidgetKey.currentContext;
if (topWidgetKeyContextt != null) {
final box = topWidgetKeyContextt.findRenderObject() as RenderBox;
topWidgetHeight = box.size.height;
}
final bottomWidgetKeyContextt = bottomWidgetKey.currentContext;
if (bottomWidgetKeyContextt != null) {
final box = bottomWidgetKeyContextt.findRenderObject() as RenderBox;
bottomWidgetHeight = box.size.height;
}
spacer = MediaQuery.of(context).size.height -
AppBar().preferredSize.height -
topWidgetHeight -
bottomWidgetHeight -
MediaQuery.of(context).viewPadding.top -
MediaQuery.of(context).viewPadding.bottom;
});
}
});
super.initState();
}
final _emailController = TextEditingController();
final _form = GlobalKey<FormState>();
final _passwordController = TextEditingController();
var visible = true;
final emailVerificationSyntax = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+");
void _errorDialog(String message) {
showDialog(
context: context,
builder: ((ctx) => AlertDialog(
title: const Text("An Error Accourd"),
content: Text(message),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: const Text("Okay"))
],
)),
);
}
void push() {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (_) => const MyApp(),
),
(route) => false);
}
Future<void> _saveData() async {
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
setState(() {
isLoading = true;
});
try {
await Login().signInUser(_loginData['email'].toString(),
_loginData['password'].toString(), context);
push();
} catch (e) {
var errorMessage = 'Authentication Failed';
if (e.toString().contains('INVALID_EMAIL')) {
errorMessage = 'The email adress is not valid';
} else if (e.toString().contains('EMAIL_NOT_FOUND')) {
errorMessage = 'No User found with this Email';
} else if (e.toString().contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid Password';
}
_errorDialog(errorMessage);
}
setState(() {
isLoading = false;
});
}
#override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromRGBO(255, 243, 18, 3),
body: SingleChildScrollView(
child: Form(
key: _form,
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 90),
child: Image.asset('assets/images/Logo.png'),
),
const SizedBox(
height: 10,
),
const SafeArea(
child: Padding(
padding: EdgeInsets.only(left: 3, right: 250, top: 10),
child: Text(
"Login",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 40),
// textAlign: TextAlign.center,
),
),
),
const Padding(
padding: EdgeInsets.only(left: 20, right: 200, top: 3),
child: Text(
"Please Login to continue",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.normal,
fontSize: 15),
// textAlign: TextAlign.center,
),
),
const SizedBox(
height: 15,
),
Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
shadowColor: Colors.grey,
elevation: 10,
child: TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email-Address',
prefixIcon: Icon(
(Icons.person),
),
border: OutlineInputBorder(borderSide: BorderSide.none),
),
onSaved: (newValue) {
_loginData['email'] = newValue!;
},
validator: (value) {
if (!emailVerificationSyntax.hasMatch(value as String)) {
return "Incorrect Email-Adress Syntax";
}
if (value.isEmpty) {
return 'Please Enter Your Email Adress';
}
return null;
},
),
),
const SizedBox(
height: 15,
),
Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
shadowColor: Colors.grey,
elevation: 10,
child: TextFormField(
controller: _passwordController,
obscureText: visible,
keyboardType: TextInputType.streetAddress,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: const Icon(
(Icons.password),
),
suffixIcon: IconButton(
onPressed: () {
setState(() {
visible = !visible;
});
},
icon: const Icon(Icons.visibility)),
border: const OutlineInputBorder(borderSide: BorderSide.none),
),
validator: (value) {
if (value!.isEmpty) {
return "Please Enter Your Passowrd";
}
return null;
},
onSaved: (newValue) {
_loginData['password'] = newValue!;
},
),
),
const SizedBox(
height: 15,
),
isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: () => _saveData(),
style: ElevatedButton.styleFrom(
// backgroundColor: Color.fromARGB(255, 246, 214, 4)),
backgroundColor: Colors.white),
child: const Text(
'Login',
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontWeight: FontWeight.normal,
),
),
),
const SizedBox(
height: 100,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Don't have an account?",
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 20),
child: TextButton(
onPressed: () {
Navigator.of(context)
.pushReplacementNamed(SignUpScreen.signUpRout);
},
child: const Text(
"Sign Up",
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold),
)),
)
],
)
]),
),
),
);
}
}
This is my project I m currently working on and now when the time comes to deliver it this is happen I tried a-lot but not figure it out.

Why am I having memory issues with flutter ChangeNotifierProvider?

I am making a shopping cart app in flutter with Change Notifier Provider. It is working fast and well at first. But it takes the more memory, the more I use it. I am adding and removing clearing items from list. Nothing complicated. Cannot know why it is working like this. It is slowing down gradually. This is main.dart:
class Main extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Cart(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: swatchColor,
primaryColor: primaryColor,
accentColor: tertiaryColor,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.black,
selectionColor: primaryColor,
selectionHandleColor: primaryColor,
),
),
initialRoute: '/login',
routes: {
'/home': (context) => Home(),
'/login': (context) => Login(),
'/tableReview': (context) => TableReview(),
'/createOrder': (context) => CreateOrder(),
'/orderReview': (context) => OrderReview(),
},
),
);
}
}
This is main cart_model.dart
import 'package:counter/data/models/cart_item.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
class Cart extends ChangeNotifier {
List<Item> cart = [];
addItemToCart({#required item}) {
Item newItem = Item(
id: item.id,
price: item.price is int ? item.price : int.parse(item.price),
title: item.title,
);
int i = cart.indexWhere((previousItem) => previousItem.id == newItem.id);
if (i > -1) {
cart[i].count++;
} else {
cart.add(newItem);
}
notifyListeners();
}
removeItemFromCart({#required item}) {
int index = cart.indexWhere((element) => element.id == item.id);
if (index > -1) {
if (cart[index].count > 1) {
cart[index].count--;
} else {
cart.removeWhere((element) => element.id == item.id);
}
}
notifyListeners();
}
clearCart() {
cart.clear();
notifyListeners();
}
int get totalPrice =>
cart.fold(0, (total, current) => total + (current.price * current.count));
}
This is menuitem.dart
class MenuItem extends StatelessWidget {
final dynamic foodItem;
MenuItem({#required this.foodItem});
void _showSecondPage(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) => Scaffold(
backgroundColor: Colors.black45,
body: Center(
child: Hero(
tag: foodItem.imgPath,
child: Image(image: NetworkImage(base_url + foodItem.imgPath)),
),
),
),
),
);
}
#override
Widget build(BuildContext context) {
int itemIndex = Provider.of<Cart>(context, listen: false)
.cart
.indexWhere((item) => item.id == foodItem.id);
return Container(
height: 80,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _showSecondPage(context),
child: Hero(
tag: foodItem.imgPath,
child: CircleAvatar(
backgroundImage: NetworkImage(base_url + foodItem.imgPath),
),
),
),
SizedBox(
width: 15,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
foodItem.title,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
Text('${foodItem.price.toString()} сум'),
],
)
],
),
Container(
width: 160,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon:
Icon(Icons.remove, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
Text(
itemIndex > -1
? '${Provider.of<Cart>(context).cart[itemIndex].count}'
: '0',
style: TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(Icons.add, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
],
),
),
],
),
);
}
}
This is consumer part:
import 'package:counter/common/socketio.dart';
import 'package:counter/data/models/cart_model.dart';
import 'package:counter/presentation/widgets/empty_cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class OrderReview extends StatefulWidget {
#override
_OrderReviewState createState() => _OrderReviewState();
}
class _OrderReviewState extends State<OrderReview> {
bool isCommentEnabled = false;
String guestCount;
String comment = '';
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
final myCart = context.watch<Cart>();
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text('Проверка заказа'),
),
body: Builder(
builder: (context) {
if (myCart.cart.length > 0) {
handleOrderCreate() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userId = prefs.getString('userId');
String tableNum = prefs.getString('tableNum');
String status = 'accepted';
print('$userId, $tableNum, $status');
Map orderToCreate = {
'tableNum': tableNum,
'status': 'accepted',
'userId': userId,
'guestCount': guestCount,
'comment': comment,
'foodList': myCart.cart
};
socketIO.emit('createOrder', json.encode(orderToCreate));
Navigator.of(context).pushNamed('/home');
Provider.of<Cart>(context, listen: false).clearCart();
}
return GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(new FocusNode()),
child: LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: IntrinsicHeight(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Form(
key: _formKey,
child: Column(
children: [
Container(
height: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color:
Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0,
3), // changes position of shadow
),
]),
child: ListView.separated(
itemBuilder:
(BuildContext context, int i) {
return ListTile(
title: Text(myCart.cart[i].title),
trailing: Container(
width: 160,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.remove,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.removeItemFromCart(
item: myCart
.cart[i]);
},
),
Text(
'${myCart.cart[i].count}',
style:
TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(
Icons.add,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.addItemToCart(
item: myCart
.cart[i]);
},
),
],
),
),
);
},
separatorBuilder:
(BuildContext context, int) {
return Divider(
height: 2,
color: Colors.grey,
);
},
itemCount: myCart.cart.length,
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Количество гостей',
),
onChanged: (newValue) {
setState(() => guestCount = newValue);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'Пожалуйста, введите количество гостей!';
}
return null;
},
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
onChanged: (newValue) {
setState(() => comment = newValue);
},
enabled: isCommentEnabled,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText:
'Лаваш острый, хот дог без майонеза и т.д.',
// labelText: 'Комментарий',
),
maxLines: 2,
),
),
Row(
children: [
Text('Комментарий'),
Switch(
value: isCommentEnabled,
onChanged: (bool value) {
setState(() =>
this.isCommentEnabled = value);
},
),
],
)
],
),
),
SizedBox(height: 20),
Row(
children: [
Text(
'Общая цена: ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
SizedBox(width: 20),
Text(
'${myCart.totalPrice} сум',
style: TextStyle(fontSize: 18),
),
],
),
Container(
height: 50,
width: 170,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.resolveWith(
(states) =>
Theme.of(context).primaryColor),
),
onPressed: () {
if (_formKey.currentState.validate()) {
handleOrderCreate();
}
},
child: Text(
'Отправить',
style: TextStyle(
color: Colors.white, fontSize: 18),
),
),
),
],
),
),
),
),
);
},
),
);
} else {
print('111');
return EmptyCart();
}
},
),
);
}
}
Is there something wrong with my code?

How To Dynamically add Dropdown buttons or delete dropdown(s) in listview with flutter Web?

i have created a page where a user who will click a title to edit the contents and can add and delete devices that the article is attached to,
but i could not figure it out on how to program the drop down dynamically, to add more drop downs when a user press the add device button,
the additional function they want me to add as well is on the Dropdown list, when they select 'NONE' it should remove that dropdown as well,
i am planning to use mysql,xampp or sqlite for my database if im done with the UI,
import 'package:flutter/material.dart';
import 'package:surveyadminpanel/Contents/tabbar.dart';
import 'package:surveyadminpanel/widgets/button.dart';
import 'package:surveyadminpanel/widgets/simplewidgets.dart';
import 'homepage.dart';
import 'dart:ui';
class Item {
Item(this.name);
String name;
}
class editsurvey extends StatefulWidget {
#override
_editsurveyState createState() => _editsurveyState();
}
class _editsurveyState extends State<editsurvey>{
int surveyquestionnum = 1;
int surveyquestiontotal = 1;
List<Item> selectedUser = [null, null];
List<Item> selecteddata = [null, null];
List<Item> users;
int linkdevices = 1;
String dropdownvalue= "SELECT FROM DROPDOWN";
List data = [
'Sample Data 1',
'Sample Data 2',
'Sample Data 3',
'Sample Data 4',
'Sample Data 5',
'Sample Data 6',
];
#override
void initState() {
super.initState();
users = <Item>[
Item('Sample device 1'),
Item('Sample device 2'),
Item('Sample device 3'),
Item('Sample device 4'),
];
}
#override
Widget _dropdownbutton (List<Item> userlist, int index){
return Container(
padding: EdgeInsets.all(1),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(15.0) //
),
),
child: DropdownButton<Item>(
underline: SizedBox(),
isExpanded: true,
icon: Icon(Icons.arrow_drop_down),
hint: Text(" $dropdownvalue"),
value: selectedUser[index],
onChanged: (Item Value) {
setState(() {
selectedUser[index] = Value;
});
},
items: userlist.map((Item user) {
return DropdownMenuItem<Item>(
value: user,
child: Row(
children: <Widget>[
SizedBox(width: 10,),
Text(
user.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
);
}
Widget _text(texthere,bold,size,color){
return Text(texthere,style: TextStyle(fontWeight: bold,fontSize: size,color: color),overflow: TextOverflow.ellipsis,maxLines: 1);
}
Widget _logo(){
return InkWell(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => admincontent()),
);
},
child: Container(width: 500,height: 200,child: Image.asset("images/v2.jpg")));
}
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Padding(padding: EdgeInsets.only(left: 30),
child: RichText(
text: TextSpan(
text: 'Good Morning Welcome to Sample:',
style: TextStyle(
color: Colors.blueAccent, fontSize: 18),
children: <TextSpan>[
TextSpan(text: usernametitle,
style: TextStyle(
color: Colors.black, fontSize: 18),
)
]
),
)
),
elevation: 1,
automaticallyImplyLeading: false,
backgroundColor: Colors.white,
leading: _logo(),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
color: Colors.blueAccent,
tooltip: 'Show Notification',
onPressed: () {
},
),
IconButton(
color: Colors.lightGreen,
icon: const Icon(Icons.account_circle),
tooltip: 'Check your Profile',
onPressed: () {
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_text("EDIT SURVEY", FontWeight.bold, 20,Colors.blue),
roundedRectButton("BACK", signInGradients),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
width: screenWidth/1.6,
height: screenHeight/1.6,
decoration: BoxDecoration(
color: Colors.orange[200],
borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_text("SURVEY TITLE", FontWeight.bold, 17,Colors.white),
_text(data[0], FontWeight.bold, 19, Colors.black),
_text("DATE CREATED", FontWeight.bold, 17,Colors.white),
_text(data[1], null, 19, Colors.black),
_text("CURRENT STATUS", FontWeight.bold, 17,Colors.white),
_text(data[2], null, 19, Colors.black),
_text("LANGUAGE VERSION", FontWeight.bold, 17,Colors.white),
_text(data[3], null, 19, Colors.black),
_text("NUMBERS OF ASSESSORS", FontWeight.bold, 17,Colors.white),
_text(data[4], null, 19, Colors.black),
_text("TOTAL RENDERED SURVEYS", FontWeight.bold, 17,Colors.white),
_text(data[5], null, 19, Colors.black),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: (){
},
child: Container(width: 100,height: 50,child: Text("EDIT SURVEY")),
),
_text("LINKED DEVICES : $linkdevices", FontWeight.bold, 17,Colors.white),
],
)
],
),
)
),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 1.0,
style: BorderStyle.solid
)
),
width: screenWidth/1.6,
height: screenHeight/1.6,
child: Column(
children: <Widget>[
_text("DEVICES PINNED", FontWeight.bold, 20,Colors.blue),
ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index){
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
child: roundedRectButton("ADD DEVICE", signInGradients),
onTap: (){
},
),
InkWell(
child: roundedRectButton("CLEAR ALL DEVICE", signInGradients),
onTap: (){
},
),
],
),
],
),
),
],
)
],
),
),
),
);
}
}
The Plan
The Result
im still trying to figure this out, but if someone can give me a lift,, im gonna be very thankful to who can help me out here ,,
You can copy paste run full code below
You can increase linkdevices and selectedUser
code snippet
List<Item> selectedUser = [null];
...
InkWell(
child: Text("ADD DEVICE"),
onTap: () {
selectedUser.add(null);
linkdevices ++;
setState(() {
});
working demo
full code
import 'package:flutter/material.dart';
class Item {
Item(this.name);
String name;
}
class editsurvey extends StatefulWidget {
#override
_editsurveyState createState() => _editsurveyState();
}
class _editsurveyState extends State<editsurvey> {
int surveyquestionnum = 1;
int surveyquestiontotal = 1;
List<Item> selectedUser = [null];
List<Item> selecteddata = [null, null];
List<Item> users;
int linkdevices = 1;
String dropdownvalue = "SELECT FROM DROPDOWN";
List data = [
'Sample Data 1',
'Sample Data 2',
'Sample Data 3',
'Sample Data 4',
'Sample Data 5',
'Sample Data 6',
];
#override
void initState() {
super.initState();
users = <Item>[
Item('Sample device 1'),
Item('Sample device 2'),
Item('Sample device 3'),
Item('Sample device 4'),
];
}
#override
Widget _dropdownbutton(List<Item> userlist, int index) {
return Container(
padding: EdgeInsets.all(1),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(Radius.circular(15.0) //
),
),
child: DropdownButton<Item>(
underline: SizedBox(),
isExpanded: true,
icon: Icon(Icons.arrow_drop_down),
hint: Text(" $dropdownvalue"),
value: selectedUser[index],
onChanged: (Item Value) {
print(Value.toString());
print(index);
setState(() {
selectedUser[index] = Value;
});
},
items: userlist.map((Item user) {
return DropdownMenuItem<Item>(
value: user,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
user.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
),
);
}
Widget _text(texthere, bold, size, color) {
return Text(texthere,
style: TextStyle(fontWeight: bold, fontSize: size, color: color),
overflow: TextOverflow.ellipsis,
maxLines: 1);
}
Widget _logo() {
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => admincontent()),
);
},
child: Container(
width: 500, height: 200, child: Image.asset("images/v2.jpg")));
}
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Padding(
padding: EdgeInsets.only(left: 30),
child: RichText(
text: TextSpan(
text: 'Good Morning Welcome to Sample:',
style: TextStyle(color: Colors.blueAccent, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: "usernametitle",
style: TextStyle(color: Colors.black, fontSize: 18),
)
]),
)),
elevation: 1,
automaticallyImplyLeading: false,
backgroundColor: Colors.white,
leading: _logo(),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.notifications),
color: Colors.blueAccent,
tooltip: 'Show Notification',
onPressed: () {},
),
IconButton(
color: Colors.lightGreen,
icon: const Icon(Icons.account_circle),
tooltip: 'Check your Profile',
onPressed: () {},
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_text("EDIT SURVEY", FontWeight.bold, 20.0, Colors.blue),
//roundedRectButton("BACK", signInGradients),
Text("BACK"),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
width: screenWidth / 1.6,
height: screenHeight / 1.6,
decoration: BoxDecoration(
color: Colors.orange[200],
borderRadius:
new BorderRadius.all(new Radius.circular(20.0)),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_text("SURVEY TITLE", FontWeight.bold, 17.0,
Colors.white),
_text(data[0], FontWeight.bold, 19.0, Colors.black),
_text("DATE CREATED", FontWeight.bold, 17.0,
Colors.white),
_text(data[1], null, 19.0, Colors.black),
_text("CURRENT STATUS", FontWeight.bold, 17.0,
Colors.white),
_text(data[2], null, 19.0, Colors.black),
_text("LANGUAGE VERSION", FontWeight.bold, 17.0,
Colors.white),
_text(data[3], null, 19.0, Colors.black),
_text("NUMBERS OF ASSESSORS", FontWeight.bold, 17.0,
Colors.white),
_text(data[4], null, 19.0, Colors.black),
_text("TOTAL RENDERED SURVEYS", FontWeight.bold,
17.0, Colors.white),
_text(data[5], null, 19.0, Colors.black),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: () {},
child: Container(
width: 100,
height: 50,
child: Text("EDIT SURVEY")),
),
_text("LINKED DEVICES : $linkdevices",
FontWeight.bold, 17.0, Colors.white),
],
)
],
),
)),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
width: 1.0,
style: BorderStyle.solid)),
width: screenWidth / 1.6,
height: screenHeight / 1.6,
child: Column(
children: <Widget>[
_text("DEVICES PINNED", FontWeight.bold, 20.0,
Colors.blue),
ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
child: Text("ADD DEVICE"),
onTap: () {
selectedUser.add(null);
linkdevices ++;
setState(() {
});
/*listWidget.add( ListView.separated(
shrinkWrap: true,
itemCount: linkdevices,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: _dropdownbutton(users, index),
);
},
separatorBuilder: (context, index) => Container(height: 10),
));
setState(() {
});*/
},
),
InkWell(
child: Text("CLEAR ALL DEVICE"),
onTap: () {},
),
],
),
],
),
),
],
)
],
),
),
),
);
}
}
class admincontent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container();
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: editsurvey(),
);
}
}

How to change a bottom navigation bar icon in the setState() function in flutter?

I'm building a food ordering app in flutter. What I want is, when the user adds items to the cart, I want the cart icon in the bottom navigation bar to obtain a red dot on top to notify the user of the addition of items to the cart.
To achieve this, I have created a global variable called no_of_cart_items and when the user adds an item to the cart, I increment this variable in the setState() function as follows:
setState(() {
GlobalVariables.no_of_cart_items+=1;
// change icon here
});
In this setState() function, I wish to change the icon in the bottom navigation bar. How should I do this?
Thank you.
FULL CODE
This is main.dart
//import lines
void main() => runApp(CanteenApp());
class CanteenApp extends StatefulWidget {
#override
_CanteenAppState createState() => _CanteenAppState();
}
class _CanteenAppState extends State<CanteenApp> {
int _currentindex=0; // index of bottom tab
int admin=GlobalVariables.admin;
BottomNavigationBadge badger = new BottomNavigationBadge(
backgroundColor: Colors.red,
badgeShape: BottomNavigationBadgeShape.circle,
textColor: Colors.white,
position: BottomNavigationBadgePosition.topRight,
textSize: 8);
Widget callpage(int currentIndex) {
switch (currentIndex) {
case 0: return UserProfile();
case 1: return Menu();
case 2: return Cart();
break;
default: return UserProfile();
}
}
#override
Widget build(BuildContext context) {
if(admin==1 && _currentindex==2) {
//if you're the admin and have called the history page
return MaterialApp(
debugShowCheckedModeBanner: false,
home: DefaultTabController(
length: 2,
child: Scaffold(
resizeToAvoidBottomPadding: false,
appBar: PreferredSize(
preferredSize: Size.fromHeight(80.0),
child: AppBar(
bottom: TabBar(
indicatorColor: Colors.white,
indicatorWeight: 5,
tabs: <Widget>[
Tab(
child: Align(
alignment: Alignment.center,
child: Text(
'Order History',
style: TextStyle(
fontSize: 20
),
)
)
),
Tab(
child: Align(
alignment: Alignment.center,
child: Text(
'Deposit / Withdraw\nHistory',
style: TextStyle(
fontSize: 17
),
textAlign: TextAlign.center,
)
)
),
],
),
),
),
body: TabBarView(
children: <Widget>[
AdminOrderHistory(),
DepositWithdrawHistory()
],
),
bottomNavigationBar: BottomNavigationBar(
elevation: 10,
currentIndex: _currentindex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Profile'),
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant_menu),
title: Text('Menu'),
),
BottomNavigationBarItem(
icon: Icon(Icons.history),
title: Text('History'),
),
],
onTap: (index){
setState(() {
_currentindex=index;
});
}
),
),
),
theme: appTheme,
);
}
else if(admin==1){
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
resizeToAvoidBottomPadding: false,
body: callpage(_currentindex),
bottomNavigationBar: BottomNavigationBar(
elevation: 10,
currentIndex: _currentindex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Profile'),
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant_menu),
title: Text('Menu'),
),
BottomNavigationBarItem(
icon: Icon(Icons.history),
title: Text('History'),
),
],
onTap: (index){
setState(() {
_currentindex=index;
});
}
),
),
theme: appTheme,
);
}
else if(admin==0){
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
resizeToAvoidBottomPadding: false,
body: callpage(_currentindex),
bottomNavigationBar:BottomNavigationBar(
elevation: 10,
currentIndex: _currentindex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Profile'),
),
BottomNavigationBarItem(
icon: Icon(Icons.restaurant_menu),
title: Text('Menu'),
),
BottomNavigationBarItem(
title: Text('Cart'),
icon: Badge(
showBadge: true,
badgeContent: Text(
GlobalVariables.no_of_cart_items.toString(),
style: TextStyle(
color: Colors.white
),
),
child: Icon(Icons.shopping_cart)
)
),
],
onTap: (index){
setState(() {
_currentindex=index;
});
}
),
),
theme: appTheme,
);
}
}
}
This is menu.dart
//import lines
int admin=GlobalVariables.admin;
List snacksmenuitems=[
['Vada Pav', 15],
['Samosa Pav', 15],
['Punjabi Samosa', 25],
['Pav', 5]
];
List ricemenuitems=[
['Fried Rice', 62],
['Schezwan Rice', 69],
['Singapore Rice', 69],
['Manchow Rice', 73],
];
class Menu extends StatefulWidget {
#override
_MenuState createState() => _MenuState();
}
class _MenuState extends State<Menu> {
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
MenuTopPart(),
MenuBottomPart(),
],
);
}
}
Color firstColor = Color(0xFFF47D15);
Color secondColor = Color(0xFFEF772C);
class MenuTopPart extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
ClipPath(
clipper: CustomShapeClipper(),
child: Container(
height:140.0,
width:MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [firstColor, secondColor],
)
),
child: Column(
children: <Widget>[
SizedBox(height: 53.0),
Text(
'MENU',
style: TextStyle(
fontSize: 30.0,
color: Colors.white,
),
textAlign: TextAlign.center,
),
],
)
)
)
],
);
}
}
class MenuBottomPart extends StatefulWidget {
#override
_MenuBottomPartState createState() => _MenuBottomPartState();
}
class _MenuBottomPartState extends State<MenuBottomPart> {
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: 10),
SizedBox(height: 10),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
child: Container(
height: MediaQuery
.of(context)
.size
.height * 0.60,
child: ListView(
padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
scrollDirection: Axis.vertical,
children: <Widget>[
Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: ExpansionTile(
title: Text('SNACKS'),
children: snacksmenuitems.map((menuitem) {
//print(menuitem);
return MenuItem(menuitem: menuitem);
/*SizedBox(height:10),
MenuItem(),
SizedBox(height:10),
MenuItem(),
SizedBox(height:10),
MenuItem()*/
}).toList()
),
)
),
SizedBox(height: 10),
Card(
child: Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: ExpansionTile(
title: Text('RICE ITEMS'),
children: ricemenuitems.map((menuitem) {
//print(menuitem);
return MenuItem(menuitem: menuitem);
/*SizedBox(height:10),
MenuItem(),
SizedBox(height:10),
MenuItem(),
SizedBox(height:10),
MenuItem()*/
}).toList()
),
)
)
]
),
),
)
]
);
}
}
class MenuItem extends StatefulWidget {
List menuitem=[];
MenuItem({Key key, this.menuitem}): super(key: key);
#override
_MenuItemState createState() => _MenuItemState();
}
class _MenuItemState extends State<MenuItem> {
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
border: Border.all(color: Colors.black12),
borderRadius: BorderRadius.all(Radius.circular(10))
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image(
image: NetworkImage('https://www.whiskaffair.com/wp-content/uploads/2018/08/Mumbai-Pav-Bhaji-4.jpg'),
width: 80,
height: 80
),
SizedBox(width:10),
Padding(
padding: const EdgeInsets.fromLTRB(0, 5, 0, 0),
child: Container(
width:190,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.menuitem[0],
style: TextStyle(
fontSize:19,
color: Colors.grey[900]
),
),
SizedBox(height:5.0),
Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
child: Row(
children: <Widget>[
Row(
children: <Widget>[
Text(
'₹',
style: TextStyle(
fontSize: 15,
color: Colors.grey[800]
),
),
Text(
widget.menuitem[1].toString(),
style: TextStyle(
fontSize: 15,
color: Colors.grey[800]
),
)
],
),
SizedBox(width:70),
Container(
child: Row(
children: <Widget>[
SizedBox(
width:30,
height:30,
child: FloatingActionButton(
onPressed: (){
setState(() {
if(GlobalVariables.allcartitems[widget.menuitem[0]][0]>0){
GlobalVariables.no_of_cart_items-=1;
GlobalVariables.allcartitems[widget.menuitem[0]][0]-=1;
GlobalVariables.totalcost-=GlobalVariables.allcartitems[widget.menuitem[0]][1];
// CHECK IF CART HAS NO ITEMS AND REMOVE BADGE HERE
}
});
},
elevation: 1,
child: Icon(Icons.remove, size: 18),
backgroundColor: Colors.red[300],
mini: true,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5.0))),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Text(
GlobalVariables.allcartitems[widget.menuitem[0]][0].toString(),
style: TextStyle(
fontSize: 18
),
),
),
SizedBox(
width:30,
height:30,
child: FloatingActionButton(
onPressed: (){
setState(() {
GlobalVariables.no_of_cart_items+=1;
GlobalVariables.allcartitems[widget.menuitem[0]][0]+=1;
GlobalVariables.totalcost+=GlobalVariables.allcartitems[widget.menuitem[0]][1];
// SET BADGE HERE
});
},
elevation: 1,
child: Icon(Icons.add, size: 20),
backgroundColor: Colors.green[300],
mini:true,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5.0))),
),
)
],
)
)
],
),
),
],
),
),
)
],
),
);
}
}
This is cart.dart:
import 'dart:convert';
import 'package:canteen_app/pages/globalvar.dart';
import 'package:canteen_app/pages/globalvar.dart' as prefix0;
import 'package:canteen_app/pages/orderReceipt.dart';
import 'package:flutter/material.dart';
import 'package:canteen_app/pages/CustomShapeClipper.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
class Cart extends StatefulWidget {
#override
_CartState createState() => _CartState();
}
class _CartState extends State<Cart> {
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
CartTopPart(),
CartBottomPart()
],
);
}
}
class CartTopPart extends StatefulWidget {
#override
_CartTopPartState createState() => _CartTopPartState();
}
Color firstColor = Color(0xFFF47D15);
Color secondColor = Color(0xFFEF772C);
class _CartTopPartState extends State<CartTopPart> {
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
ClipPath(
clipper: CustomShapeClipper(),
child: Container(
height:140.0,
width:MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [firstColor, secondColor],
)
),
child: Column(
children: <Widget>[
SizedBox(height: 53.0),
Text(
'CART',
style: TextStyle(
fontSize: 30.0,
color: Colors.white,
),
textAlign: TextAlign.center,
),
],
)
)
)
],
);
}
}
var cartmenuitems = GlobalVariables.allcartitems.keys.toList();
class CartBottomPart extends StatefulWidget {
#override
_CartBottomPartState createState() => _CartBottomPartState();
}
class _CartBottomPartState extends State<CartBottomPart> {
bool _isLoading=false;
createAlertDialog(BuildContext context, String errormessage){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(errormessage)
);
}
);
}
#override
Widget build(BuildContext context) {
if(GlobalVariables.no_of_cart_items>0) {
return _isLoading==true ? Center(child: CircularProgressIndicator()) : Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
child: Column(
children: <Widget>[
Container(
height: MediaQuery
.of(context)
.size
.height * 0.40,
child: ListView(
padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
scrollDirection: Axis.vertical,
children: cartmenuitems.map((menuitem) {
//print(cartmenuitems);
// print(GlobalVariables.allcartitems[menuitem]);
//if(GlobalVariables.allcartitems[menuitem]>=1) {
//print('heyy');
return CartOrderDish(menuitem: menuitem);
//}
}).toList()
),
),
Divider(
color: Colors.black
),
Row(
children: <Widget>[
Text(
'Total Amount:',
style: TextStyle(
fontSize: 20
),
),
SizedBox(width: 140),
Row(
children: <Widget>[
Text(
'₹',
style: TextStyle(
fontSize: 20
),
),
Text(
GlobalVariables.totalcost.toString(),
style: TextStyle(
fontSize: 20
)
)
],
)
],
),
SizedBox(height: 5),
Align(
alignment: Alignment.centerLeft,
child: Text(
'(Inclusive of GST)',
style: TextStyle(
fontSize: 15
),
),
),
SizedBox(height: 18),
RaisedButton(
onPressed: () {
if((GlobalVariables.accountbalance-GlobalVariables.totalcost)<0){
createAlertDialog(context, "Whoops! The total cost exceeds your account balance!\n\nYour account balance can be updated at the CASH COUNTER.");
}
else {
setState(() {
_isLoading = true;
});
// creating a list of all cart items to send to php
List cart = [];
cartmenuitems.map((menuitem) {
if (GlobalVariables.allcartitems[menuitem][0] > 0) {
cart.add([menuitem, GlobalVariables.allcartitems[menuitem][0], GlobalVariables.allcartitems[menuitem][1] * GlobalVariables.allcartitems[menuitem][0]]);
}
}).toList();
print(jsonEncode(cart));
Future placeOrderFunction() async {
print(GlobalVariables.username);
final response = await http.post(
"https://kjscecanteenapp.000webhostapp.com/place_order_sys.php",
body: {
"cart": json.encode(cart),
"username": GlobalVariables.username
});
// print(response.body);
var decodedResponse = json.decode(response.body);
print(decodedResponse);
setState(() {
_isLoading = false;
});
if (decodedResponse['error'] != -1) {
// means no error
int orderId=decodedResponse['error'];
int cost=GlobalVariables.totalcost;
GlobalVariables.no_of_cart_items = 0;
String date=DateFormat('dd-MMM-yyyy').format(DateTime.now());
cartmenuitems.map((menuitem) {
if (GlobalVariables.allcartitems[menuitem][0] > 0) {
GlobalVariables.allcartitems[menuitem][0] = 0;
}
});
GlobalVariables ob = new GlobalVariables();
ob.resetcart();
GlobalVariables.accountbalance -= GlobalVariables.totalcost;
GlobalVariables.totalcost = 0;
Navigator.of(context)
.push(MaterialPageRoute<Null>(
builder: (BuildContext context) {
return new OrderReceipt(orderId: orderId, cost: cost, date: date, cart: cart);
}));
}
else{
createAlertDialog(context, "There was some error during the order placement. Don't worry tho try again in a few seconds!");
}
}
placeOrderFunction();
}
},
elevation: 5.0,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0)),
padding: const EdgeInsets.all(0.0),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
Color(0xFF0083B0),
Color(0xFF00B4DB),
]
)
),
padding: const EdgeInsets.fromLTRB(40, 15, 40, 15),
child: Text(
'Place Order',
style: TextStyle(
fontSize: 20
),
),
)
)
],
),
);
}
else {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
height: MediaQuery.of(context).size.height*0.6,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Please add some items into your cart.',
style: TextStyle(
fontSize: 20,
),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
}
class CartOrderDish extends StatefulWidget {
String menuitem;
CartOrderDish({Key key, this.menuitem}): super(key: key);
#override
_CartOrderDishState createState() => _CartOrderDishState();
}
class _CartOrderDishState extends State<CartOrderDish> {
#override
Widget build(BuildContext context) {
if(GlobalVariables.allcartitems[widget.menuitem][0]>0) {
int price=GlobalVariables.allcartitems[widget.menuitem][0]*GlobalVariables.allcartitems[widget.menuitem][1];
return Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
widget.menuitem,
style: TextStyle(
fontSize: 20
),
),
),
SizedBox(width: 50),
Container(
child: Row(
children: <Widget>[
SizedBox(
width: 30,
height: 30,
child: FloatingActionButton(
heroTag: 'fab1',
elevation: 1,
child: Icon(Icons.remove, size: 18),
backgroundColor: Colors.red[300],
mini: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0))),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Text(
GlobalVariables.allcartitems[widget.menuitem][0].toString(),
style: TextStyle(
fontSize: 18
),
),
),
SizedBox(
width: 30,
height: 30,
child: FloatingActionButton(
heroTag: 'fab2',
elevation: 1,
child: Icon(Icons.add, size: 20),
backgroundColor: Colors.green[300],
mini: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0))),
),
)
],
)
),
SizedBox(width: 50),
Row(
children: <Widget>[
Text(
'₹',
style: TextStyle(
fontSize: 20
),
),
Text(
price.toString(),
style: TextStyle(
fontSize:20
)
)
],
)
],
),
);
}
else{
return Container();
}
}
}
Instead of changing the entire icon to indicate items added to cart, you could use Badge
Badge package: https://pub.dev/packages/badges
Update-1: For implementing the badges:
var p1badge = false;
var p2badge = false;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: Badge(
showBadge: p1badge,
child: Icon(Icons.filter_1),
),
title: Text('Page-1')),
BottomNavigationBarItem(
icon: Badge(
showBadge: p2badge,
child: Icon(Icons.filter_2),
),
title: Text('Page-2'))
];
}
Use a VoidCallback to update the badge:
class Page1 extends StatelessWidget {
VoidCallback onP1Badge;
Page1({this.onP1Badge});
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RaisedButton(
child: Text('P1 BADGE'),
onPressed: () {onP1Badge();},
),
],
);
}
}
Change the value of p1badge to true and call setState():
pages = [
Page1(
onP1Badge: () {
p1badge = true;
setState(() {});
},
),
Page2()
];
Update-2: Check this out: https://github.com/TheArhaam/Flutter-BottomNavigationBar-Badge
GIF: