How to access context and setstate outside build method in Flutter - flutter

How to access context and setstate outside build method in Flutter?
To make the app responsive I need context.
I get error "Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name."
When I write context here:-
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
Full code file:-
import 'package:expandable_reorderable_list/expandable_reorderable_list.dart';
import 'package:flutter/material.dart';
import 'package:o_popup/o_popup.dart';
import 'package:project_submission/responsive.dart';
import 'drag_and_drop_list.dart';
void main() {
runApp(const MyApp());
}
class CardsList {
final String header;
final List<Cards> cards;
String textField;
CardsList({
required this.header,
required this.cards,
this.textField = '',
});
}
class Cards {
final String text;
final int position;
const Cards({
required this.text,
required this.position,
});
}
List<CardsList> widgets = [
CardsList(
header: 'To-do',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header2',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header3',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header4',
textField: '',
cards: [
Cards(text: 'Hello1', position: 1),
Cards(text: 'Hello2', position: 2),
Cards(text: 'Hello3', position: 3),
],
),
];
bool addCard = false;
bool greyArea = false;
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: Wait());
}
}
class Wait extends StatefulWidget {
const Wait({Key? key}) : super(key: key);
#override
State<Wait> createState() => _WaitState();
}
class _WaitState extends State<Wait> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Portfolio(
context1: context,
)));
},
child: Text('Wait'),
);
}
}
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF2B1B81),
Color(0xFFDD499D),
],
),
),
),
Text(
'Project Management',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
Padding(
padding: EdgeInsets.only(
left: 10,
top: 30,
),
child: DragAndDropLists(
listWidth: 300,
axis: Axis.horizontal,
listPadding: EdgeInsets.only(right: 10),
itemDragOnLongPress: false,
children: lists,
onItemReorder: onItemReorder,
onListReorder: onListReorder,
),
),
// Row(
// children: [
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add(data);
// widgets.remove(data);
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// widgets
// .sort((a, b) => a['position'].compareTo(b['price']));
// });
// },
// builder: (context, _, __) => SizedBox(
// height: MediaQuery.of(context).size.height,
// child: Column(
// children: [
// Padding(
// padding: EdgeInsets.only(left: 30.0, top: 30),
// child: Container(
// width: 300,
// decoration: BoxDecoration(
// color: Color(0xFFEBECF0),
// borderRadius: BorderRadius.circular(6),
// ),
// child: Column(
// children: [
// Text(
// 'Project Resources',
// style: TextStyle(
// color: Color(0xFF5D6C83),
// fontWeight: FontWeight.w600,
// fontSize: 12),
// ),
// for (var wid in widgets)
// Column(
// children: [
// Padding(
// padding: EdgeInsets.all(8.0),
// child: Draggable(
// child: Container(
// decoration: BoxDecoration(
// color: Colors.green,
// ),
// child: Text(wid['text']),
// height: 100,
// width: 100,
// ),
// data: wid,
// feedback: Container(
// color: Colors.red,
// height: 100,
// width: 100,
// ),
// childWhenDragging: SizedBox(),
// ),
// ),
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add({
// 'text': data['text'],
// 'position': 1
// });
// widgets.remove({
// 'text': data['text'],
// 'position': data['position']
// });
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// });
// },
// builder: (context, _, __) {
// print(_);
// return SizedBox();
// },
// ),
// ],
// ),
// greyArea == true
// ? Container(
// color: Colors.grey,
// height: 20,
// width: 100,
// )
// : SizedBox(),
// SizedBox(
// height: 8,
// ),
// ],
// ),
// ),
// ),
// ],
// ),
// ),
// ),
// ],
// ),
],
),
),
);
}
void onItemReorder(
int oldItemIndex,
int oldListIndex,
int newItemIndex,
int newListIndex,
) {
setState(() {
final oldListItems = lists[oldListIndex].children;
final newListItems = lists[newListIndex].children;
final movedItem = oldListItems.removeAt(oldItemIndex);
newListItems.insert(newItemIndex, movedItem);
});
print(lists);
}
void onListReorder(
int oldListIndex,
int newListIndex,
) {
setState(() {
final movedList = lists.removeAt(oldListIndex);
lists.insert(newListIndex, movedList);
});
}
}

Related

I have a Error Closure call with mismatched arguments: function '_GameDetailsPageState.build.<anonymous closure>

