Search and find the string in List of DTO class in flutter? - list

I have this DTO class and in response of API i get the list of this :
class ProjectCode {
String id;
String projectCode;
String projectTitle;
ProjectCode({this.id, this.projectCode, this.projectTitle});
ProjectCode.fromJson(Map<String, dynamic> json) {
id = json['Id'];
projectCode = json['ProjectCode'];
projectTitle = json['ProjectTitle'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Id'] = this.id;
data['ProjectCode'] = this.projectCode;
data['ProjectTitle'] = this.projectTitle;
return data;
}
}
now how can i search in list and find the ProjectTitle that i need to find it and that method return the id in DTO ?

This is simple, you can use this method to find the String that you need to find. make method like this for everything do you need to search like this :
String find(List<ProjectCode> projectCodeList, String projectTitle) {
return projectCodeList
.firstWhere(
(projectCode) => projectCode.projectTitle.contains(projectTitle))
.id;
}

Related

Flutter: How to update model item inside list

I have a List<Items> items of model Items
class Items {
String name;
String? value;
String price;
}
And i have a Map<String, String> values witch contains values for model. As a key it uses same data as Items.name and value of it contains data.
So my question is. How can i update my items list with added value data from values map? Basically, list of items contains only required field name. Later i get values for it and place it inside map. Now i want to update my list with added value data
This is how you structure the class to accept the Map<String, String> values:
class Item {
String? name;
String? value;
Item({this.name, this.value});
Item.fromJson(Map<String, dynamic> json) {
name = json['name'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['value'] = value;
return data;
}
}
If this is your map:
Map<String, String> values = {"name": "wambua", "value": "Programmer"};
This is how you map the map to the class:
Item.fromJson(values);

How to convert or equalize Query<Map<String, dynamic>> to List

I have BrandList in my Firebase like this;
How can I convert or equalize this Firebase List to List.
I tried this;
var brandsRef = _firestore.collection("vehicles1").where("Brands");
List brandsList = brandsRef;
But I got this error "A value of type 'Query<Map<String, dynamic>>' can't be assigned to a variable of type 'List'."
You need to use the document Id to get the query and then you can get the data which returns a Map.
From that Map, you can supply the key to retrieve the value. In this case, the key is "Brands".
var brandsQuery = await _firestore.collection("vehicles1").doc(document Id).get();
List brandList = brandsQuery.data()["Brands"];
First I would suggest to create a model of your class Brand in addition to the jsonSerialization classics:
class Brands {
Brands({this.brandName});
List<String> brandName;
Map<String, dynamic> toMap() {
return {
'Brands': brandName,
};
}
factory Brands.fromMap(Map<String, dynamic> map) {
return Brands(
brandName: List<String>.from(map['Brands']),
);
}
String toJson() => json.encode(toMap());
factory Brands.fromJson(String source) => Brands.fromMap(json.decode(source));
}
Then you need to add a few steps to the way you retreive elements:
var response = _firestore.collection("vehicles1").where("Brands").get();
final results =
List<Map<String, dynamic>>.from(response.docs.map((e) => e.data()));
Brands brands =
results.map((e) => Brands.fromMap(e)).toList();

How to convert list getting from future method to Map<String, dynamic>

I want to convert the list coming from getPosts method (getting result from the web json and stored in the posts list) to List
Post Class
class Post {
final int userId;
final String id;
final String title;
final String body;
Post(this.userId, this.id, this.title, this.body);
}
Future<List<Post>> getPosts() async {
var data = await http
.get("https://jsonplaceholder.typicode.com/posts");
var jasonData = json.decode(data.body);
List<Post> posts = [];
for (var i in jasonData) {
Post post = Post(i["userId"], i["id"], i["title"], i["body"]);
posts.add(post);
}
return posts;
}
I tried to put the result directly to this method
static List<Map> convertToMap({List myList }) {
List<Map> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}
but it's not working, I see this error
The argument type 'List<Map<dynamic, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.
Change List<Map> by List<Map<String, dynamic>>
static List<Map<String, dynamic>> convertToMap({List myList }) {
List<Map<String, dynamic>> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}

How to convert a dynamic list into list<Class>?

I'm trying to convert a dynamic list into a list of class-model(Products). This is how my method looks like:
public List<Products> ConvertToProducts(List<dynamic> data)
{
var sendModel = new List<Products>();
//Mapping List<dynamic> to List<Products>
sendModel = data.Select(x =>
new Products
{
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data, null).ToString()
}).ToList();
}
I have tried these both ways to get the property values, but it gives me null errors saying these properties doesn't exist or they are null.
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data,
null).ToString()
This is how my Model-class looks like:
public class Products
{
public string ID { get; set; }
public string Name { get; set; }
public string Price { get; set; }
}
Can someone please let me know what I'm missing? thanks in advance.
You're currently trying to get properties from data, which is your list - and you're ignoring x, which is the item in the list. I suspect you want:
var sendModel = data
.Select(x => new Products { Name = x.Name, Price = x.Price })
.ToList();
You may want to call ToString() on the results of the properties, but it's not clear what's in the original data.

How to get distinct records from a list

I have a list of type Myclass
List<Myclass> liSubjectIdDetail = new List<Myclass>();
where Myclass looks like
public class Myclass
{
public Nullable<decimal> SubjectId { get; set; }
public string SubjectName { get; set; }
}
I am adding records into liSubjectIdDetail from a table
foreach (decimal Id in VarCEMSIdDetail)
{
liSubjectIdDetail.AddRange(db.Stt.MyTable.Where(x => x.Id == Id).Select(x => new Myclass { SubjectId = x.SubjectId, SubjectName = x.SubjectName }).ToList());
}
where Id contains a list of certain Ids on the basis of which records I fetch.
Now I want to get only distinct records in this list.
I have tried it with hashtable in place of List
and I also tried
liSubjectIdDetail= liSubjectIdDetail.Distinct().ToList();
but this too, is not working. Please give me a better solution.
Thanks in advance
Try this extension method
public static class IEnumerableExtensions {
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
Usage:
liSubjectIdDetail= liSubjectIdDetail.DistinctBy(s => s.SubjectName).ToList();