【问题标题】:How to perform .reduce on Hive List flutter如何在 Hive List Flutter 上执行 .reduce
【发布时间】:2021-09-14 21:44:04
【问题描述】:

我有一个 Hive 对象

import 'package:hive/hive.dart';

part 'cartHiveModel.g.dart';

@HiveType(typeId: 0)
class CartModel extends HiveObject {
  // for the product title
  @HiveField(0)
  late final String title;
  // for checking the store id
  @HiveField(1)
  late final String storeID;
  // fot the product image
  @HiveField(2)
  late final String image;
  // for the discounted price
  @HiveField(3)
  late final int price;
  // for the original price
  @HiveField(4)
  late final int originalPrice;
  // for the quantity.
  @HiveField(5)
  late final int quantity;

  CartModel({
    required this.image,
    required this.originalPrice,
    required this.price,
    required this.quantity,
    required this.storeID,
    required this.title,
  });
}

当我尝试通过以下方式计算总金额时

var list = Hive.box<CartModel>('cartModel').values;
                list.reduce((value, element) => value.price + value.price);

它给了我这样的运行时错误:

The return type 'int' isn't a 'CartModel', as required by the closure's context.

我想要什么:我想计算列表中的总金额并将总和作为整数返回。

【问题讨论】:

    标签: flutter dart flutter-hive


    【解决方案1】:

    reduce 的返回类型是您要减少的列表的类型。您将返回 int 并添加,但它希望返回 CartModel

    相反,您可以map/reduce,其中map 首先创建ints 列表(price 属性):

    list.map((item) => item.price).reduce((sum, price) => sum + price);
    

    或者你可以使用fold:

    list.fold(0, (sum, item) => sum + item.price);
    

    【讨论】:

    • 非常感谢你回答马特:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多