Context: Found this candidate, but the arguments don't match - flutter

I'm new on flutter, I have 2 screens and I have tried a lot to fix the problems and make this code run, the error shows when I tried to push arguments in the constructor to BmiResultScreen
BmiScreen code (which i need to get the values from):
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'bmi_result_screen.dart';
class BmiScreen extends StatefulWidget {
#override
_BmiScreenState createState() => _BmiScreenState();
}
class _BmiScreenState extends State<BmiScreen> {
bool isMale = true;
double height = 120.0;
int age = 0;
double weight = 0.0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BMI Calculator'),
),
body: Column(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(children: [
Expanded(
child: GestureDetector(
onTap: (){
setState(() {
isMale = true;
});
},
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Image(
image: AssetImage('assets/images/male.png'),
height: 90.0,
width: 90.0,
),
SizedBox(
height: 15.0,
),
Text('MALE',
style: TextStyle(
fontSize: 25.0, fontWeight: FontWeight.bold))
],
),
decoration: BoxDecoration(
color: isMale ? Colors.blue : Colors.grey[400],
borderRadius: BorderRadiusDirectional.circular(10.0)),
),
),
),
SizedBox(
width: 20.0,
),
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
isMale = false;
});
},
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Image(
image: AssetImage('assets/images/female.png'),
height: 90,
width: 90,
),
SizedBox(
height: 15.0,
),
Text('FEMALE',
style: TextStyle(
fontSize: 25.0, fontWeight: FontWeight.bold))
],
),
decoration: BoxDecoration(
color: !isMale ? Colors.blue : Colors.grey[400],
borderRadius: BorderRadiusDirectional.circular(10.0)),
),
),
),
]),
)),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0
),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadiusDirectional.circular(10.0)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('HEIGHT',
style:
TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold)),
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${height.round()}',
style: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.w900,
)
),
SizedBox(
width: 5.0,
),
Text(
'cm',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w900
),
),
],
),
Slider(
value: height,
max: 220.0,
min: 80.0,
onChanged: (value) {
setState(() {
height = value;
});
},
),
],
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadiusDirectional.circular(10.0)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'WEIGHT',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
)
),
SizedBox(
height: 15.0,
),
Text(
'${weight}',
style: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.w900,
)
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
setState(() {
if(weight>=0.5){
weight = weight -0.5;
}
});
},
child: Icon(
Icons.remove
),
mini: true,
heroTag: '--weight',
),
FloatingActionButton(
onPressed: () {
setState(() {
weight = weight + 0.5;
});
},
child: Icon(
Icons.add
),
mini: true,
heroTag: '++weight',
),
],
),
],
),
),
),
SizedBox(
width: 20.0,
),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadiusDirectional.circular(10.0)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'AGE',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
)
),
SizedBox(
height: 15.0,
),
Text(
'${age}',
style: TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.w900,
)
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
setState(() {
if(age >= 1){
--age;
}
});
},
child: Icon(
Icons.remove
),
mini: true,
heroTag: '--age',
),
FloatingActionButton(
onPressed: () {
setState(() {
++age;
});
},
child: Icon(
Icons.add
),
mini: true,
heroTag: '++age',
),
],
),
],
),
),
),
],
),
),
),
Container(
color: Colors.blue,
width: double.infinity,
height: 50.0,
child: MaterialButton(
onPressed: () {
double result = weight / pow(height/100,2);
print(result.round());
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BmiResultScreen(
isMale: isMale,
age: age,
result: result.round(),
),
)
);
},
child: const Text('CALCULATE'),
),
),
],
),
);
}
}
BmiResultScreen code(which I'm trying to use the values comes from the last screen):
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
class BmiResultScreen extends StatelessWidget {
final bool isMale;
final int result;
final int age;
BmiResultScreen({
required this.isMale,
required this.age,
required this.result,
});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'BMI Result'
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Gender: $isMale',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
),
),
Text(
'Result: ${result.round()}',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
),
),
Text(
'Age: $age',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
),
),
],
),
)
);
}
}