I am currently creating comments in the app that the user will be able to do and after doing the function I get this error and I don't know how to fix it.
error
https://i.stack.imgur.com/rbLph.png
https://i.stack.imgur.com/Xa4vg.png
https://i.stack.imgur.com/9SPQR.png
https://i.stack.imgur.com/5Wxag.png
I searched for similar errors but those solutions did not help me
CustomTextField
class CustomTextField extends StatelessWidget {
String? hint;
final TextEditingController commentController;
final Function(String)? onSubmit;
CustomTextField(
{this.hint, required this.onSubmit, required this.commentController});
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: commentController,
onSubmitted: onSubmit,
decoration: InputDecoration(
hintText: "$hint",
hintStyle: TextStyle(fontSize: 12),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Colors.deepPurple.shade200, width: 0)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(width: 2.0))),
)
],
),
);
}
}
Comments List
import 'package:intl/intl.dart';
import '../../../../../assets/paidwork_icons.dart';
import '../../../../../common/utils/paidwork_colors.dart';
class CommentsList extends StatefulWidget {
final List<Comment> comments;
CommentsList(this.comments);
#override
State<CommentsList> createState() => _CommentsListState();
}
class _CommentsListState extends State<CommentsList> {
int likes = 0;
int dislikes = 0;
void giveLike() {
setState(() {
if (likes == 0) {
likes++;
} else {
likes--;
}
});
}
void giveDisLike() {
setState(() {
if (dislikes == 0) {
dislikes++;
} else {
dislikes--;
}
});
}
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: widget.comments.isEmpty
? Column(
children: <Widget>[
Text(
'No comments added yet!',
style: Theme.of(context).textTheme.headline6,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
),
),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
child: Row(
children: <Widget>[
Container(
width: 400,
height: 235,
decoration: BoxDecoration(
color: PaidworkColors.lightWhite,
borderRadius: BorderRadius.circular(10)),
child: Column(
children: [
SizedBox(
height: 8,
),
Padding(
padding: const EdgeInsets.only(left: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: 50,
child: Image(image: AssetImage('')),
),
SizedBox(
width: 10,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Container(
child: Row(
children: [
Text(
'Maciej',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontFamily: 'Poppins',
fontSize: 15),
),
SizedBox(
width: 10,
),
Text(
DateFormat('yyyy/MM/dd').format(
widget.comments[index].date),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
],
),
),
Container(
child: Row(
children: [
Icon(
PaidworkIcons
.paidwork_icon_chart_alt,
size: 30,
),
SizedBox(
width: 10,
),
],
),
),
Container(
width: 320,
child: Text(
widget.comments[index].description,
style: TextStyle(
color: Colors.black,
fontFamily: 'Poppins',
fontSize: 14),
),
),
Container(
width: 320,
child: Row(
children: [
Container(
child: Row(
children: [
Text(
likes.toString(),
style: TextStyle(
color: PaidworkColors
.lightUnactive),
),
GestureDetector(
onTap: () => giveLike(),
child: Icon(
PaidworkIcons
.paidwork_icon_heroicons_hand_like,
color: PaidworkColors
.lightUnactive,
),
)
],
),
),
SizedBox(
width: 20,
),
Container(
child: Row(
children: [
Text(
'${dislikes}',
style: TextStyle(
color: PaidworkColors
.lightUnactive),
),
GestureDetector(
onTap: () {
giveDisLike();
},
child: Icon(
PaidworkIcons
.paidwork_icon_heroicons_hand_dislike,
color: PaidworkColors
.lightUnactive,
),
)
],
),
),
],
)),
],
),
],
),
),
],
),
)
],
),
);
},
itemCount: widget.comments.length,
),
);
}
}
Functions
void _startAddNewTransaction(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (_) {
return AddingCommentForm(
commentController: commentController,
userCommentAvatar: 'assets/images/account_game_avatar.png',
userCommentUsername: 'Maciej',
userCommentDate: '21.12.2222',
addYourReview: () {},
cancelReview: () {},
addTx: _addNewTransaction);
},
);
}
final List<Comment> _userComments = [];
void _addNewTransaction(String txDescription, String txDifficulty) {
final newTx = Comment(
description: txDescription,
difficulty: txDifficulty,
date: DateTime.now(),
id: DateTime.now().toString(),
);
setState(() {
_userComments.add(newTx);
});
}
bool openAddReviewForm = false;
void addReview() {
setState(() {
openAddReviewForm = !openAddReviewForm;
});
}
final TextEditingController commentController = TextEditingController();
void submitData() {
final enteredDescription = commentController.text;
if (enteredDescription.isEmpty) {
return;
}
widget.addTx(
enteredDescription,
);
Navigator.of(context).pop();
}

How do i correctly initialise a variable from a stateful widget to another widget in flutter and maintain state?

