英文:
Trouble using Provider
问题
以下是翻译好的部分:
"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"
"列表userOrders
包含用户放入购物篮中的所有物品。"
"Provider class: (Or what it's supposed to be)"
"提供者类:(或它应该是什么样子的)"
"Food:"
"食物类:"
"CheckOut button"
"结账按钮"
英文:
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('');
}
}
答案1
得分: 0
在这里,您引入了本地变量,因此字段 orderTotalPrice
没有被更新,因为您有以下代码
更改此行如下
ordersTotalPrice = userOrders.fold(0, (sum, order) => sum + order.totalPrice);
编辑
使用 AnimationBuilder
刷新UI中已更改的数据。
AnimatedBuilder(
animation: context.read<TotalPrice>(),
builder: (BuildContext context, Widget? child) {
return Text('${context.read<TotalPrice>().ordersTotalPrice}');
},
)
英文:
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}');
},
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论