Problems like this can be fixed by upgrading your flutter version or cleaning.
flutter upgrade --force
flutter clean
delete Podfile and Podfile.lock
run pub get
flutter run

Related

error: The argument type 'File?' can't be assigned to the parameter type 'File'. Flutter

I want to select an image from the gallery and display it at the bottom of the container when the container is clicked using image_picker. But 'The argument type 'File?' can't be assigned to the parameter type 'File'. ' error occurs. I searched hard for an answer on Google and StackOverFlow, but couldn't solve it. What should I do?
This is my code:
import 'dart:io';
import 'package:flutter/material.dart';
import '../../../constants.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
class UploadFishingVesselImages extends StatefulWidget {
const UploadFishingVesselImages({Key? key}) : super(key: key);
#override
State<UploadFishingVesselImages> createState() =>
_UploadFishingVesselImagesState();
}
class _UploadFishingVesselImagesState extends State<UploadFishingVesselImages> {
File? _image;
final _picker = ImagePicker();
Future choiceImage() async {
var pickedImage = await _picker.pickImage(source: ImageSource.gallery);
if (pickedImage == null) return null;
setState(() {
_image = File(pickedImage.path);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: baseColor10,
elevation: 0,
leading: IconButton(
onPressed: () {
Get.back();
},
icon: Icon(Icons.arrow_back),
color: baseColor50,
),
title: Text(
'선박판매등록',
style: TextStyle(
color: baseColor50,
fontFamily: 'semi-bold',
fontSize: titleMedium,
),
),
),
body: GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TopBar(context),
marginHeight32,
buildTextColumn(),
Row(
children: [
GestureDetector(
onTap: () async {
await choiceImage();
},
child: Expanded(
child: Container(
height: 90,
width: MediaQuery.of(context).size.width * 0.3,
decoration: BoxDecoration(
color: baseColor20,
),
),
),
),
SizedBox(width: 10),
Expanded(
child: Container(
height: 90,
width: MediaQuery.of(context).size.width * 0.3,
decoration: BoxDecoration(
color: baseColor20,
),
),
),
SizedBox(width: 10),
Expanded(
child: Container(
height: 90,
width: MediaQuery.of(context).size.width * 0.3,
decoration: BoxDecoration(
color: baseColor20,
),
),
),
],
),
// Error occurs. 'The argument type 'File?' can't be assigned
// to the parameter type 'File'.
Image.file(_image),
],
),
),
),
),
),
floatingActionButton: Visibility(
visible: MediaQuery.of(context).viewInsets.bottom == 0,
child: FloatingActionButton(
backgroundColor: primaryColor50,
foregroundColor: baseColor10,
focusColor: primaryColor50,
onPressed: () {},
child: Icon(
Icons.arrow_forward_ios_rounded,
),
),
),
);
}
// 상단 텍스트
Column buildTextColumn() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'사진 등록',
style: TextStyle(
color: baseColor50,
fontSize: titleMedium,
fontFamily: 'semi-bold',
),
),
marginHeight4,
Text(
'판매선박의 사진을 등록해주세요.(최대 20장)'
'\n다양하고 선명한 사진을 올릴 경우, 판매 확률이 더욱 높아집니다.',
style: TextStyle(
fontSize: bodySmall,
),
),
marginHeight32,
],
);
}
// 상단바
Column TopBar(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
child: Container(
height: 3,
color: baseColor30,
width: MediaQuery.of(context).size.width * 0.2,
),
),
Expanded(
child: Container(
height: 3,
color: baseColor30,
width: MediaQuery.of(context).size.width * 0.2,
),
),
Expanded(
child: Container(
height: 3,
color: baseColor30,
width: MediaQuery.of(context).size.width * 0.2,
),
),
Expanded(
child: Container(
height: 3,
color: primaryColor50,
width: MediaQuery.of(context).size.width * 0.2,
),
),
Expanded(
child: Container(
height: 3,
color: baseColor30,
width: MediaQuery.of(context).size.width * 0.2,
),
),
],
),
marginHeight4,
Row(
children: [
Expanded(
child: Container(
child: Center(
child: Text(
'선박정보',
style: TextStyle(
fontFamily: 'medium',
fontSize: labelSmall,
color: baseColor30,
),
),
),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
'옵션',
style: TextStyle(
fontFamily: 'medium',
fontSize: labelSmall,
color: baseColor30,
),
),
),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
'설명등록',
style: TextStyle(
fontFamily: 'medium',
fontSize: labelSmall,
color: baseColor30,
),
),
),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
'사진등록',
style: TextStyle(
fontFamily: 'medium',
fontSize: labelSmall,
color: primaryColor50,
),
),
),
),
),
Expanded(
child: Container(
child: Center(
child: Text(
'결제',
style: TextStyle(
fontFamily: 'medium',
fontSize: labelSmall,
color: baseColor30,
),
),
),
),
),
],
),
],
);
}
}
you are facing this error cause Image.file() does not accept nullable variable and your _image variable is nullable so you have to set condition for it you can set like this.
_image==null?Container(): Image.file(_image??File('')),
this condition will not throw any nullable error. and you can put any different widget instead of container if you want to show anything else when the _image is null.
If youre sure that your File? object is not null, you can use null check operator ! to get rid of that error. Like
Image.file(_image!),