I have two widgets
JobsHeaderWidget
JobsView
JobsHeaderWidget is a stateful widget where i code all the logic and initialise int current = 0; in the state. In this same file, i have another class named CategoriesBuilder where i use switch cases to make sure at each switch case a different container is returned. ( a switch case for each tab )
This switch cases is now responsible for switching containers depending on the tab bar selected as seen in this image:
I will also drop the code snippet of the JobsHeaderWidget for better clarifications.
The problem is - when i use this CategoriesBuilder in same widget as the 'JobsHeaderWidget' it works.
But i don't want to use it in same widget cos of the logic of my design. I want to be able to use this builder in JobsView widget which is another dart file and it doesn't work maybe because of wrong approach.
I tried converting the JobsView to a stateful widget and initialising 'int current = 0;' but it doesn't work.
I also tried making int current = 0; global var, it worked but the state doesn't change when i select individual tab bars. ( I mean my switch cases don't seem to work ).
I have gone round stackoverflow for answers before asking this but can't find a solution.
Snippets of each widgets below.
JobsHeaderWidget
class JobsHeaderWidget extends StatefulWidget {
const JobsHeaderWidget({
Key key,
}) : super(key: key);
#override
State<JobsHeaderWidget> createState() => _JobsHeaderWidgetState();
}
class _JobsHeaderWidgetState extends State<JobsHeaderWidget> {
List<String> items = [
"All",
"Critical",
"Open",
"Closed",
"Overdue",
];
ValueChanged<int> onChange;
int current = 0;
List<DropdownMenuItem<String>> get dropdownItems {
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(
child: Text(
"Today",
),
value: "Today"),
];
return menuItems;
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Jobs',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w600),
),
Row(
children: [
Text(
'View Insights ',
style: GoogleFonts.poppins(
color: Color(0xff3498DB),
fontSize: 12,
fontWeight: FontWeight.w500),
),
Icon(
Icons.arrow_forward_ios,
color: Color(0xff3498DB),
size: 12,
),
],
),
SizedBox(
height: 10,
),
filterJobs(),
],
),
),
);
}
Widget filterJobs() {
String selectedValue = "Today";
return Column(
children: [
Container(
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 100),
width: double.infinity,
child: IntrinsicWidth(
child: FittedBox(
fit: BoxFit.fitWidth,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
for (int i = 0; i < items.length; i++) ...[
GestureDetector(
onTap: () {
setState(() {
current = i;
});
},
child: AnimatedContainer(
height: 40,
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.only(
left: 14.0, right: 14.0, top: 4, bottom: 4),
decoration: BoxDecoration(
color: current == i
? const Color(0xff34495E)
: const Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(50),
),
child: Center(
child: Text(
items[i],
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500,
color:
current == i ? Colors.white : Colors.grey),
),
),
),
),
]
],
),
),
),
),
Divider(
color: Color(0xff34495E).withOpacity(0.2),
),
Row(
children: [
Text(
'All Jobs',
style:
GoogleFonts.poppins(fontSize: 9, fontWeight: FontWeight.w400),
),
SizedBox(
width: 5,
),
Text(
' * This Week',
style:
GoogleFonts.poppins(fontSize: 9, fontWeight: FontWeight.w400),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'25',
style: GoogleFonts.poppins(
fontSize: 20, fontWeight: FontWeight.w600),
),
Container(
height: 30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(2),
color: Color(0xffF4F4F4)),
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
),
child: Row(
children: [
Container(
decoration: BoxDecoration(
color: Color(0xff34495E),
borderRadius: BorderRadius.circular(2)),
child: Icon(
Icons.tune,
size: 15,
color: Colors.white,
),
),
SizedBox(
width: 5,
),
DropdownMenuItem(
child: DropdownButtonHideUnderline(
child: Container(
child: DropdownButton(
isDense: true,
style: GoogleFonts.poppins(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xff34495E),
),
onChanged: (value) {},
items: dropdownItems,
value: selectedValue,
),
),
),
),
],
),
),
),
],
),
//If i uncomment this line and use the category builder here, it works fine! CategoriesBuilder(current: current)
],
);
}
}
class CategoriesBuilder extends StatelessWidget {
const CategoriesBuilder({
Key key,
#required this.current,
}) : super(key: key);
final int current;
#override
Widget build(BuildContext context) {
return Builder(
builder: (context) {
switch (current) {
case 0:
return AllJobsListView();
case 1:
return CriticalJobsListView();
case 2:
return OpenJobsListView();
case 3:
return ClosedJobsListView();
case 4:
return OverdueJobsListView();
default:
return SizedBox.shrink();
}
},
);
}
}
JobsView
class JobsView extends StatefulWidget {
const JobsView({
Key key,
}) : super(key: key);
#override
State<JobsView> createState() => _JobsViewState();
}
class _JobsViewState extends State<JobsView> {
int current = 0;
#override
Widget build(BuildContext context) {
final controller = Get.put(EServicesController());
return Scaffold(
// floatingActionButton: new FloatingActionButton(
// child: new Icon(Icons.add, size: 32, color: Get.theme.primaryColor),
// onPressed: () => {Get.offAndToNamed(Routes.E_SERVICE_FORM)},
// backgroundColor: Get.theme.colorScheme.secondary,
// ),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
body: RefreshIndicator(
onRefresh: () async {
Get.find<LaravelApiClient>().forceRefresh();
controller.refreshEServices(showMessage: true);
Get.find<LaravelApiClient>().unForceRefresh();
},
child: CustomScrollView(
controller: controller.scrollController,
physics: AlwaysScrollableScrollPhysics(),
shrinkWrap: false,
slivers: <Widget>[
SliverAppBar(
backgroundColor: Color(0xffFFFFFF),
expandedHeight: MediaQuery.of(context).size.height * 0.4,
elevation: 0.5,
primary: true,
pinned: false,
floating: false,
//iconTheme: IconThemeData(color: Get.theme.primaryColor),
// title: Text(
// "Jobs".tr,
// style: Get.textTheme.headline6
// .merge(TextStyle(color: Get.theme.primaryColor)),
// ),
centerTitle: false,
automaticallyImplyLeading: false,
// leading: new IconButton(
// icon: new Icon(Icons.arrow_back_ios,
// color: Get.theme.primaryColor),
// onPressed: () => {Get.back()},
// ),
actions: [
SearchButtonWidget(),
],
//bottom: HomeSearchBarWidget(),
flexibleSpace: FlexibleSpaceBar(
collapseMode: CollapseMode.parallax,
title: JobsHeaderWidget(),
)),
SliverToBoxAdapter(
child: Wrap(
children: [
//ServicesListWidget(),
// The state doesnt change here for some reasosns CategoriesBuilder(current: current)
],
),
),
],
),
),
);
}
}
Try this: keep your 'int current' within _JobsViewState as you have in your code.
When you call your JobsHeaderWidget , pass the function it will use to update the the value of the current variable; and rebuild the state from here.
Something like this:
class JobsHeaderWidget extends StatefulWidget {
final Function changeCurrentValue(int newValue);
const JobsHeaderWidget({
this.changeCurrentValue,
Key key,
}) : super(key: key);
#override
State<JobsHeaderWidget> createState() => _JobsHeaderWidgetState();
}
class _JobsHeaderWidgetState extends State<JobsHeaderWidget> {
#override
Widget build(BuildContext context) {
// Somewhere inside build, instead calling setState()
// call the function you passed to the widget
GestureDetector(
onTap: () {
changeCurrentValue(i);
},
)
}
}
class _JobsViewState extends State<JobsView> {
int current = 0;
void changeCurrentValue(int newValue) {
setState(() {
current = newValue;
});
}
#override
Widget build(BuildContext context) {
//somewhere inside build
flexibleSpace: FlexibleSpaceBar(
collapseMode: CollapseMode.parallax,
title: JobsHeaderWidget(changeCurrentValue: changeCurrentValue),
)),
}
}
After hours and even sleeping overnight on this question i came up with a work-around that works. (minor refactoring)
This was my approach :
Convert my JobsView widget to a stateful widget and put all my controllers in place.
Copied all my variables from JobHeaderWidget and put it in the state of my JobsView widget.
Instead of returning a widget in the title of my sliver app as thus :
flexibleSpace: FlexibleSpaceBar( collapseMode: CollapseMode.parallax, title: JobsHeaderWidget(), )),
I copied all of my code from the widget tree from JobsHeaderWidget and put converted to a method and replaced it in my title.
My builder CategoryBuilder was put in a separate then imported as i used it in my SliverAppAdapter .
Of cos i got rid of the unnecessary dart file JobsHeaderWidget.
FULL CODE BELOW
class JobsView extends StatefulWidget {
#override
State<JobsView> createState() => _JobsViewState();
}
class _JobsViewState extends State<JobsView> {
List<String> items = [
"All",
"Critical",
"Open",
"Closed",
"Overdue",
];
int current = 0;
List<DropdownMenuItem<String>> get dropdownItems {
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(
child: Text(
"Today",
),
value: "Today"),
];
return menuItems;
}
#override
Widget build(BuildContext context) {
final controller = Get.put(EServicesController());
return Scaffold(
// floatingActionButton: new FloatingActionButton(
// child: new Icon(Icons.add, size: 32, color: Get.theme.primaryColor),
// onPressed: () => {Get.offAndToNamed(Routes.E_SERVICE_FORM)},
// backgroundColor: Get.theme.colorScheme.secondary,
// ),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
body: RefreshIndicator(
onRefresh: () async {
Get.find<LaravelApiClient>().forceRefresh();
controller.refreshEServices(showMessage: true);
Get.find<LaravelApiClient>().unForceRefresh();
},
child: CustomScrollView(
controller: controller.scrollController,
physics: AlwaysScrollableScrollPhysics(),
shrinkWrap: false,
slivers: <Widget>[
SliverAppBar(
backgroundColor: Color(0xffFFFFFF),
expandedHeight: MediaQuery.of(context).size.height * 0.4,
elevation: 0.5,
primary: true,
pinned: false,
floating: false,
//iconTheme: IconThemeData(color: Get.theme.primaryColor),
// title: Text(
// "Jobs".tr,
// style: Get.textTheme.headline6
// .merge(TextStyle(color: Get.theme.primaryColor)),
// ),
centerTitle: false,
automaticallyImplyLeading: false,
// leading: new IconButton(
// icon: new Icon(Icons.arrow_back_ios,
// color: Get.theme.primaryColor),
// onPressed: () => {Get.back()},
// ),
actions: [
SearchButtonWidget(),
],
//bottom: HomeSearchBarWidget(),
flexibleSpace: FlexibleSpaceBar(
collapseMode: CollapseMode.parallax,
title: mainHeader(),
)),
SliverToBoxAdapter(
child: Wrap(
children: [
//ServicesListWidget(),
CategoriesBuilder(current: current)
],
),
),
],
),
),
);
}
Padding mainHeader() {
return Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Jobs',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w600),
),
Row(
children: [
Text(
'View Insights ',
style: GoogleFonts.poppins(
color: Color(0xff3498DB),
fontSize: 12,
fontWeight: FontWeight.w500),
),
Icon(
Icons.arrow_forward_ios,
color: Color(0xff3498DB),
size: 12,
),
],
),
SizedBox(
height: 10,
),
() {
String selectedValue = "Today";
return Column(
children: [
Container(
constraints:
const BoxConstraints(maxWidth: 600, maxHeight: 100),
width: double.infinity,
child: IntrinsicWidth(
child: FittedBox(
fit: BoxFit.fitWidth,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
for (int i = 0; i < items.length; i++) ...[
GestureDetector(
onTap: () {
setState(() {
current = i;
});
},
child: AnimatedContainer(
height: 40,
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.only(
left: 14.0,
right: 14.0,
top: 4,
bottom: 4),
decoration: BoxDecoration(
color: current == i
? const Color(0xff34495E)
: const Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(50),
),
child: Center(
child: Text(
items[i],
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500,
color: current == i
? Colors.white
: Colors.grey),
),
),
),
),
]
],
),
),
),
),
Divider(
color: Color(0xff34495E).withOpacity(0.2),
),
Row(
children: [
Text(
'All Jobs',
style: GoogleFonts.poppins(
fontSize: 9, fontWeight: FontWeight.w400),
),
SizedBox(
width: 5,
),
Text(
' * This Week',
style: GoogleFonts.poppins(
fontSize: 9, fontWeight: FontWeight.w400),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'25',
style: GoogleFonts.poppins(
fontSize: 20, fontWeight: FontWeight.w600),
),
Container(
height: 30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(2),
color: Color(0xffF4F4F4)),
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
),
child: Row(
children: [
Container(
decoration: BoxDecoration(
color: Color(0xff34495E),
borderRadius: BorderRadius.circular(2)),
child: Icon(
Icons.tune,
size: 15,
color: Colors.white,
),
),
SizedBox(
width: 5,
),
DropdownMenuItem(
child: DropdownButtonHideUnderline(
child: Container(
child: DropdownButton(
isDense: true,
style: GoogleFonts.poppins(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xff34495E),
),
onChanged: (value) {},
items: dropdownItems,
value: selectedValue,
),
),
),
),
],
),
),
),
],
),
//CategoriesBuilder(current: current)
],
);
}(),
],
),
),
);
}
}

