How to insert a List<Class> into a Map<String, dynamic> in dart? - flutter

My problem is that I have a list of the following class:
class ingreso_Egreso_Dummy{
int tipo;
String monto;
String moneda;
String descripcion;
}
then I want to insert the data into a Map which later will be converted into a json and which I am creating like this:
Map<String, dynamic> body;
body = {
"Cod_Prom": "01",
"CodCli": "003526",
"Status": _index_status.toString(),
"NOMBRE": controller_nombre.text,
"APELLIDOS": controller_apellidos.text,
"solicitud":[{
"Cod_Solicit": 1.toString(),
"Fecha": DateFormat("y-d-M").format(DateTime.now()),
"Status_Solicit": "E",}],
"prestamo":[{
"Monto_Solicit":controller_monto_solic.text,
"Plazo":controller_plazo.text,
"Cod_TipoPlazo":_index_tipoplazo.toString(),
"Nombre_Resp":controller_nombreresp.text,
"Telf_Resp":controller_telefonoresp.text,}],
"Ingresos": [{
//// here I want create a loop that returns a map for each value
//// of the list like this:
//// "Descripcion": Listaingresos[i].descripcion;
})
}]
};
Every help is very appreciated, thank you.

// camelCaseStyle is a standard for class names for Dart
class IngresoEgresoDummy {
int tipo;
String monto;
String moneda;
String descripcion;
Map<String, dynamic> toJson(){
return {
'tipo': tipo,
'monto': monto,
'monedo': moneda,
'descripcion': descripcion
};
}
}
and after that
List<IngresoEgresoDummy> listaingresos= List();
Map<String, dynamic> body = {
// all your params
"Ingresos": listaingresos.map((ingreso) => ingreso.toJson()).toList()
// all your params
};

Related

Flutter when serializing list of objects with jsonEncode the final string is getting cutt off