Flutter using ChangeNotifierProvider.value

i have Provider model:
class TerminalDataModel with ChangeNotifier{
List<Item> _itemMenu = listItems;
final List<Order> _ordersList = orders;
Order? _currentOrder;
Order? get currentOrder => _currentOrder;
List<Order> get ordersList => _ordersList;
void createOrder() {
_currentOrder = Order(
user: currentUser?.name,
number: 1,
orderStatus: OrderStatus.opened,
time: DateTime.now());
_ordersList.add(_currentOrder!);
notifyListeners();
}
void changeOrder(Order order){
}
}
and two pages: 1. terminal page: on this page I can view my selected order and can change it or change status(paid or for example closed)
class OrderList extends StatelessWidget {
TerminalDataModel terminalDataModel = TerminalDataModel();
OrderList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: ChangeNotifierProvider<TerminalDataModel>.value(
value: terminalDataModel,
child: OrdersTableView(),
));
}
}
class OrdersTableView extends StatelessWidget {
List<GlobalKey> _key = List.generate(3, (v) => new GlobalKey());
double yPosition = 170;
var provider;
OrdersTableView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
provider = Provider.of<TerminalDataModel>(context, listen: true);
GlobalKey key = GlobalKey();
return Column(
children: [
Stack(
children: [
Container(
height: 40,
color: Styles.appBarColor,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Container(
height: double.infinity,
width: 50,
color: Styles.blackColor,
child: IconButton(
onPressed: () {
Navigator.pushNamed(context, '/terminal');
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
)),
Row(
children: [
Text(currentUser?.name ?? '',
style: const TextStyle(
color: Colors.white, fontSize: 18)),
const Icon(
Icons.lock,
color: Colors.white,
),
],
),
],
),
),
SizedBox(
height: 40,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Center(
child: Text('Orders',
style: TextStyle(color: Colors.white, fontSize: 18))),
],
),
),
],
),
Stack(children: [
Container(
height: 50,
width: MediaQuery.of(context).size.width,
color: Styles.blackColor,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
Provider.of<TerminalDataModel>(context, listen: false)
.createOrder();
},
child: const Text("New order",
style: TextStyle(color: Colors.white, fontSize: 18)),
),
const SizedBox(
width: 25,
),
TextButton(
key: _key[0],
onPressed: () {},
child: const Text('All Status',
style: const TextStyle(
color: Colors.white, fontSize: 18))),
const SizedBox(
width: 25,
),
TextButton(
key: _key[1],
onPressed: () {},
child: const Text('Wait pay',
style: TextStyle(color: Colors.white, fontSize: 18))),
const SizedBox(
width: 25,
),
TextButton(
key: _key[2],
onPressed: () {},
child: const Text('Payed',
style: TextStyle(color: Colors.white, fontSize: 18))),
],
),
),
),
Positioned(
bottom: -22,
left: yPosition,
child: const Icon(
Icons.arrow_drop_up,
size: 50,
color: Colors.white,
))
]),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: SizedBox(
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Expanded(
flex: 3,
child: Text('Open',
style: TextStyle(color: Colors.black, fontSize: 18))),
Expanded(
flex: 5,
child: Text('Order',
style: TextStyle(color: Colors.black, fontSize: 18))),
Expanded(
flex: 3,
child: Text('Status',
style: TextStyle(color: Colors.black, fontSize: 18))),
Expanded(
flex: 1,
child: Text('Sum',
style: TextStyle(color: Colors.black, fontSize: 18))),
],
),
),
),
const Divider(),
ordersList(provider.ordersList, context),
],
);
}
double getYPositionOfWidget(
GlobalKey key,
) {
RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero); //this is global position
double y = position.dy;
return y;
}
Widget ordersList(List<Order> orderList, BuildContext context) {
Column ordersTable = Column(
children: <Widget>[],
);
for (int i = 0; i <= orderList.length - 1; i++) {
ordersTable.children.add(
GestureDetector(
onTap: () {
//Navigator.pushNamed(context, '/terminal',arguments: {'model': provider });
Navigator.push(context, MaterialPageRoute(builder: (contex) {
return Provider<TerminalDataModel>.value(
value: provider, child: PosTerminal());
}));
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: SizedBox(
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
flex: 3,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${orderList[i].time!.hour}:${orderList[i].time!.minute}",
style: const TextStyle(
color: Colors.black, fontSize: 18)),
Text(getTimeAgo(orderList[i].time ?? DateTime.now()),
style: const TextStyle(
color: Colors.black, fontSize: 13))
],
)),
const Expanded(
flex: 5,
child: Text('Order',
style: TextStyle(color: Colors.black, fontSize: 18))),
const Expanded(
flex: 3,
child: Text('Status',
style: TextStyle(color: Colors.black, fontSize: 18))),
const Expanded(
flex: 1,
child: Text('Sum',
style: TextStyle(color: Colors.black, fontSize: 18))),
],
),
),
),
),
);
ordersTable.children.add(const Divider());
}
return ordersTable;
}
String getTimeAgo(DateTime dateTime) {
String timeAgo = '';
if (dateTime.hour < DateTime.now().hour) {
timeAgo += "${DateTime.now().hour - dateTime.hour} hours, ";
}
if (dateTime.minute < DateTime.now().minute) {
timeAgo += "${DateTime.now().minute - dateTime.minute} minutes";
}
return timeAgo;
}
}
and 2. order_detale page: there I show a list of orders and can create a new order
class PosTerminal extends StatelessWidget {
PosTerminal({Key? key, }) : super(key: key);
#override
Widget build(BuildContext context) {
print(Provider.of<TerminalDataModel>(context,listen: false).ordersList);
return Scaffold(
backgroundColor: Styles.backgroundColor,
body: ChangeNotifierProvider(
create: (context) => TerminalDataModel(),
child: const PosBody(),
)
);
}
}
class PosBody extends StatelessWidget {
const PosBody({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
double sizeW = MediaQuery.of(context).size.width;
double appBarH = 35;
return Column(
children: [
SizedBox(
width: sizeW,
height: appBarH,
child: Stack(children: [
SizedBox(
width: sizeW,
height: appBarH,
child: Container(
color: Styles.appBarColor,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
ElevatedButton.icon(
onPressed: () {
Navigator.pushNamed(context, '/orders');
},
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
label: Text(AppLocalizations.of(context)!.orders,
style: const TextStyle(
color: Colors.white, fontSize: 18)),
style: ElevatedButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
/* Please add this to avoid padding */
elevation: 0,
primary: Colors.transparent,
),
),
SizedBox(
height: appBarH - 3,
width: 100,
child: ElevatedButton(
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Styles.backgroundColor),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4),
topRight: Radius.circular(4),
))),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
elevation: MaterialStateProperty.all(0),
),
child: Text(
AppLocalizations.of(context)!.order,
style: const TextStyle(
color: Colors.black, fontSize: 18),
),
),
),
],
),
Row(
children: [
const Text("Сергей",
style:
TextStyle(color: Colors.white, fontSize: 18)),
const SizedBox(
width: 5,
),
const Icon(
Icons.lock,
color: Colors.white,
),
ElevatedButton.icon(
onPressed: () {
final action = CupertinoActionSheet(
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text(
"Admin panel",
style:
TextStyle(color: Styles.appBarColor),
),
onPressed: () {
Navigator.pushNamed(
context, '/adminPanel');
},
),
CupertinoActionSheetAction(
child: const Text("Settings",
style: TextStyle(
color: Styles.appBarColor)),
onPressed: () {},
)
],
cancelButton: CupertinoActionSheetAction(
child: const Text(
"Cancel",
style: TextStyle(color: Colors.red),
),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(
context: context,
builder: (context) => action);
},
icon: const Icon(Icons.menu),
label: const Text(""),
style: ElevatedButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
/* Please add this to avoid padding */
elevation: 0,
primary: Colors.transparent,
),
),
],
)
],
),
),
),
SizedBox(
width: sizeW,
height: appBarH,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text("Чек № 2323",
style: TextStyle(color: Colors.white, fontSize: 18)),
],
),
),
]),
),
SizedBox(
height: MediaQuery.of(context).size.height - appBarH,
child: Row(
children: [
Expanded(
flex: 2,
child: Container(
color: Styles.backgroundColor,
child: Column(
children: [
const SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Expanded(flex: 4, child: Text("Наименование")),
Expanded(flex: 1, child: Text("Кол-во")),
Expanded(flex: 1, child: Text("Цена")),
Expanded(flex: 1, child: Text("Итого")),
],
),
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 15.0),
child: Divider(
height: 1,
color: Colors.black12,
),
),
SizedBox(
height: MediaQuery.of(context).size.height -
appBarH -
200,
child: Container(),
),
const Divider(
height: 1,
color: Colors.black12,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 25, vertical: 10),
child: Column(
children: [
Row(
children: const [
Text("Итого"),
],
),
const SizedBox(
height: 10,
),
Row(
children: const [
Text("К оплате"),
],
),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 15),
child: SizedBox(
height: 30,
width: double.infinity,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
),
onPressed: () {},
child: const Text("Pay")),
),
)
],
)),
],
),
),
),
Expanded(
flex: 4,
child: Container(
color: Colors.white,
),
),
],
),
)
],
);
}
}
On the model, I save my orders and when I tap on the order I want to pass an object to the 2nd-page, update it and when I pop my 2nd-page list of orders should be updated. How I can do it?