only when use iphone simulator

I have this error:
The following FileSystemException was thrown resolving an image codec:
Cannot open file, path = '/Users/todo/Library/Developer/CoreSimulator/Devices/82205CEC-3D83-4A29-BF17-01C5B0515F71/data/Containers/Data/Application/035B9913-BEC5-46BA-84A5-8C1FE3C4E671/tmp/image_picker_B8D488A3-2790-4D53-A5D8-52E57E2C4108-76094-000003172DF085D2.jpg' (OS Error: No such file or directory, errno = 2)
When the exception was thrown, this was the stack
only when use iphone simulator while android emulator no problem
import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../app/utility.dart';
import '../db/aql_db.dart';
import '../globals.dart';
import '../menu_page.dart';
import '../model/aql_model.dart';
import '../widget/input_text.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
var _current = resultsFld[0];
class AqlPg extends StatefulWidget {
const AqlPg({Key? key}) : super(key: key);
#override
State<AqlPg> createState() => _AqlPgState();
}
class _AqlPgState extends State<AqlPg> {
final List<TextEditingController> _criticalController = [];
final List<TextEditingController> _majorController = [];
final List<TextEditingController> _minorController = [];
final List<TextEditingController> _imgCommintControllers = [];
final _irController = TextEditingController();
bool clickedCentreFAB =
false; //boolean used to handle container animation which expands from the FAB
int selectedIndex =
0; //to handle which item is currently selected in the bottom app bar
//call this method on click of each bottom app bar item to update the screen
void updateTabSelection(int index, String buttonText) {
setState(() {
selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
//
_irController.text = aqltbl.ir ?? '';
String _current = aqltbl.result ?? resultsFld[0];
//
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
//---- stack for FloatingActionButton
Stack(
children: <Widget>[
//this is the code for the widget container that comes from behind the floating action button (FAB)
Align(
alignment: FractionalOffset.bottomCenter,
child: AnimatedContainer(
child: const Text(
'Hello',
style: TextStyle(fontSize: 18, color: whiteColor),
),
duration: const Duration(milliseconds: 250),
//if clickedCentreFAB == true, the first parameter is used. If it's false, the second.
height: clickedCentreFAB
? MediaQuery.of(context).size.height
: 10.0,
width: clickedCentreFAB
? MediaQuery.of(context).size.height
: 10.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
clickedCentreFAB ? 0.0 : 300.0),
color: Colors.blue),
),
),
],
),
// --- Top Page Title
const SizedBox(
height: 50,
),
const Center(
child: Text(
'Aql page',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: medBlueColor),
),
),
Text(
'Shipment no:$shipmentId',
style: const TextStyle(color: medBlueColor),
),
//--- input container
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Container(
height: 270,
width: 300,
margin: const EdgeInsets.only(top: 5),
child: ListView.builder(
itemCount: (aqltbl.aql ?? []).length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
//here
var _aqlList = aqltbl.aql![index];
//
if (aqltbl.aql!.length > _criticalController.length) {
_criticalController.add(TextEditingController());
_majorController.add(TextEditingController());
_minorController.add(TextEditingController());
}
//
_criticalController[index].text =
_aqlList.critical ?? '';
_majorController[index].text = _aqlList.major ?? '';
_minorController[index].text = _aqlList.minor ?? '';
//
return Column(
children: [
Container(
height: 260,
width: 200,
margin: const EdgeInsets.only(left: 10),
padding: const EdgeInsets.all(10),
// ignore: prefer_const_constructors
decoration: BoxDecoration(
color: lightBlue,
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: [
Text(
(_aqlList.name ?? '').toString(),
style: const TextStyle(
color: medBlueColor,
fontSize: 13,
),
),
// ignore: prefer_const_constructors
MyInputField(
title: 'critical',
hint: 'write critical ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _criticalController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].critical = value;
_save();
});
},
),
MyInputField(
title: 'majority',
hint: 'write majority ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _majorController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].major = value;
_save();
});
},
),
MyInputField(
title: 'minority',
hint: 'write minority ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _minorController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].minor = value;
_save();
});
},
),
],
),
),
],
);
}),
),
Container(
height: 270,
width: 300,
margin: const EdgeInsets.only(right: 10, left: 20),
padding: const EdgeInsets.only(
left: 10, bottom: 3, right: 10, top: 5),
decoration: const BoxDecoration(
color: lightBlue,
),
child: Column(
children: [
const Text(
'Summery results',
style: TextStyle(color: medBlueColor),
),
Container(
margin: const EdgeInsets.only(top: 10, bottom: 5),
alignment: Alignment.centerLeft,
child: const Text(
'Results',
style: TextStyle(color: medBlueColor),
),
),
Container(
padding: const EdgeInsets.only(right: 5, left: 5),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: borderColor,
)),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
focusColor: whiteColor,
value: aqltbl.result,
hint: const Text('select result'),
isExpanded: true,
iconSize: 36,
icon: const Icon(Icons.arrow_drop_down),
items: resultsFld.map((res) {
return DropdownMenuItem<String>(
value: res,
child: Text(
res,
style: const TextStyle(
fontFamily: 'tajawal',
fontSize: 15,
color: medBlueColor),
),
);
}).toList(),
onChanged: (val) {
setState(() {
aqltbl.result = val;
});
_save();
},
),
),
),
// aqltbl.result = selRes;
MyInputField(
width: 300,
title: 'information remarks (ir)',
hint: '',
maxLines: 3,
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _irController,
onSubmit: (value) {
aqltbl.ir = value;
_save();
},
),
],
),
),
],
),
),
//Images Container
Container(
height: 400,
padding: const EdgeInsets.all(0),
margin: const EdgeInsets.only(bottom: 10, left: 10),
decoration: const BoxDecoration(color: lightGrey),
child: (aqltbl.images ?? []).isEmpty
? Column(
children: [
Image.asset(
'images/empty-photo.jpg',
height: 300,
),
Container(
margin: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text('Click'),
Text(
'Camera button',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(' to add new photo'),
],
)),
],
)
: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: (aqltbl.images ?? []).length,
itemBuilder: (context, imgIndex) {
String? _image =
(aqltbl.images ?? [])[imgIndex].name.toString();
inspect('aql image file');
File(_image).exists() == true
? inspect('image exist')
: inspect('not exist: ' + _image);
inspect('_image: ' + _image);
if (aqltbl.images!.length >
_imgCommintControllers.length) {
_imgCommintControllers.add(TextEditingController());
}
_imgCommintControllers[imgIndex].text =
aqltbl.images![imgIndex].imgComment!;
inspect(_imgCommintControllers.length);
return Container(
margin: const EdgeInsets.only(left: 5),
height: 300,
child: Column(
children: [
Stack(
children: [
Image.file(
File(_image),
height: 300,
),
Container(
decoration: const BoxDecoration(
color: medBlueColor,
),
child: IconButton(
onPressed: () {
inspect('clear');
String imgName =
aqltbl.images![imgIndex].name ??
'';
aqltbl.images!.removeAt(imgIndex);
// aqltbl.images!.removeWhere(
// (item) => item.name == imgName);
_imgCommintControllers
.removeAt(imgIndex);
setState(() {});
},
color: whiteColor,
icon: const Icon(Icons.clear)),
)
],
),
MyInputField(
title: 'Write remarks about image',
hint: '',
controller: _imgCommintControllers[imgIndex],
onSubmit: (value) {
aqltbl.images![imgIndex].imgComment = value;
aqltbl.images![imgIndex].name = _image;
_save();
},
),
],
));
}),
),
],
),
),
// --- FloatingActionButton
floatingActionButtonLocation: FloatingActionButtonLocation
.centerDocked, //specify the location of the FAB
floatingActionButton: FloatingActionButton(
backgroundColor: medBlueColor,
onPressed: () {
inspect(aqltbl);
setState(() {
clickedCentreFAB =
!clickedCentreFAB; //to update the animated container
});
},
tooltip: "Centre FAB",
child: Container(
margin: const EdgeInsets.all(15.0),
child: const Icon(Icons.send),
),
elevation: 4.0,
),
// --- bottom action bar
bottomNavigationBar: BottomAppBar(
child: Container(
margin: const EdgeInsets.only(left: 12.0, right: 12.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
//to leave space in between the bottom app bar items and below the FAB
IconButton(
//update the bottom app bar view each time an item is clicked
onPressed: () {
// updateTabSelection(0, "Home");
Get.to(const MainMenu());
},
iconSize: 27.0,
icon: Image.asset(
'images/logo.png',
color: medBlueColor,
),
),
const SizedBox(
width: 50.0,
),
IconButton(
onPressed: () async {
// updateTabSelection(2, "Incoming");
await _takeImage('gallery');
},
iconSize: 27.0,
icon: const Icon(
Icons.image_outlined,
color: medBlueColor,
),
),
IconButton(
onPressed: () async {
// updateTabSelection(1, "Outgoing");
await _takeImage('camera');
},
iconSize: 27.0,
icon: const Icon(
Icons.camera_alt,
color: medBlueColor,
),
),
],
),
),
//to add a space between the FAB and BottomAppBar
shape: const CircularNotchedRectangle(),
//color of the BottomAppBar
color: Colors.white,
),
);
}
_save() {
inspect('submit');
saveAql(shipmentId, aqltbl);
box.write('aql'+shipmentId.toString(), aqltbl);
}
_takeImage(method) async {
String _imgPath = await imageFromDevice(method);
if (_imgPath != empty) {
ImagesModel imgMdl = ImagesModel();
imgMdl.name = _imgPath;
imgMdl.imgComment = '';
if (aqltbl.images != null) {
// _saveLocaly(close: 0);
setState(() {
aqltbl.images!.add(imgMdl);
_save();
});
}
}
}
Future _sendAqlToServer() async {
try {
var response = await http.post(urlSendProductPhoto, body: {
'aql': json.encode(aqltbl).toString(),
'id': shipmentId.toString(),
});
if (response.statusCode == 200) {
Get.snackbar('Success', 'Image successfully uploaded');
return response.body;
} else {
Get.snackbar('Fail', 'Image not uploaded');
inspect('Request failed with status: ${response.statusCode}.');
return 'empty';
}
} catch (socketException) {
Get.snackbar('warning', 'Image not uploaded');
return 'empty';
}
}
}
Try following the path that it is saying it cannot find in your computer, I had a similar issue, I tried opening an Iphone 12 instead of an Iphone 13 and it worked out the issue, my problem was I inadvertently deleted a few files I shouldn't have.

