How do I join Keys and Values. Flutter/Dart - json

This is my code right now :
List<Map<String, dynamic>> incidentList = [
for (final json in listNode.map((x) => x.toJson()))
{
'Code': json['field'][0]['field_value'],
'Description': json['field'][1]['field_value'],
'Organisation Unit': json['field'][2]['field_value'],
'Date Reported': json['field'][3]['field_value'],
'Status': json['field'][4]['field_value'],
'RunHyperlink' : json['run_hyperlink']
}
];
final List<String> values = [];
for(final item in incidentList){
values.add(item.keys.map((e) => e.toString()).join("\n"));
values.add(item.values.map((e) => e.toString()).join("\n"));
}
await WriteCache.setListString(key: 'cache4', value: values);
How do I combine the keys and value so that my list is in the format of "key : value" instead of just value

You can run a nested loop
for(final item in incidentList){
String groupedElement = "";
for(var innerItem in item.entries)
{
groupedElement += "${innerItem.key}:${innerItem.value},";
}
value.add(groupedElement);
}

You can Not shure what format you want, but is sound like JSON. So if you want JSON
You can just replace:
await WriteCache.setListString(key: 'cache4', value: json.encode(incidentList));
Don't forget to import dart:convert:
import 'dart:convert';
And remove:
final List<String> values = [];
for(final item in incidentList){
values.add(item.keys.map((e) => e.toString()).join("\n"));
values.add(item.values.map((e) => e.toString()).join("\n"));
}
ATTENTION, this will return a String, not a list of String
For retrieveing a Map<String, dynamic> from your save data, just do:
final jsonData = json.decode(savedJsonStr);

Related

Getting this error when printing formatted list. Flutter/Dart