StateError was thrown building StreamBuilder<DocumentSnapshot<Object?>Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

I am Trying to build an app. which fetching the user credential data and shows in profile page. I am getting an error => Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist in the profile section need help
Widget headerProfile(BuildContext context, DocumentSnapshot snapshot) {
return SizedBox(
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Container(
height: 200.0,
width: 180.0,
child: Column(
children: [
GestureDetector(
onTap: () {},
child: CircleAvatar(
backgroundColor: constantColors.transperant,
radius: 60.0,
backgroundImage: NetworkImage(snapshot['userimage']),
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(snapshot['username'],
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 16.0)),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(EvaIcons.email, color: constantColors.greenColor),
Padding(
padding: const EdgeInsets.only(left:9.0),
child: Text(snapshot['useremail'],
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 13.0)),
),
],
),
),
],
),
),
),
Container(
// width: 200.0,
width: 200.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top:16.0, right: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
decoration: BoxDecoration(
color: constantColors.darkColor,
borderRadius: BorderRadius.circular(15.0)),
height: 70.0,
width: 80.0,
child: Column(
children: [
Text(
'0',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 28.0),
),
Text(
'Followers',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 12.0),
),
],
),
),
Container(
decoration: BoxDecoration(
color: constantColors.darkColor,
borderRadius: BorderRadius.circular(15.0)),
height: 70.0,
width: 80.0,
child: Column(
children: [
Text(
'0',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 28.0),
),
Text(
'Following',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 12.0),
),
],
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(top:16.0),
child: Container(
decoration: BoxDecoration(
color: constantColors.darkColor,
borderRadius: BorderRadius.circular(15.0)),
height: 70.0,
width: 80.0,
child: Column(
children: [
Text(
'0',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 28.0),
),
Text(
'Posts',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 12.0),
),
],
),
),
),
],
),
)
],
),
);
}
I think the error is coming from the snapshot['username'], snapshot['userimage'] and snapshot['useremail'].....
This is my Profile.dart
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
leading: IconButton(
onPressed: () {},
icon: Icon(
EvaIcons.settings2Outline,
color: constantColors.lightBlueColor,
)),
actions: [
IconButton(
onPressed: () {},
icon: Icon(EvaIcons.logOutOutline,
color: constantColors.greenColor)),
],
backgroundColor: constantColors.blueGreyColor.withOpacity(0.4),
title: RichText(
text: TextSpan(
text: 'My ',
style: TextStyle(
color: constantColors.whiteColor,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
children: <TextSpan>[
TextSpan(
text: 'Profile',
style: TextStyle(
color: constantColors.blueColor,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
])),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false)
.getUserUid)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return new Column(
children: [
Provider.of<ProfileHelpers>(context, listen: false).headerProfile(context, snapshot.data)
],
);
}
},
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: constantColors.blueGreyColor.withOpacity(0.6)),
),
),
),
);
}
and below is the FirebaseOperations.dart
Future initUserData(BuildContext context) async {
return FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.get()
.then((doc) {
print('Fetching user data...');
initUserName = doc.data()['username'];
initUserEmail = doc.data()['useremail'];
initUserImage = doc.data()['userimage'];
print(initUserName);
print(initUserEmail);
print(initUserImage);
notifyListeners();
});
String initUserEmail, initUserName, initUserImage;
String get getInitUserName => initUserName;
String get getInitUserEmail => initUserEmail;
String get getInitUserImage => initUserImage;
All my code is this please help and there is user profile circle avatar at the bottom navbar it is also not the the image
Widget bottomNavBar(BuildContext context, int index, PageController pageController) {
return CustomNavigationBar(
currentIndex: index,
bubbleCurve: Curves.bounceIn,
scaleCurve: Curves.decelerate,
selectedColor: constantColors.blueColor,
unSelectedColor: constantColors.whiteColor,
strokeColor: constantColors.blueColor,
scaleFactor: 0.5,
iconSize: 30.0,
onTap: (val) {
index = val;
pageController.jumpToPage(val);
notifyListeners();
},
backgroundColor: Color(0xff040307),
items: [
CustomNavigationBarItem(icon: Icon(EvaIcons.home)),
CustomNavigationBarItem(icon: Icon(Icons.message_rounded)),
CustomNavigationBarItem(
icon: CircleAvatar(
radius: 35.0,
backgroundColor: constantColors.blueGreyColor,
backgroundImage: NetworkImage(Provider.of<FirebaseOperations>(context, listen: false).initUserImage),
)),
]);
}
Homepage.dart
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: constantColors.darkColor,
body: PageView(
controller: homepageController,
children: [
Feed(),
Chatroom(),
Profile(),
],
physics: NeverScrollableScrollPhysics(),
onPageChanged: (page) {
setState(() {
pageIndex = page;
});
},
),
bottomNavigationBar: Provider.of<HomepageHelpers>(context, listen: false)
.bottomNavBar(context, pageIndex, homepageController),
);
}
Please Help

