I've been trying trying to make the checkout show the total price of what's in the basket. But turns it's way more difficult than I thought.
The list userOrders
holds all the user has put into the basket
Provider class: (Or what it's suppossed to be)
class TotalPrice with ChangeNotifier {
int ordersTotalPrice = 0;
int totalPrice() {
final ordersTotalPrice =
userOrders.fold(0, (sum, order) => sum + order.totalPrice);
notifyListeners();
return ordersTotalPrice;
}
}
Food:
class Food {
String imgUrl;
String desc;
String name;
String waitTime;
num score;
int price;
int quantity;
List<Map<String, String>> ingredients;
String about;
bool highlight;
Food(this.imgUrl, this.desc, this.name, this.waitTime, this.score, this.price,
this.quantity, this.ingredients, this.about,
{this.highlight = false});
}
CheckOut button
class _NextButtonState extends State<NextButton> {
String getCurrency() {
var format = NumberFormat.simpleCurrency(name: 'NGN');
return format.currencySymbol;
}
@override
Widget build(BuildContext context) {
return userOrders.isNotEmpty
? Container(
color: Colors.transparent,
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 5.0, 5.0),
height: 60,
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: const BorderSide(color: Colors.transparent),
),
),
),
child: Text(
'${getCurrency()}${context.watch<TotalPrice>().ordersTotalPrice}',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
onPressed: () {},
),
)
: Text('');
}
}
Here, you introduced local variable so the field orderTotalPrice
didn't get updated as you have
final ordersTotalPrice = userOrders.fold(0, (sum, order) => sum + order.totalPrice);
change this line as following
ordersTotalPrice = userOrders.fold(0, (sum, order) => sum + order.totalPrice);
Edited
Use AnimationBuilder
to refresh the changed data in UI.
AnimatedBuilder(
animation: context.read<TotalPrice>(),
builder: (BuildContext context, Widget? child) {
return Text('${context.read<TotalPrice>().ordersTotalPrice}');
},
)