Flutter list query - flutter

Im trying to check a list inside list and then show it as ViewList
for example
const Sport = [
{
"Name": "James",
"SportTaq": ["Soccer", "American football"],
},
];
and then check list witch include loud Soccer
print(Sport.where((item) => item["SportTaq"].contains("Soccer")));
but it did not work can you help me with it please

You can do something like this:
void main() {
const Sport = [
{
"Name": "James",
"SportTaq": ["Soccer", "American football"],
},
{
"Name": "Bob",
"SportTaq": ["American football","basketball"],
},
];
print(Sport.where((item) {
List sports = item["SportTaq"];
return sports.contains("Soccer");
}).toList());
}

Related

How to remove duplicate item from list of maps with it's property in Flutter | Dart

I have a list of Maps. The below is the list of maps,
List teachers = [
{
'name':'John',
'subject':'English'
},
{
'name':'Rohan',
'subject':'Hindi'
},
{
'name':'Benny',
'subject':'English'
},
{
'name':'Rose',
'subject':'Tamil'
},
{
'name':'Shine',
'subject':'Kannada'
},
{
'name':'Tintu',
'subject':'English'
}
];
From this I want to keep any of the one english teacher and remove all other teacher with subject english.
The below is the expected result.
List teachers = [
{
'name':'John',
'subject':'English'
},
{
'name':'Rohan',
'subject':'Hindi'
},
{
'name':'Rose',
'subject':'Tamil'
},
{
'name':'Shine',
'subject':'Kannada'
},
];
You can use collection package and try this:
var grouped =
groupBy(teachers, (Map<String, String> value) => value['subject']);
List<Map> result = grouped.entries.map((e) => e.value.first).toList();
print("result =$result");//result =[{name: John, subject: English}, {name: Rohan, subject: Hindi}, {name: Rose, subject: Tamil}, {name: Shine, subject: Kannada}]

how can get dynamic key json in flutter

"
success": true,
"result": {
"values": {
"asdf": [],
"dj": [
{
"id": 18,
"ownerId": "5b0b3932-e262-4ac4-923c-13daf2bd4a3c",
"ownerName": "tester",
"name": "masr",
"description": "she was and firebase have also had to make their decision and make the beg to 8be 8the 8same 6th 7century 8of 8and 6and 88th century ones in flutter take on my favourite ",
"statusId": "PENDING",
"status": null,
"price": 9000.00,
"isPublic": false,
"startDate": "2022-05-26T00:00:00",
"expectedEndDate": "2022-05-27T00:00:00",
"finishDate": null,
"interests": [
{
"id": "my-first-interest",
"isDeleted": false
},
{
"id": "gdg",
"isDeleted": false
},
{
"id": "dj",
"isDeleted": false
}
]
},
]
}
}
the dynamic key is asdf and dj change form user to anoter
i want to get id or ownername .... etc without object can any one help me in this cause
Since you don't know the key name in advance, you will have to iterate over all of them looking for JSON object members that look like they contain ID and owner. Something like this:
import 'dart:convert';
import 'dart:io';
void main() {
final decoded = json.decode(File('json1.json').readAsStringSync());
// values will be a JSON object
final values = decoded['result']['values'] as Map<String, dynamic>;
// values.values will be all of the JSON arrays in that object
// do a whereType just to rule out any other fields in the JSON object
// use expand to merge all lists together
// and wheretype again to double check that we only have JSON objects
// further check that only JSON objects with the right values are selected
// and map these to PODOs
final result = values.values
.whereType<List>()
.expand((e) => e)
.whereType<Map>()
.where((e) => e.containsKey('id') && e.containsKey('ownerId'))
.map<IdAndOwner>((m) => IdAndOwner(m['id'], m['ownerId']))
.toList();
print(result); // prints [Id/OwnerId=18/5b0b3932-e262-4ac4-923c-13daf2bd4a3c]
}
class IdAndOwner {
final int id;
final String ownerId;
IdAndOwner(this.id, this.ownerId);
#override
String toString() => 'Id/OwnerId=$id/$ownerId';
}

Mongoose - Search inside nested array with no limits