Flutter layout, alignment, page controller, and how to make OnboardingScreen only one time?

i'm working on project for my university project and i'm having a problem.
First, i wanna add a back to my onboarding screen but i already use align for "next" on the bottom right while i want the back in the bottom left
Second, i wanna make the title (welcome,purpose,creator) in the middle, but i cannot put it in the center because i'm using a sizedbox
Third, i want the onboarding screen to only appear once, so when a user who have open it won't see it again (basically the first time opening, onboardingscreen but the second time straight to homepage)
sorry for my english
photo if you wanna visualize:
Photo
Here are the code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../home_screen.dart';
class Onboarding extends StatefulWidget {
#override
_OnboardingScreen createState() => _OnboardingScreen();
}
class _OnboardingScreen extends State<Onboarding> {
final int _numPages = 3;
final PageController _pageController = PageController(initialPage: 0);
int _currentPage = 0;
List<Widget> _buildPageIndicator() {
List<Widget> list = [];
for (int i = 0; i < _numPages; i++) {
list.add(i == _currentPage ? _indicator(true) : _indicator(false));
}
return list;
}
Widget _indicator(bool isActive) {
return AnimatedContainer(
duration: Duration(milliseconds: 150),
margin: EdgeInsets.symmetric(horizontal: 8.0),
height: 8.0,
width: isActive ? 24.0 : 16.0,
decoration: BoxDecoration(
color: isActive ? Colors.white : Color(0xFF7B51D3),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.1, 0.4, 0.7, 0.9],
colors: [
Colors.black,
Color(0xff112339),
Color(0xff112339),
Colors.black,
],
),
),
child: Padding(
padding: EdgeInsets.symmetric(vertical: 40.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
alignment: Alignment.centerRight,
child: FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},
child: Text(
'Skip',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
),
Container(
height: 600.0,
child: PageView(
physics: ClampingScrollPhysics(),
controller: _pageController,
onPageChanged: (int page) {
setState(() {
_currentPage = page;
});
},
children: <Widget>[
Padding(
padding: EdgeInsets.only(top:70.0,left: 40.0,right: 40.0,),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Center(
child: Image(
image: AssetImage(
'assets/images/Logo.png',
),
height: 120.0,
width: 120.0,
),
),
SizedBox(height: 50.0),
Text(
'Welcome',
style: TextStyle(
color: Colors.white,
fontSize: 21.0,
height: 1.5,
),
),
SizedBox(height: 30.0),
Text(
'Welcome to Moviez, the place where you will spend your time magically',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
height: 1.2,
fontFamily: 'Raleway',
),
),
],
),
),
Padding(
padding: EdgeInsets.only(top:70.0,left: 40.0,right: 40.0,),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Center(
child: Image(
image: AssetImage(
'assets/images/Logo.png',
),
height: 120.0,
width: 120.0,
),
),
SizedBox(height: 50.0),
Text(
'Purpose',
style: TextStyle(
color: Colors.white,
fontSize: 21.0,
height: 1.5,
),
),
SizedBox(height: 30.0),
Text(
'This App is for educational purposes only',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
height: 1.2,
),
),
],
),
),
Padding(
padding: EdgeInsets.only(top:70.0,left: 40.0,right: 40.0,),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Center(
child: Image(
image: AssetImage(
'assets/images/Logo.png',
),
height: 120.0,
width: 120.0,
),
),
SizedBox(height: 50.0),
Text(
'Creator',
style: TextStyle(
color: Colors.white,
fontSize: 21.0,
height: 1.5
),
),
SizedBox(height: 30.0),
Text(
'Adela, Caroline, Cordellya, David, Valentino',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
height: 1.2,
),
),
],
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: _buildPageIndicator(),
),
_currentPage != _numPages - 1
? Expanded(
child: Align(
alignment: FractionalOffset.bottomRight,
child: FlatButton(
onPressed: () {
_pageController.nextPage(
duration: Duration(milliseconds: 500),
curve: Curves.ease,
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'Next',
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
),
),
SizedBox(width: 10.0),
Icon(
Icons.arrow_forward,
color: Colors.white,
size: 30.0,
),
],
),
),
),
)
: Text(''),
],
),
),
),
),
bottomSheet: _currentPage == _numPages - 1
? Container(
height: 100.0,
width: double.infinity,
color: Colors.white,
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},
child: Center(
child: Padding(
padding: EdgeInsets.only(bottom: 30.0),
child: Text(
'Get started',
style: TextStyle(
color: Color(0xFF5B16D0),
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
)
: Text(''),
);
}
}
here is my main.dart
import 'package:flutter/material.dart';
import 'package:movie_app/screens/home_screen/widgets/onboard.dart';
import 'screens/home_screen/home_screen.dart';
void main() {
runApp(MyApp());
Paint.enableDithering = true;
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Movie App',
theme: ThemeData(
primarySwatch: Colors.blue,
iconTheme: IconThemeData(
color: Colors.white,
),
textTheme: ThemeData.light().textTheme.copyWith(
bodyText1: TextStyle(
// fontFamily: 'OpenSans',
// fontWeight: FontWeight.bold,
fontSize: 22,
color: Colors.white,
),
button: TextStyle(
color: Colors.white,
),
),
appBarTheme: AppBarTheme(
iconTheme: IconThemeData(color: Colors.white),
actionsIconTheme: IconThemeData(size: 30),
)),
home: Onboarding(),
);
}
}
Answering your first point:
Assuming that you want the "back" button on the same row as the "next" one, I would suggest you edit your Row widget as follows.
Row(children: [
Icon(Icons.arrow_back),
Text('Back'),
Spacer(),
Text('Next'),
Icon(Icons.arrow_forward),
])
I've used two Text widgets just to show you how it would look. In your app, you can use two different buttons with different text and different onTap or onPressed methods. You can check the Button section of this page to learn more about the different buttons available in Flutter.
Second: I think that all you have to do to have your titles centered on the screen is to change the crossAxisAlignment property of the related Column form CrossAxisAlignment.start to CrossAxisAlignment.center

