Add json values in to the list of object - flutter

How I can get all the values in this JSON and add all the value in to the list of object in the dart?
"data": [
{
"$id": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
},
],
like this var list = ["2",1017,....]

Assuming you've a JSON file, which you may have parsed like this:
String json = await rootBundle.loadString('file_name.json');
var response = jsonDecode(json);
This is how you can do it:
List<dynamic> jsonData; //similar to var jsonData = [something, something, ...]
//traversing through each value in the key value arrangement of the json
for (var k in response.values) {
jsonData.add(k); //adding each value to the list
}
After the loop ends, jsonData will have all the values of your JSON file.

It's important for you to know that even if you put the keys on a list, they won't necessarily be in order, because of the way maps work.
Assuming your json is a map and not a json string, you could put all of the values on a list like so:
var myList = (jsonObject['data'] as List).fold<List>(
[],
(prev, curr) => [...prev, ...curr.values]
);
if you were talking about a json string:
Map<String, dynamic> jsonObject = jsonDecode(jsonString);

For simplicity, lets assume this json is unparsed in a string.
(1) Assuming the code snippet you added is a string && is valid json you can do as follows :)
import 'dart:convert';
void main() {
var x = json.decode('''
{
"data": [
{
"hello": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
}
]
}
''');
print(x);
List<dynamic> listOfObjects = (x['data'] as Iterable<dynamic>).toList();
/// this is just gonna be a list of all of your object.
print(listOfObjects);
List<dynamic> listOfValues = (x['data'] as Iterable<dynamic>).map((_object) {
return (_object as Map<String, dynamic>).values.toList();
}).toList();
/// this is gonna be a 2d array here,
print(listOfValues);
}
Hope This helped out:)
Also json here comes from import 'dart:convert';

Related

Flutter : How change modify unmodifiable map

I have list like this in provider:
List orders=[]:
void getOrders(){
orders = [
{"id":1,
"order":[
{"id":1,"name":"mike"},
{"id":2,"name":"john"},
{"id":3,"name":"smith"}
]
},
{"id":1,
"order":[
{"id":1,"name":"roz"},
{"id":2,"name":"sam"},
{"id":3,"name":"ruby"}
]
},
];
notifyListeners();
}
in provider when I use this methos to chane indexed order with another:
void changeOrder(orderIndex,item){
orders[orderIndex].update("order",(val)=>item);
notifyListeners();
}
I get this error type '(dynamic) => dynamic' is not a subtype of type '(Object) => Object' of 'update'
and when I use this :
void changeOrder(orderIndex,item){
orders[orderIndex]["order"]=item;
notifyListeners();
}
I get this error Unsupported operation: Cannot modify unmodifiable map
Add More Details
the item in changeOrder method comes from screen contain orders :
var item = List.from(orders[index]);
orders type is List<Map<String, dynamic>>. While reading the item, it will be a map instead of list.
Map item = Map.from(orders[index]);
And you can use both way you;ve tried.
List<Map<String, dynamic>> orders = [];
void getOrders() {
orders = [
{
"id": 1,
"order": [
{"id": 1, "name": "mike"},
{"id": 2, "name": "john"},
{"id": 3, "name": "smith"}
]
},
{
"id": 1,
"order": [
{"id": 1, "name": "roz"},
{"id": 2, "name": "sam"},
{"id": 3, "name": "ruby"}
]
},
];
}
void changeOrder(orderIndex, item) {
orders[orderIndex]["order"] = item;
// orders[orderIndex].update("order", (val) => item);
}
void main(List<String> args) {
getOrders();
print(orders);
Map item = Map.from(orders[1]);
changeOrder(1, item);
print(orders);
}

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';
}

how to store every element of api response list to a List<String> in flutter?

I have to Store Every Element of List to List so how i can do this?
Json Response as below.
{
"responseCode": 200,
"responseMessage": "OK",
"data": null,
"dataList": [
"Technical",
"Field"
],
"excelDataList": null,
"totalRecords": 2,
"pageRecords": 0,
"currentPageNumber": 1,
"totalPages": 0
}
Here i have to store dataList values in list.
You first have to call jsonDecode to convert your String into deserialized data, then you can use the [] operator to access individual keys.
Read more at
import "dart:convert";
const String apiResult = """{
"responseCode": 200,
"responseMessage": "OK",
"data": null,
"dataList": [
"Technical",
"Field"
],
"excelDataList": null,
"totalRecords": 2,
"pageRecords": 0,
"currentPageNumber": 1,
"totalPages": 0
}
""";
void main() {
Map<String, dynamic> des = jsonDecode(apiResult);
List<dynamic> data = des["dataList"];
print(data);
}
which would print
> [Technical, Field]

how to accommodate an input into a list array in flutter

how to accommodate an input into a list array with shared preferences?
I made a code like below
handlesave() async {
SharedPreferences ref = await SharedPreferences.getInstance();
List<String> _arr = [];
var idU = user.user.id;
final dataJ = JobStorageModel(
iduser: idU.toString(),
id: widget.job.id,
job_title: widget.job.job_title,
location: widget.job.location,
);
String json = jsonEncode(dataJ);
print('save -> $json');
ref.setString('bookmark', json);
}
so that it becomes a list array like the following
{
"ID": 1,
"iduser": "1",
"job_title": "Designer",
"location": "monggola"
},
{
"ID": 2,
"iduser": "1",
"job_title": "UX",
"location": "singapore"
}

