如何在 Hive List flutter 上执行 .reduce
How to perform .reduce on Hive List flutter
我有一个 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.
我想要什么:我想计算列表中的总金额和return整个总和作为一个整数。
reduce
的 return 类型是您要减少的列表的类型。您正在 return 添加一个 int
,但它期望 CartModel
被 return 编辑。
相反,您可以 map
/reduce
,其中 map
首先创建 int
的列表(price
属性 ):
list.map((item) => item.price).reduce((sum, price) => sum + price);
或者您可以使用 fold
:
list.fold(0, (sum, item) => sum + item.price);
我有一个 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.
我想要什么:我想计算列表中的总金额和return整个总和作为一个整数。
reduce
的 return 类型是您要减少的列表的类型。您正在 return 添加一个 int
,但它期望 CartModel
被 return 编辑。
相反,您可以 map
/reduce
,其中 map
首先创建 int
的列表(price
属性 ):
list.map((item) => item.price).reduce((sum, price) => sum + price);
或者您可以使用 fold
:
list.fold(0, (sum, item) => sum + item.price);