Home > Enterprise >  how do I transfer it to the other list , If an array in a string is equal to the id of an object?
how do I transfer it to the other list , If an array in a string is equal to the id of an object?

Time:11-01

enter image description here

the string is coming like this, I want to add the objects if this objects id's are equal with this string array elements.

I am fetching the data,I convert it as model List =>List<DataDependantListModel> listModel; I have tried to create condition but I couldn't. here is the class model ;

class DataDependantListModel {
String? id;
String? name;

DataDependantListModel({this.id, this.name});

DataDependantListModel.fromJson(Map<String, dynamic> json) {
id = json['Id'];
name = json['Name'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['Name'] = name;
return data;
}
}

CodePudding user response:

Wow that's really strange if back-end return the response like that. It obviously should be a list, not a string. In my opinion, you have to ask back-end guys to change. Otherwise, you could do like this:

String strResponse = json["VisaFamilyId"] as String;
strResponse = strResponse.substring(1, strResponse.length - 1); // remove '[' and ']'
List<String> visaFamilyIds = strResponse.split(","); // every id is separated to each other by a comma

Well, now you get your list of ids, which are given by back-end. As your question, how to get list of listModel which have id in visaFamilyIds? You could code like this:

List<DataDependantListModel> result = listModel.map((e) => visaFamilyIds.contains(e.id)).toList();

By the way, please carefully check your DataDependantListModel. Are the fields id and name can be nullable? I don't think so.

Good luck.

CodePudding user response:

You could use jsonDecode from dart:convert to parse the VisaFamilyId ("[6, 1003]") and then use where on listModel to filter out the common entries.

final visaFamilyId = jsonDecode('[1, 2]');
final result = listModel.where((e) => visaFamilyId.contains(e.id)).toList();
  • Related