Flutter: Updating UI from outside of a StatefulWidget

I am new to flutter, and working on a shopping cart project. i don't know how exatly i am suppose to ask this question but, here is what i wanted.
I am trying to update my UI when the cart item and prices changes, which means to display sum amount of products from ListView (Stateful widget) to main OrderPage Stateful widget. I know about setState() method, but i think i should use some callback methods here, dont know exactly.
I have explained in short in Image - see below img
What i have done: when user modify cart products, I have saved the value (price/product/count) in to constant value , i calculate the value and save in constant value, and later use that const var in Main widget (Main Ui), which does update when i close and reopen the page, but could not able to update when button pressed (product +/-buttons)
What i want to do is,
Update my total value when +/- buttons are pressed.
Here is my full code:
class cartConstant{
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text("Your order Summery",style: TextStyle(color: Colors.black54),),
centerTitle: true,
),
body: Container(
child:
FutureBuilder(
builder: (context, snapshot){
// var datas = snapshot.data;
return
ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index){
// Cart cart = datas[index];
return CartListView();
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i,int priceC){
cartConstant.packageCount = i*priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: (){
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap:(){
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {
},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
you can also check from my cart screen shot below:
You can copy paste run full code below
You can use callback refresh() and pass callback to CartListView
code snippet
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
...
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
...
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
...
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
working demo
full code
import 'package:flutter/material.dart';
class cartConstant {
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text(
"Your order Summery",
style: TextStyle(color: Colors.black54),
),
centerTitle: true,
),
body: Container(
child: FutureBuilder(
builder: (context, snapshot) {
// var datas = snapshot.data;
return ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"8000",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i, int priceC) {
cartConstant.packageCount = i * priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap: () {
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
widget.callback();
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: OrderPage(),
);
}
}
When the button is tapped, you just need to update the Subtotal amount and cart total.
Step 1 : Replace the harcoded value by a variable. So, something like :
Row(
children: <Widget>[
Text(
"Subtotal",
style: ...
),
Text(
"$subTotal",
style: ....
),
],
),
Step 2 : Now, add a code to calcualte subTotal and cartTotal. You already have code which increments and decrements the variable _counter. You just need to tweak that part like :
setState( (){
_counter++;
// So, the quantity is increased. Just get the price of current item and add in the sub total.
subTotal += priceC;
cartTotal = subTotal - discount;
} );