I have difficulty to convert a long list to JSON string. This is my main model which I want to convert to JSON string
class ActivityBookingRequest {
int adminId;
List<ActivityBookingDetail> activityBookingList;
Map toJson() {
List<Map> activityBookingListMap = this.activityBookingList != null
? this.activityBookingList.map((i) => i.toJson()).toList()
: null;
return {
'adminId': adminId,
'activityBookList': activityBookingListMap,
};
}
}
This is my sub-model which is the list I am trying to serialize!
class ActivityBookingDetail {
int bookingId;
int resourceId;
int sourceId;
String sourceName;
int productId;
String pickupDate;
String cutOffDate;
int adultNumber;
int childrenNumber;
ActivityBookingDetail(
this.bookingId,
this.resourceId,
this.sourceId,
this.sourceName,
this.productId,
this.pickupDate,
this.cutOffDate,
this.adultNumber,
this.childrenNumber,
);
Map<String, dynamic> toJson() {
return {
'ssId': bookingId,
'ssResourceId': resourceId,
'sourceId': sourceId,
'sourceName': sourceName,
'productId': productId,
'pickupDate': pickupDate,
'cutOffDate': cutOffDate,
'noAdult': adultNumber,
'noChild': childrenNumber,
};
}
}
When I convert this to a JSON string if the list is long, the final JSON string is getting cut off!
{"adminId":213,{"ssId":4,"ssResourceId":4,"sourceId":1,"sourceName":"TRES","productId":3,"pickupDate":"2022-09-08T18:30:00","cutOffDate":"2022-09-08T18:30:00","noAdult":1,"noChi

Flutter Dart The getter '' was called on null

I'm sending response.body and country name with slash as like germany/ as parameter and converting it to Germany in parser and returning. But if i use parameter, i'm getting error of the getter 'vacTotal' was called on null. If i write "Germany"to countryDataVac["Germany"] the code works correctly. Is it the problem on {"Global": new CountryDataVac()}? The default value is "Global".
main.dart:
Map<String, CountryDataVac> countryDataVac = {"Global": new CountryDataVac()};
static Map<String, CountryDataVac> getCountryDataVac(String body, var countryname) {
Map<String, CountryDataVac> countryDataVac = {};
responseVac1Day = await http.get("https://disease.sh/v3/covid-19/vaccine/coverage?fullData=true&lastdays=1"); //vaccine number info
countryDataVac = Parser.getCountryDataVac(responseVac1Day.body, "germany/"); //vaccine number info
Parser.dart:
var usera = CountryDataVac.fromJson(jsonDecode(result));
countryDataVac[capitalize(countryname).replaceAll("/", "")] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //gives 'germany/' as 'Germany' but getting error if i get the countryname by parameter
countryDataVac["Germany"] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //works
}
CountryDataVac.dart (created by json to dart)
import 'dart:convert';
List<CountryDataVac> countryDataVacFromJson(String str) => List<CountryDataVac>.from(json.decode(str).map((x) => CountryDataVac.fromJson(x)));
String countryDataVacToJson(List<CountryDataVac> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryDataVac {
CountryDataVac({
this.vacTotal = 0,
this.vacDaily = 0,
this.vactotalPerHundred = 0,
this.vacdailyPerMillion = 0,
this.date = "",
});
int vacTotal = 0;
int vacDaily = 0;
int vactotalPerHundred = 0;
int vacdailyPerMillion = 0;
String date = "";
factory CountryDataVac.fromJson(Map<String, dynamic> json) => CountryDataVac(
vacTotal: json["total"],
vacDaily: json["daily"],
vactotalPerHundred: json["totalPerHundred"],
vacdailyPerMillion: json["dailyPerMillion"],
date: json["date"],
);
Map<String, dynamic> toJson() => {
"total": vacTotal,
"daily": vacDaily,
"totalPerHundred": vactotalPerHundred,
"dailyPerMillion": vacdailyPerMillion,
"date": date,
};
}
use
countryname.replaceFirst(countryname[0], countryname[0].toUpperCase()).replaceAll("/", "");
instead of
capitalize(countryname).replaceAll("/", "")
i think there is something wrong with your capitalize method

Mapping CSV data in flutter

Auto-complete search list
How to parse csv data instead of json data as mentioned in this article. I am new to csv and I have trouble mappping csv data to a model list. I need to pass the csv list to autocomplete field in another package plz help me in mapping it to the model.
class Players {
String keyword;
int id;
String autocompleteterm;
String country;
Players({
this.keyword,
this.id,
this.autocompleteterm,
this.country
});
factory Players.fromJson(Map<String, dynamic> parsedJson) {
return Players(
keyword: parsedJson['keyword'] as String,
id: parsedJson['id'],
autocompleteterm: parsedJson['autocompleteTerm'] as String,
country: parsedJson['country'] as String
);
}
}
class PlayersViewModel {
static List<Players> players;
static Future loadPlayers() async {
try {
players = new List<Players>();
String jsonString = await rootBundle.loadString('assets/players.json');
Map parsedJson = json.decode(jsonString);
var categoryJson = parsedJson['players'] as List;
for (int i = 0; i < categoryJson.length; i++) {
players.add(new Players.fromJson(categoryJson[i]));
}
} catch (e) {
print(e);
}
}

How to Adding New Data into JSON Dart?

I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}

Parse a JSON array with multiple object types

Let's say I have a JSON array like this:
"videos": [
{
"id": 25182,
"game": 115653,
"name": "Trailer",
"video_id": "BdA22Lh6Rwk"
},
27749,
{
"id": 29188,
"game": 115653,
"name": "A New Team and New Rivals in Pokémon Sword and Pokémon Shield! ⚔️🛡️",
"video_id": "ZBiTpi8ecTE"
}
]
Normally if the item's JSON format in videos is like videos[0] or videos[2] then I was able to parse it to Video like this:
json['videos']?.cast<Map<String, dynamic>>()?.map<Video>((f) {
return Video.fromJson(f);
})?.toList();
My Video class:
class Video {
int id;
int game;
String name;
String videoId;
Video({this.id, this.game, this.name, this.videoId});
Video.fromJson(Map<String, dynamic> json) {
id = json['id'];
game = json['game'];
name = json['name'];
videoId = json['video_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['game'] = this.game;
data['name'] = this.name;
data['video_id'] = this.videoId;
return data;
}
}
But if something with the different structure like videos[1] is within the array then I ended up with Exception. How can I parse videos[1] to Video with video[1] as Video's id?
You have to know the different formats and figure out which one each entry is.
You can do that by checking the type of the entry: Is it an integer or a map?
Example:
List<Video> videosFromJson(List<Object> videoJson) {
var result = <Video>[];
for (int i = 0; i < videoJson.length; i++) {
var entry = videoJson[i];
if (entry is Map<String, dynamic>) {
result.add(Video.fromJson(entry));
} else if (entry is int) {
result.add(Video()..id = entry);
} else {
throw FormatException("Not a recognized video format", entry, i);
}
}
return result;
}