My mongodb collection is stores records of groups which can have subgroups, which can further have sub-sub groups and there will not be any limits of nesting of this sub-groups. Is there anyway in mongoose to find a group name that resides in nth level?
My collection structure looks like the following, so suppose if i want to find if "My Group" has a subgroup named "My Group 1001", how am I supposed to find it?
{
"id": "60c18d4ce973fc139f23bf93",
"name": "My Group",
"subgroups": [
{
"id": "70c18d4ce973fc139f23bf93",
"name": "My Group 2",
"subgroups": [
{
"id": "80c18d4ce973fc139f23bf93",
"name": "My Group 3",
"subgroups": [
{
"id": "90c18d4ce973fc139f23bf93",
"name": "My Group 4",
"subgroups": [ ... ],
}
]
}
]
}
]
}
The other solutions that I found on stackoverflow suggested that it can be achieved using the dot notation for eg,
$or: [
{"name": "My Group 1001"},
{"subgroups.name": "My Group 1001"},
{"subgroups.subgroups.name": "My Group 1001"},
...
]
But since in my case the level is not known hence I cannot use the above pattern.
Mongodb is not an ideal tool for recursive operations.
Not recommended, but you can use $function to do the job with javascript:
db.collection.find({
$expr: {
$function: {
body: "function(subgroups, topName) { let recursiveSearch = function(sg){ if(!sg) {return false}; return sg.some(function(subdoc) {return subdoc.name == 'My Group 1001' || recursiveSearch(subdoc.subgroups)})}; return topName == 'My Group 1001' || recursiveSearch(subgroups);}",
args: [
"$subgroups",
"$name"
],
lang: "js"
}
}
})
The function alone formatted for readability:
function(subgroups, topName) {
let recursiveSearch = function (sg) {
if (!sg) { return false };
return sg.some(function (subdoc) {
return subdoc.name == 'My Group 1001' || recursiveSearch(subdoc.subgroups)
})
};
return topName == 'My Group 1001' || recursiveSearch(subgroups);
}
There is no tail recursion so I imagine it may blow up if it exhaust call stack. Didn't test it myself though.
If you have luxury of changing data format, consider adding a top level "names" flat array of all names from the nested documents. It will add some overhead to the application logic to keep it up to date on each update. The search will be as simple as
db.collection.find({"names": "My Group 1001"})
As an additional bonus you will be able to benefit from multikey indexes
Maybe finding keys with values can help you:
const flattenObj = (obj, parent, res = {}) => {
for (let key in obj) {
let propName = parent ? parent + '.' + key : key;
if (typeof obj[key] == 'object') {
flattenObj(obj[key], propName, res);
} else {
res[propName] = obj[key];
}
}
return res;
}
const obj = {
"id": "60c18d4ce973fc139f23bf93",
"name": "My Group",
"subgroups": [
{
"id": "70c18d4ce973fc139f23bf93",
"name": "My Group 2",
"subgroups": [
{
"id": "80c18d4ce973fc139f23bf93",
"name": "My Group 3",
"subgroups": [
{
"id": "90c18d4ce973fc139f23bf93",
"name": "My Group 4"
}
]
}
]
}
]
}
const dotNotation = flattenObj(obj);
// Finding keys from object by a specific value
const key1 = Object.keys(dotNotation).find(key => dotNotation[key] === 'My Group 2');
const key2 = Object.keys(dotNotation).find(key => dotNotation[key] === 'My Group 3');
const key3 = Object.keys(dotNotation).find(key => dotNotation[key] === 'My Group 4');
console.log(`Key of 'My Group 2': ` + key1);
console.log(`Key of 'My Group 3': ` + key2);
console.log(`Key of 'My Group 4': ` + key3);

How to match id with current id in array

How I will check current user id == id and show user like or not in UI
"reference":[
{
"id":"123",
"userid"234"
},
{
"id":"1423",
"userid"25534"
},
{
"id":"15423",
"userid"2335534"
},
]
if this is json response try to convert it in models using https://javiercbk.github.io/json_to_dart/
or here is code that can work for u
var reference = [
{"id": "123", "userid": "234"},
{"id": "1423", "userid": "25534"},
{"id": "15423", "userid": "2335534"},
];
var r = reference.firstWhere((e) => e["id"] == "123");
print(r);
// output
{id: 123, userid: 234}

How json array pages by id dart

how all pages to map title print?
how json select example id=12 to map print title
{
"result": {
"name": "json1",
"pages": [
{
"zones": [
{
"title": "title1"
},
{
"title": "title2"
}
],
"id": 4
},
{
"zones": [
{
"title": "title3"
},
{
"title": "title4"
}
],
"id": 12
}
],
"creatorUserName": "admin",
"id": 2
}
}
List post = json;
children: post
.map( (post) => Container(
child: Center(child: Text(post.title]),)
))
.toList(),
I make a code to parse your json
var data = json.decode(jsonData);
var pagesArray = data["result"]["pages"];
pagesArray.forEach((page) {
var zones = page["zones"];
//Each id have your titles
int id = page["id"];
List<String> titles = new List();
zones.forEach((zone) {
titles.add(zone["title"]);
});
print("Id $id have this titles : ${titles.toString()}");
});