How to map data if the key is numeric in flutter

I am getting a response as key as numeric. How to map data for the following response
{
"1": [
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
],
"2": [
{
"id": 9,
"name": "ttt1"
},
{
"id": 5,
"name": "ttt3"
}
],
"3": [
{
"id": 4,
"name": "ttg",
"status_id": 1
}
]
}
Here is my model
import 'dart:convert';
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
String homeBannerModelToJson(Map<String, List<HomeBannerModel>> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, List<dynamic>.from(v.map((x) => x.toJson())))));
class HomeBannerModel {
int id;
String name;
HomeBannerModel({this.id, this.name});
HomeBannerModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
name= json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
I need to take the value in UI as
var data1 = data['1'];
var data2= data['2'];
var data3= data['3'];
but I am getting errors. help how to get the data of each key in each of the variable
but while mapping I am getting errors I have added part of my code in UI
_message:"type 'Map<String, dynamic>' is not a subtype of type 'List'"
The following method will convert your json string to a valid map object so that you can get your data the way you wanted.
Map<String, List<HomeBannerModel>> homeBannerModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, List<HomeBannerModel>>(k, List<HomeBannerModel>.from(v.map((x) => HomeBannerModel.fromJson(x)))));
to access data
final data = homeBannerModelFromJson(your_json_string);
print(data['1'][0].name); // test 1
You current json structure is Map<String, List<Map<String, dynamic>>>
You can try something like
var json = {...};
json.forEach((key, list) {
list.forEach((homeBannerModelMap) {
HomeBannerModel hBM = HomeBannerModel.fromJson(homeBannerModelMap);
});
});
You getting the error because your data is the type of Map, not the List.
So you can do something like this:
// [data] is result banners
List data = [];
// [result] is your object variable {"1": [{"id": 1, "name": "Welcome!"}]} etc
// So .forEach method is used for iterating through your json object
result.forEach((k, v){
// in which iteration I will map every instance to List of [HomeBannerModel]
var value = v.map((banner) => HomeBannerModel.fromJson(banner)).toList();
//in result I will add the result to our [banners] List
data.add(value);
});
But in this case, you should do:
data1 = data[1] // use int as the key, result will be List of BannerModels [Instance of 'HomeBannerModel', Instance of 'HomeBannerModel']
instead of:
var data1 = data['1']; //use string as the key
Please try the following code with just one model 'HomeBannerModel'.
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final Map datas = {};
json.forEach((key, value) {
datas.addAll(
{"$key": value.map((ele) => HomeBannerModel.fromMap(ele)).toList()});
});
print(datas["1"]);
print(datas["2"]);
print(datas["3"]);
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
You may also try with two models (1) Data and (2) HomeBannerModel. Please see the following code :
main() {
final Map<String, dynamic> json = {
"1": [
{"id": 6, "name": "test 1"},
{"id": 8, "name": "test 2"},
{"id": 7, "name": "test 3"}
],
"2": [
{"id": 9, "name": "ttt1"},
{"id": 5, "name": "ttt3"}
],
"3": [
{"id": 4, "name": "ttg", "status_id": 1}
]
};
final List<Data> data = [];
json.forEach((key, value) {
data.add(Data.fromMap({"id": key, "details": value}));
});
print(data.firstWhere((e) => e.dataID == '1').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '2').homeBannerModel);
print(data.firstWhere((e) => e.dataID == '3').homeBannerModel);
}
class Data {
final String dataID;
final List<HomeBannerModel> homeBannerModel;
Data({
this.dataID,
this.homeBannerModel,
});
factory Data.fromMap(Map<String, dynamic> map) {
if (map == null) return null;
return Data(
dataID: map["id"],
homeBannerModel: (map["details"]
.map<HomeBannerModel>((ele) => HomeBannerModel.fromMap(ele))
.toList() as List<HomeBannerModel>));
}
#override
String toString() => 'Data(id: $dataID, details: $homeBannerModel)';
}
class HomeBannerModel {
final int id;
final String name;
final int status_id;
HomeBannerModel({
this.id,
this.name,
this.status_id,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'status_id': status_id,
};
}
factory HomeBannerModel.fromMap(map) {
if (map == null) return null;
return HomeBannerModel(
id: map['id'],
name: map['name'],
status_id: map['status_id'],
);
}
#override
String toString() => 'Details(id: $id, name: $name, status_id: $status_id)';
}
From what I’m seeing in the sample response you shared , the kets are all string as should be... "1" is also String FYI.
Coming to the error you're getting its because you are probably using the var data1,data2,data3 as a map which it isn't.
var data1 = data['1'];
if you print this var you will get :
[
{
"id": 6,
"name": "test 1"
},
{
"id": 8,
"name": "test 2"
},
{
"id": 7,
"name": "test 3"
}
]
If you want to access the submap with id of 6 and name Test 1 do the following:
print(data1[0]);
to display name:
print(data1[0]["name"]);