flutter Problem same quantity show on products

when I am increasing my quantity of one product then all product's quantity is increasing, so how to solve it.
This is my product page:
import 'dart:convert';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hospital/Authentication/LoginLogoutScreenPage/login.dart';
import 'package:hospital/CartPage/Cart_Api/cart_api.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/ProductDetailsPage/product_detailPage.dart';
import 'package:hospital/ProductDetailsPage/related_product_page.dart';
import 'package:hospital/SecondSection/Medicine/medicine_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;
import 'package:line_icons/line_icons.dart';
import 'package:provider/provider.dart';
class DetailPage extends StatefulWidget {
final plistId;
const DetailPage({Key key, this.plistId}) : super(key: key);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
final GlobalKey<FormState> _formKey = GlobalKey();
int quantity = 1;
var response;
var detailPageApi;
#override
void initState() {
super.initState();
fetchData(widget.plistId);
}
fetchData(var consultWithDoctor) async {
var api = Uri.parse(
'$ecommerceBaseUrl/productListApi.php?a2rTokenKey=$a2rTokenKey&plistId=${widget.plistId}');
response = await http.get(
api,
);
print("detailPageApi " + api.toString());
print("detailPageBody " + response.body);
detailPageApi = jsonDecode(response.body);
print("detailPagelist " + detailPageApi.toString());
setState(() {});
}
Future _submit() async {
var errorMessage = 'Authentication Failed';
if (successfully_add_cart_status.toString() == 'false') {
errorMessage = 'Please try again later';
print(errorMessage);
_showerrorDialog(errorMessage);
} else {
errorMessage = 'Product Succesfully Added to Cart';
print(errorMessage);
_showerrorDialog(errorMessage);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: kGreen,
title: Text(
"Details",
style: TextStyle(fontStyle: FontStyle.italic),
),
actions: [
IconButton(
icon: Icon(Icons.shopping_cart),
// onPressed: () => print("open cart"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Cartpage()),
);
},
),
DropDownMenu(),
],
),
body: Container(
child: response != null
? ListView.builder(
itemCount: detailPageApi.length.clamp(0, 1),
scrollDirection: Axis.vertical,
physics: ScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
var details = detailPageApi[index];
if (details['num'] == 0) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.white,
),
);
}
return Column(
children: <Widget>[
Hero(
tag: "1",
child: SizedBox(
height: 300.0,
width: 300.0,
child: Carousel(
boxFit: BoxFit.cover,
autoplay: false,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 800),
dotSize: 6.0,
dotIncreasedColor: Colors.black,
dotBgColor: Colors.transparent,
// dotPosition: DotPosition.topRight,
dotVerticalPadding: 10.0,
showIndicator: true,
indicatorBgPadding: 7.0,
images: [
NetworkImage(details['pImgImg']),
],
),
),
),
SizedBox(
height: 50,
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Name :",
style: TextStyle(
fontSize: 18,
height: 1.5,
fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Flexible(
child: Text(
// widget.details,
details['productName'],
style: TextStyle(
fontSize: 17,
height: 1.5,
fontWeight: FontWeight.w500),
),
),
],
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Details :",
style: TextStyle(
fontSize: 18,
height: 1.5,
fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Flexible(
child: Text(
// widget.details,
details['productDescription'],
style: TextStyle(
fontSize: 17,
height: 1.5,
fontWeight: FontWeight.w500),
),
),
],
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Row(
children: <Widget>[
Text(
"Price :",
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Row(
children: <Widget>[
Text(
// "Rs " + widget.pPromotionPrice,
"Rs 55.0",
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Text(
// "Rs " + widget.pPrice,
"Rs 100",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
// color: warning,
decoration: TextDecoration.lineThrough),
)
],
)
],
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.only(right: 20, left: 20),
child: Row(
children: <Widget>[
Text(
"Qty :",
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Row(
children: <Widget>[
InkWell(
onTap: () {
if (quantity > 1) {
setState(() {
quantity = --quantity;
});
}
// minus here
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(
// border: Border.all(color: primary),
shape: BoxShape.circle),
child: Icon(
LineIcons.minus,
size: 15,
),
),
),
SizedBox(
width: 15,
),
Text(
quantity.toString(),
style: TextStyle(fontSize: 16),
),
SizedBox(
width: 15,
),
InkWell(
onTap: () {
setState(() {
quantity = ++quantity;
});
// minus here
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(
// border: Border.all(color: primary),
shape: BoxShape.circle),
child: Icon(
LineIcons.plus,
size: 15,
),
),
),
],
)
],
),
),
SizedBox(
height: 50,
),
InkWell(
onTap: () async {
if (var_uid.toString() != null.toString()) {
_submit();
var qty = quantity.toString();
var plistId = widget.plistId;
print('pplistid' + plistId);
var uid = var_uid.toString();
var sid = var_sid.toString();
print('uuid' + uid);
print('ssid' + sid);
var response =
await add_to_cart_fn(qty, plistId, uid, sid);
print("rsp: " + response['msg']);
} else {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LoginPage()));
}
},
// },
child: Padding(
padding: EdgeInsets.only(left: 20, right: 20),
child: Container(
height: 45,
width: double.infinity,
decoration: BoxDecoration(
color: kGreen,
borderRadius: BorderRadius.circular(30)),
child: Center(
child: Text(
"ADD TO CART",
style: TextStyle(
color: kWhite,
fontSize: 20,
),
),
),
),
),
),
SizedBox(height: 20.0),
RelatedProductPage(plistId: widget.plistId)
],
);
})
: Center(
child: CircularProgressIndicator(
backgroundColor: Colors.white,
),
),
),
);
}
void _showerrorDialog(String message) {
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.grey[350],
textColor: Colors.black,
fontSize: 16.0);
}
}
You are using the same quantity variable against each item. Changing the value on one of those will cause all items to update. What you need to do is to keep a Map of quantity selected against product id. That way whenever you increase or decrease the quantity, you update the quantity against that specific product id and the rest will remain unchanged.
EDIT: Here is how this will work
//Create a new map to save the product id and product selected quantity
var productQuantity = new Map<int, int>()
//When setting the values of the product, set the quantity from the map
Padding(
padding: const EdgeInsets.only(right: 20, left: 20),
child: Row(
children: <Widget>[
Text(
"Qty :",
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.w500),
),
SizedBox(width: 20,),
Row(
children: <Widget>[
InkWell(
onTap: () {
if (quantity > 1) {
setState(() {
//Changed here
productQuantity['$productId'] -= 1;
});
}
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(shape: BoxShape.circle),
child: Icon(
LineIcons.minus,
size: 15,
),
),
),
SizedBox(width: 15,),
Text(
//Changed here
productQuantity['$productId'].toString(),
style: TextStyle(fontSize: 16),
),
SizedBox(width: 15,),
InkWell(
onTap: () {
setState(() {
//Changed here
productQuantity['$productId'] += 1;
});
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(
shape: BoxShape.circle),
),
child: Icon(
LineIcons.plus,
size: 15,
),
),
),
],
)
],
),
)
you set the common quantity in all products so change it and set it inside the class.
Please Check the example
import 'package:flutter/material.dart';
class QuantityUpdatePage extends StatefulWidget {
#override
_QuantityUpdatePageState createState() => _QuantityUpdatePageState();
}
class _QuantityUpdatePageState extends State<QuantityUpdatePage> {
List<Product> productArray = [];
#override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
productArray.clear();
productArray.add(Product(1, "Product 1", 1));
productArray.add(Product(2, "Product 2", 1));
productArray.add(Product(3, "Product 3", 1));
productArray.add(Product(4, "Product 4", 1));
productArray.add(Product(5, "Product 5", 1));
setState(() {});
});
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("QUANTITY UPDATE")),
body: ListView.builder(
shrinkWrap: true,
itemCount: productArray.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(right: 20, left: 20),
child: ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
SizedBox(
height: 20,
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(productArray[index].productName),
SizedBox(
width: 40,
),
Row(
children: <Widget>[
Text(
"Qty :",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
),
SizedBox(
width: 20,
),
Row(
children: <Widget>[
InkWell(
onTap: () {
if (productArray[index].quantity > 1) {
setState(() {
productArray[index].quantity = --productArray[index].quantity;
});
}
// minus here
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(
// border: Border.all(color: primary),
shape: BoxShape.circle),
child: Icon(
Icons.minimize,
size: 15,
),
),
),
SizedBox(
width: 15,
),
Text(
productArray[index].quantity.toString(),
style: TextStyle(fontSize: 16),
),
SizedBox(
width: 15,
),
InkWell(
onTap: () {
setState(() {
productArray[index].quantity = ++productArray[index].quantity;
});
// minus here
},
child: Container(
width: 25,
height: 25,
decoration: BoxDecoration(
// border: Border.all(color: primary),
shape: BoxShape.circle),
child: Icon(
Icons.add,
size: 15,
),
),
),
],
)
],
),
],
),
SizedBox(
height: 20,
),
],
),
);
}));
}
}
class Product {
String productName;
int quantity;
int id;
Product(this.id, this.productName, this.quantity);
}
#Deepak if you don't understand Maps use list instead, with a value being updated for each index. Initialize a list of int types with some large values like 1000000, and update the value for each index. use ListView builder to fetch the data from the API for each index.
List<int> quantity = List.empty(growable: true);
OR
List<int> quantity = List.filled(10000, []);
For updating quantity:-
quantity[index] += 1;
For Grid view thing, refer this example from CodeGrepper:-
GridView.count(
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the List.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headline5,
),
);
}),
);

