如何让功能更高效?
这是我写的所有测试代码:
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter_test/flutter_test.dart';
void main() {
test(
'find list item and apply math',
() {
final mockList = <Model>[
Model(id: '1', name: 'Cortado', price: 12),
Model(id: '2', name: 'Caffe Latte', price: 24),
Model(id: '3', name: 'Americano', price: 48),
Model(id: '4', name: 'Turkish Coffee', price: 96),
Model(id: '5', name: 'Filter Coffee', price: 64),
Model(id: '6', name: 'Flat White', price: 128),
];
final selectItems = [mockList[0], mockList[3]];
final result = findAndOperate(
mainList: mockList,
selectedList: selectItems,
operations: Operations.PLUS,
value: 40,
);
print(result);
},
);
}
List<Model> findAndOperate({
required double value,
required Operations operations,
required List<Model> mainList,
required List<Model> selectedList,
}) {
for (final selectItem in selectedList) {
for (final item in mainList) {
if (item == selectItem) {
final itemIndex = mainList.indexOf(item);
switch (operations) {
case Operations.PLUS:
final changeItem =
selectItem.copyWith(price: selectItem.price + value);
mainList.removeAt(itemIndex);
mainList.insert(itemIndex, changeItem);
case Operations.MULTIPLICATION:
final changeItem = selectItem.copyWith(
price: selectItem.price + (selectItem.price * value),
);
mainList.removeAt(itemIndex);
mainList.insert(itemIndex, changeItem);
}
}
}
}
return mainList;
}
// ignore: constant_identifier_names
enum Operations { PLUS, MULTIPLICATION }
// ignore: one_member_abstracts
class Model {
Model({required this.id, required this.name, required this.price});
final String id;
final String name;
final double price;
Model copyWith({
String? id,
String? name,
double? price,
}) {
return Model(
id: id ?? this.id,
name: name ?? this.name,
price: price ?? this.price,
);
}
@override
String toString() => 'MockModel(id: $id, name: $name, price: $price)';
@override
bool operator ==(covariant Model other) {
if (identical(this, other)) return true;
return other.id == id && other.name == name && other.price == price;
}
@override
int get hashCode => id.hashCode ^ name.hashCode ^ price.hashCode;
}
我编写的函数按预期工作,但我对此很陌生,我很好奇我可以改进或学习什么。
运行该函数时出现的结果:
[MockModel(id: 1,名称:Cortado,价格:52.0),MockModel(id:2,名称:Caffe Latte,价格:24.0),MockModel(id:3,名称:Americano,价格:48.0),MockModel( id: 4, 名称: 土耳其咖啡, 价格: 136.0), MockModel(id: 5, 名称: 过滤咖啡, 价格: 64.0), MockModel(id:6,名称:Flat White,价格:128.0)]
开关盒中缺少
break;
语句。这意味着代码将继续到下一个案例,但这实际上是不需要的。
我很确定你可以避免内循环。您正在检查
mainList
中的每个项目和 selectedList
中的每个项目