List<ServiceModel> serviceList = [
ServiceModel(id: "12", name: "Repair", subServiceList: [
SubServiceModel(name: "Toilet Repair", id: "123"),
SubServiceModel(name: "SafetyTank Repair", id: "456"),
SubServiceModel(name: "Roof Repair", id: "789")
]),
ServiceModel(id: "13", name: "Fixing", subServiceList: [
SubServiceModel(name: "Roof fix", id: "222"),
SubServiceModel(name: "pipe fix", id: "111")
]),
];
我有上面的数据…我需要做的是对servicemodel进行多次选择,并且可以从子服务列表中删除任何选择,这样我就可以只针对特定的servicemodel拥有特定的选择数据。
首先,您需要使ServiceModel的一个实例与其他实例不同:
class ServiceModel{
final String id;
final String name;
ServiceModel({required this.name, required this.id });
@override
bool operator ==(other) => other.hashCode == hashCode && other is ServiceModel;
@override
int get hashCode => id.hashCode;
}
显示如下:
var service1 = ServiceModel(id:"1", name:"service1");
var service2 = ServiceModel(id:"2", name:"service2");
var service3 = ServiceModel(id:"1", name:"service3")
//false
print(service1 == service2);
//true, because their ids are same
print(service1 == service3);
然后让我们创建一个ServiceModel树实体。每个serviceModel都有子服务(子服务)。为什么树?它将为您提供灵活性,您可以创建嵌套的ServiceModel,不仅是2级,而是您想要的任何级别。更新上面的代码:
class ServiceModel {
final String id;
final String name;
final List<ServiceModel> subServices;
ServiceModel(
{required this.name,
required this.id,
this.subServices = const [],});
@override
bool operator ==(other) =>
other.hashCode == hashCode && other is ServiceModel;
@override
int get hashCode => id.hashCode;
}
现在修改代码构建servicesList:
List<ServiceModel> serviceList = [
ServiceModel(id: "12", name: "Repair", subServices: [
ServiceModel(name: "Toilet Repair", id: "123"),
ServiceModel(name: "SafetyTank Repair", id: "456"),
ServiceModel(name: "Roof Repair", id: "789")
]),
ServiceModel(id: "13", name: "Fixing", subServices: [
ServiceModel(name: "Roof fix", id: "222"),
ServiceModel(name: "pipe fix", id: "111")
]),
];
那么如何构建选定的ServiceModels列表呢?容易:
List<ServiceModel> selectedServices = [];
List<ServiceModel> serviceList = [
ServiceModel(id: "12", name: "Repair", subServices: [
ServiceModel(name: "Toilet Repair", id: "123"),
ServiceModel(name: "SafetyTank Repair", id: "456"),
ServiceModel(name: "Roof Repair", id: "789")
]),
ServiceModel(id: "13", name: "Fixing", subServices: [
ServiceModel(name: "Roof fix", id: "222"),
ServiceModel(name: "pipe fix", id: "111")
]),
];
//you may add whatever service, each of them has unique hashCode according to id
selectedServices.add(serviceList.first.subServices.first);
//true
print(selectedServices
.contains(ServiceModel(name: "Toilet Repair", id: "123")));