This is my code to write cache :
async {
var newMessage = await (ReadCache.getString(key: 'cache1'));
var response = await http.get(
Uri.parse(
'http://192.168.1.4:8080/HongLeong/MENU_REQUEST.do?_dc=1658076505340&reset_context=1&table_id=25510&id_MenuAction=3&path=%3Cp%20class%3D%22x-window-header-path%22%3ELoss%20Event%3C%2Fp%3E&ViewType=MENU_REQUEST&gui_open_popup=1&id_Window=17&activeWindowId=mw_17&noOrigUserDate=true&LocalDate=20220718&LocalTime=00482500&TimeZone=Asia%2FShanghai&UserDate=0&UserTime=0&server_name=OPRISK_DATACOLLECTOR&key_id_list=&cell_context_id=0&id_Desktop=100252&operation_key=1000184&operation_sub_num=-1&is_json=1&is_popup=0&is_search_window=0&ccsfw_conf_by_user=0&is_batch=0&previousToken=1658069547560&historyToken=1658076505339&historyUrl=1'),
headers: {HttpHeaders.cookieHeader: newMessage},
);
LossEventResponseModel lossEventResponseModel =
LossEventResponseModel.fromJson(jsonDecode(response.body));
final listNode = lossEventResponseModel.response.genericListAnswer.listNode;
List<Map<String, dynamic>> incidentList = [
for (final json in listNode.map((x) => x.toJson()))
{
'Code': json['field'][0]['field_value'],
'Description': json['field'][1]['field_value'],
'Organisation Unit': json['field'][2]['field_value'],
'Date Reported': json['field'][3]['field_value'],
'Status': json['field'][4]['field_value'],
}
];
final incidentListJson = jsonEncode(incidentList);
await WriteCache.setString(key: 'listcache', value: incidentListJson);
and this is my code to read cache and format the list :
getList() async {
final incidentListJson = await ReadCache.getString(key: 'listcache');
final List incidentList = jsonDecode(incidentListJson);
String formatIncidentList(List<Map<String, dynamic>> list) {
return list.map(
(incident) => incident.entries.map(
(entry) => "${entry.key}: ${entry.value}"
),
).join("\n");
}
print(formatIncidentList(incidentList));
}
this is the error that I am getting :
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'
any fixes to my code?
I am trying to format and print my list as :
Code: LE-0000000002,
Description: test_01,
Organisation Unit: 01_01_04_01_SA - Shah Alam,
Date Reported: 18/09/2020,
the reason why I want to have this format is so that I will able to access the keys.
and also I want to display it on screen with the keys instead of just the values itself.

flutter foreach loop on json response from API

I have converted my JSON response in the below model:
VehicleList vehicleListFromJson(String str) =>
VehicleList.fromJson(json.decode(str));
String vehicleListToJson(VehicleList data) => json.encode(data.toJson());
class VehicleList {
VehicleList({
this.vehicles,
});
List<Vehicle> vehicles;
factory VehicleList.fromJson(Map<String, dynamic> json) => VehicleList(
vehicles: List<Vehicle>.from(
json["vehicles"].map((x) => Vehicle.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"vehicles": List<dynamic>.from(vehicles.map((x) => x.toJson())),
};
}
class Vehicle {
Vehicle({
this.vehid,
this.vehname,
this.vehdescrip,
this.vehbodyopen,
this.vehbodyopenimg,
this.vehbodyclose,
this.vehbodycloseimg,
});
String vehid;
String vehname;
String vehdescrip;
String vehbodyopen;
String vehbodyopenimg;
String vehbodyclose;
String vehbodycloseimg;
factory Vehicle.fromJson(Map<String, dynamic> json) => Vehicle(
vehid: json["vehid"],
vehname: json["vehname"],
vehdescrip: json["vehdescrip"],
vehbodyopen: json["vehbodyopen"],
vehbodyopenimg: json["vehbodyopenimg"],
vehbodyclose: json["vehbodyclose"],
vehbodycloseimg: json["vehbodycloseimg"],
);
Map<String, dynamic> toJson() => {
"vehid": vehid,
"vehname": vehname,
"vehdescrip": vehdescrip,
"vehbodyopen": vehbodyopen,
"vehbodyopenimg": vehbodyopenimg,
"vehbodyclose": vehbodyclose,
"vehbodycloseimg": vehbodycloseimg,
};
}
I make the API call like this:
Future<VehicleList> getVehicles() async {
var client = http.Client();
var vehicleModel = null;
try {
var response = await client.get(Uri.parse(Strings.getVehiclesUrl));
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
vehicleModel = VehicleList.fromJson(jsonMap);
}
} catch (Exception) {
return vehicleModel;
}
return vehicleModel;
}
Now I need to implement a for each loop on this to check if the value for key "vehbodyopen" is "Y" or "N" and create seperate arrays or objects for them and then display them in a ListViewBuilder widget.
Im new to flutter. Im from javascript background. I solved the problem in javascript by executing for each loop in the json response and stored them in two different arrays. Im looking for the same solution in flutter and dart if possible.
for (int i = 0; i < vehicleModel.length; i++) {
if(vehicleModel[i].vehbodyopen == "Y"){
//do stuff
}else{
//do another stuff
}
}
you might try this
I found a possible solution I had to loop over the vehicles List inside the vehicleModel.
List vehList = vehicleModel.vehicles;
List openVehList = [];
List closedVehList = [];
for (var veh in vehList) {
print('executing foreach');
if (veh.vehbodyopen == "Y") {
openVehList.add(veh);
} else {
closedVehList.add(veh);
}
}

How to convert data from json to List<Object> in Flutter

I need to obtain a list of Articles(a custom object) from a realtime database in Firebase. I first decode my data from a json data type. Then I try to convert it into a list using this line of code:
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList();
However, this gives a syntax error of "The argument type 'Article Function(Map<dynamic,dynamic>)' can't be assigned to the parameter type 'dynamic Function(Article)'." I have included the code I use to fetch an Article(the custom object) as well as the factory method for the class.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse)
.map((Map model) => Article.fromJson(model))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
\\Factory Method
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
author: json['author'],
date: json['date'],
imageUrl: json['imageUrl'],
modalities: json['modalities'],
);
}
I make an example with something like a json response.
void main() {
//this is an example like a json response
List<Map<String, dynamic>> articleResponse = [
{
"id":"1",
"name":"test1"
},
{
"id":"2",
"name":"test2"
}
];
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList();
print('${articles.length} articles in the list!! use to render de ui list');
}
class Article{
String id;
String name;
Article({this.id,this.name});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
name: json['name'],
);
}
}
basically you need to change your method to get articles with this.
//Method to get articles
Future<List<Article>> fetchArticles() async {
final response = await http.get(
"https://some-server.firebaseio.com/some-url.json");
final articleResponse = json.decode(response.body);
List<Article> articles = List<Article>.from(articleResponse.map((Map art)=>Article.fromJson(art)))
.toList(); // Now we're looping over the response entries (maps of article info) to create Article instances
return articles;
}
you can use JsonToDart
this is create a class for parse your complex json data
paste json and get class of model
you can overrride toString in your model like:
#override
String toString() {
return '{
id: $id,
title: $title,
author: $author,
date: $date,
imageUrl: $imageUrl,
modalities: $modalities
}';
}
and override toMap :
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'title': title,
'author': author,
'date': date,
'imageUrl': imageUrl,
'modalities': modalities,
};
}
and you can use serialization that. this can help you