Having difficulty adding items to shopping cart - Flutter

I have my Cart model as below
class Cart {
String description;
double unitCost;
double amount;
int quantity;
String color;
String imageURl;
Cart({
this.description,
this.unitCost,
this.amount,
this.color,
this.quantity,
this.imageURl,
});
}
And my CartData notifier class which has a _cartList with pre-loaded data as shown below:
class CartData extends ChangeNotifier {
List<Cart> _cartItems = [
Cart(
imageURl:
'https://s2.r29static.com/bin/entry/ebd/0,675,2000,1050/x,80/1929471/image.jpg',
description: 'Nike Air Max',
quantity: 3,
unitCost: 6000,
),
Cart(
color: 'red',
description: 'Nike Air Max',
quantity: 3,
unitCost: 3000,
),
Cart(
imageURl:
'https://s2.r29static.com/bin/entry/ebd/0,675,2000,1050/x,80/1929471/image.jpg',
description: 'Nike Air Max',
quantity: 6,
unitCost: 6000,
),
Cart(
color: 'purple',
description: 'Nike Air Max',
quantity: 2,
unitCost: 1000,
),
Cart(
color: 'purple',
description: 'Nike Air Max',
quantity: 2,
unitCost: 2000,
),
];
UnmodifiableListView<Cart> get cartItems {
return UnmodifiableListView(_cartItems);
}
int get cartItemsCount {
return _cartItems.length;
}
void addItemToCart(
String color,
double unitCost,
String description,
String imageURL,
int quantity,
) {
_cartItems.insert(
0,
Cart(
color: color,
unitCost: unitCost,
description: description,
imageURl: imageURL,
quantity: quantity,
),
);
notifyListeners();
}
void getTotalSum(Cart cart) {}
double getAmount(int qty, double unitCost) {
return qty * unitCost;
}
void upDateCartItem(Cart cartItem, bool isIncrementing) {
if (isIncrementing == true) {
cartItem.quantity++;
print(
'Cart item purchase quantity is: ${cartItem.quantity}, after incrementing from updateCartItem');
} else {
if (cartItem.quantity >= 1) {
cartItem.quantity--;
print(
'Cart item purchase quantity is: ${cartItem.quantity} after decrementing from updateCartItem');
}
if (cartItem.quantity == 0) {
deleteItemFromCart(cartItem);
}
print(cartItem.quantity);
}
cartItem.amount = cartItem.quantity * cartItem.unitCost;
print('Cart Item amount is: ${cartItem.amount} from updateCartItem');
notifyListeners();
}
void deleteItemFromCart(Cart cartItem) {
_cartItems.remove(cartItem);
notifyListeners();
}
}
I want to be able to add items on the fly to my existing list of Cart Items using my addItemToCart() method, and display them immediately on my shopping cart page.
In my shopping screen, I have a few declarations as below:
String defaultDescription = 'add description';
String paymentDescription = 'add description';
String amount = '0';
int cartTotal = 0;
However, I'm unable to add item(s) to cart from my shopping screen when I call the addItemToCart method as below:
_addToCart() {
if (amount == '' || amount == '0') {
print('add an amount');
_showToast(this.context, 'amount');
} else if (paymentDescription == defaultDescription) {
print('please enter a valid description to proceed');
_showToast(this.context, 'payment description');
} else {
print(amount);
print(paymentDescription);
//do something like add to cart
CartData cartData = Provider.of<CartData>(context, listen: false);
cartData.addItemToCart(
null,
double.parse(output),
paymentDescription,
null,
1,
);
}
setState(() {
paymentDescription = defaultDescription;
amount = '0';
});
}
Here's my checkout screen that displays the cart Items:
class CheckoutScreen extends StatefulWidget {
static const String id = 'checkout_screen';
#override
_CheckoutScreenState createState() => _CheckoutScreenState();
}
class _CheckoutScreenState extends State<CheckoutScreen> {
#override
void initState() {
super.initState();
CustomerNotifier customerNotifier =
Provider.of<CustomerNotifier>(context, listen: false);
customerNotifier.getCustomers(customerNotifier);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ChangeNotifierProvider(
create: (context) => CartData(),
child: Consumer<CartData>(
builder: (context, cartData, child) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
IconButton(
icon: Icon(
Icons.arrow_back_ios,
color: Colors.black26,
),
onPressed: () => Navigator.pop(context),
),
Text(
'Shopping cart',
style: TextStyle(
fontSize: 21.0,
color: Colors.black26,
fontWeight: FontWeight.bold,
),
),
],
),
Container(
margin: EdgeInsets.only(top: 8.0, bottom: 8.0),
height: MediaQuery.of(context).size.height / 16,
width: MediaQuery.of(context).size.width - 150,
decoration: BoxDecoration(
border: Border.all(color: kThemeStyleButtonFillColour),
borderRadius: BorderRadius.circular(5.0),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Customer drop down',
textAlign: TextAlign.center,
style: kRegularTextStyle,
maxLines: 2,
textDirection: TextDirection.ltr,
softWrap: true,
),
SizedBox(width: 5.0),
Icon(
Icons.keyboard_arrow_down,
color: kThemeStyleButtonFillColour,
size: 25,
),
],
),
),
Expanded(
flex: 4,
child: Container(
height: MediaQuery.of(context).size.height - 225,
padding: const EdgeInsets.only(
left: 16, right: 16, bottom: 8.0),
child: ListView.builder(
itemCount: cartData.cartItems.length,
shrinkWrap: true,
itemBuilder: (context, index) {
final cartItem = cartData.cartItems[index];
return cartData.cartItems.isEmpty
? Container(
child: Align(
alignment: Alignment.center,
child: Text('Your cart is empty')))
: Container(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 6.0),
child: Row(
children: <Widget>[
Expanded(
child: Container(
width: 80.0,
height: 70.0,
child: Center(
child: cartItem.imageURl == null
? Container(
padding:
EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: Color((math.Random()
.nextDouble() *
0xFFFFFF)
.toInt())
.withOpacity(1.0),
borderRadius:
BorderRadius.circular(
20.0),
),
)
: Container(
padding:
EdgeInsets.all(4.0),
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
cartItem.imageURl),
),
borderRadius:
BorderRadius.circular(
20.0),
),
),
),
),
),
SizedBox(width: 12.0),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 100.0,
child: Text(
cartItem.description,
style: TextStyle(
fontWeight: FontWeight.bold),
),
),
SizedBox(height: 8.0),
Row(
children: <Widget>[
GestureDetector(
child: Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius:
BorderRadiusDirectional
.circular(4.0),
),
child: Icon(
Icons.remove,
color: Colors.white,
size: 15.0,
),
),
onTap: () {
cartData.upDateCartItem(
cartItem, false);
},
),
Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 15.0),
child: Text(
'${cartItem.quantity}',
style: TextStyle(
fontWeight:
FontWeight.bold,
fontSize: 15.0),
),
),
GestureDetector(
child: Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
color:
kThemeStyleButtonFillColour,
borderRadius:
BorderRadiusDirectional
.circular(4.0),
),
child: Icon(
Icons.add,
color: Colors.white,
size: 15.0,
),
),
onTap: () {
cartData.upDateCartItem(
cartItem, true);
},
),
],
),
],
),
// Spacer(),
Expanded(
child: Text(
'${cartData.getAmount(cartItem.quantity, cartItem.unitCost)}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15.0),
),
),
Expanded(
child: GestureDetector(
child: Icon(
Icons.delete_forever,
size: 25.0,
color: kThemeStyleButtonFillColour,
),
onTap: () => cartData
.deleteItemFromCart(cartItem),
),
),
],
),
);
},
),
),
),
],
);
},
),
),
),
);
}
}
What could I be missing here?
Calling your addItemToCart() should rebuild the children inside Consumer<CartData>() because of notifyListeners(). This should help you give some clue on what's happening.
Add a debugPrint('List length: ${cartData.cartItemsCount}') inside the Consumer to check if List _cartItems changes after adding an item.