flutter 使用提供程序时出现问题

ozxc1zmp  于 2023-02-16  发布在  Flutter
关注(0)|答案(1)|浏览(135)

我一直在试着让结账台显示购物篮里东西的总价,但结果比我想象的要难得多。
列表userOrders包含用户放入购物篮中的所有内容
https://ibb.co/DQwTyHC
提供程序类:(或者它应该是什么)

class TotalPrice with ChangeNotifier {
  int ordersTotalPrice = 0;

  int totalPrice() {
    final ordersTotalPrice =
        userOrders.fold(0, (sum, order) => sum + order.totalPrice);
    notifyListeners();
    return ordersTotalPrice;
  }
}

食物:

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 按钮

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('');
  }
}
myzjeezk

myzjeezk1#

在这里,您引入了局部变量,因此字段orderTotalPrice不会像您所做的那样得到更新

final ordersTotalPrice = userOrders.fold(0, (sum, order) => sum + order.totalPrice);

将此行更改如下

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}');
            },
          )

相关问题