How to pass a list of json to body of http request (post) in Flutter?

I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.
incrementListPaymentSlipes(PaymentSlipes objPayment) async {
objPayment.name = "Douglas";
objPayment.personalId = "00000000000";
Map<String, dynamic> json = objPayment.toJson();
listPaymentSlipes.add(jsonEncode(json));
}
var response = await http.post(url, body: {
"payment_slips": listPaymentSlipes,
}
example of correct body:
"payment_slips": [
{
"personal_id": "01888728680",
"name": "Fulano da Silva"
}
]
{"error":"'{{personal_id: 00000000000, name: Douglas}}' é invalido como 'payment_slips'","code":"payment_slips_invalid"}```
You can do it in a very simple way. Create payment.dart file and copy paste the below code classes.
class PaymentList {
PaymentList(this.payments);
List<Payment> payments;
Map<String, dynamic> toJson() => <String, dynamic>{
'payment_slips': payments,
};
}
class Payment {
Payment({this.name, this.personalId});
String name;
String personalId;
Map<String, dynamic> toJson() => <String, dynamic>{
'personal_id': personalId,
'name': name,
};
}
Now you can covert it to the required json format using below code. For example I am creating a dummy list:
final PaymentList paymentList =
PaymentList(List<Payment>.generate(2, (int index) {
return Payment(name: 'Person $index', personalId: '$index');
}));
final String requestBody = json.encoder.convert(paymentList);
The requestBody variable will have the json string as follows:
{"payment_slips": [
{
"personal_id": "0",
"name": "Person 0"
},
{
"personal_id": "1",
"name": "Person 1"
}
]}
Now you can call the api:
var response = await http.post(url, body: requestBody}
Note: Please import the below package, which will be required to access json:
import 'dart:convert';
So it looks like you are not getting the JSON you expect. I have put together some code to show you how to get the body you want.
Link to run in DartPad https://dartpad.dartlang.org/3fde03078e56efe13d31482dea8e5eef
class PaymentSlipes {
String name;
String personaId;
ObjPayment({this.name, this.personaId});
//You create this to convert your object to JSON
Map<String, dynamic> toJson() => {'name': name, 'personaId': personaId};
}
// This method is needed to convert the list of ObjPayment into an Json Array
List encondeToJson(List<PaymentSlipes> list) {
List jsonList = List();
list.map((item) => jsonList.add(item.toJson())).toList();
return jsonList;
}
// This is an example and this code will run in DartPad link above
void main() {
PaymentSlipes objPayment = PaymentSlipes(name: "Douglas", personaId: "123425465");
PaymentSlipes objPayment2 = PaymentSlipes(name: "Dave", personaId: "123425465;
PaymentSlipes objPayment3 = PaymentSlipes(name: "Mike", personaId: "123425465");
var list = [objPayment, objPayment2, objPayment3];
// This is the mapping of the list under the key payment_slips as per your example and the body i would pass to the POST
var finalJson = {"payment_slips": encondeToJson(list)};
print(finalJson);
}

how to encode and send to server json list by dio

i have class that generate json list this is my class
class Tool{
String Name;
bool selection;
String englishName;
Map<String, dynamic> toJson() {
return {
'Name': persianName,
'selection': selection,
'englishName': englishName
};
}
}
List<Tool> tools=new List();
setTool(tool){
tools.add(tool);
}
toolsLength(){
return tools.length;
}
updatetool(index,goal){
tools[index]=goal;
}
getTool(index){
return tools[index];
}
getAllTools(){
return tools;
}
and this is dio library that send my list to server every thing is ok but my array is into Double quotation in other word my list is string how to pick up double quotation around of json array . if assume my json array hase
"tools": [{"name":"jack","selection" : false " ,"englishName":"jock"}]
result is :
"tools": "[{"name":"jack","selection" : false " ,"englishName":"jock"}]"
how fix it this is my class for send
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
response = await
dio.post("${strings.baseurl}/analyze/$username/$teacher", data:
formData);
print("----------> response is :"+response.toString());
Edit
You can paste the following code to DarPad https://dartpad.dartlang.org/
The following demo shows transform your Json String to Tool List and Convert your Tool List to JSON string again and use map.toJson
var yourresult = toolList.map((e) => e.toJson()).toList();
you can see result in picture
use FormData.from need to know what your api's correct JSON String.
Please test your web api with Postman, if you success, you will know correct format string.
In your code
FormData formData = new FormData.from({
"tools":jsonEncode(getAllTools().map((e) => e.toJson()).toList()) ,
});
if you are trying to to do
FormData formData = new FormData.from({
"tools":'[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]' ,
});
so you can get your json string first and put it in FormData
var toolsJson = toolsToJson(toolList);
FormData formData = new FormData.from({
"tools":toolsJson ,
});
full demo code, you can paste to DartPad to see string and list conversion
import 'dart:async';
import 'dart:io';
import 'dart:core';
import 'dart:convert';
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}
main() {
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
var toolsStr = '[{"name":"jack","selection" : false ,"englishName":"jock"}, {"name":"jack2","selection" : false ,"englishName":"jock2"}]';
var toolList = toolsFromJson(toolsStr);
var toolsJson = toolsToJson(toolList);
print("toolsJson ${toolsJson} \n");
var toolsmap = toolList[0].toJson();
print("toolsmap ${toolsmap.toString()}\n");
var yourresult = toolList.map((e) => e.toJson()).toList();
print(yourresult.toString());
}
you can paste your JSON string to https://app.quicktype.io/, you will get correct Dart class
correct JSON string of your sample. in false keyword followed by a " cause JSON string parsing error.
[
{"name":"jack",
"selection" : false ,
"englishName":"jock"
}
]
code to parse JSON string and encode to List, use toJson will convert to JSON string you need to send with dio form
// To parse this JSON data, do
//
// final tools = toolsFromJson(jsonString);
import 'dart:convert';
List<Tools> toolsFromJson(String str) => new List<Tools>.from(json.decode(str).map((x) => Tools.fromJson(x)));
String toolsToJson(List<Tools> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
class Tools {
String name;
bool selection;
String englishName;
Tools({
this.name,
this.selection,
this.englishName,
});
factory Tools.fromJson(Map<String, dynamic> json) => new Tools(
name: json["name"],
selection: json["selection"],
englishName: json["englishName"],
);
Map<String, dynamic> toJson() => {
"name": name,
"selection": selection,
"englishName": englishName,
};
}