I am trying to map a json list in my application using JSON Serializable. But I am not able to map it.
Following is the response from the API:
{
"code": 200,
"message": "Countries Lists",
"count": 250,
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 2,
"name": "Aland Islands"
},
{
"id": 3,
"name": "Albania"
},
{
"id": 4,
"name": "Algeria"
},
{
"id": 5,
"name": "American Samoa"
},
{
"id": 6,
"name": "Andorra"
},
{
"id": 7,
"name": "Angola"
},
{
"id": 8,
"name": "Anguilla"
},
{
"id": 9,
"name": "Antarctica"
},
{
"id": 10,
"name": "Antigua And Barbuda"
},
{
"id": 11,
"name": "Argentina"
},
{
"id": 12,
"name": "Armenia"
},
{
"id": 13,
"name": "Aruba"
},
{
"id": 14,
"name": "Australia"
},
{
"id": 15,
"name": "Austria"
},
{
"id": 16,
"name": "Azerbaijan"
},
{
"id": 17,
"name": "Bahamas The"
},
{
"id": 18,
"name": "Bahrain"
},
{
"id": 19,
"name": "Bangladesh"
},
{
"id": 20,
"name": "Barbados"
}
]
}
Following is my response file:
#JsonSerializable()
class BaseResponse {
#JsonKey(name: "code")
int? status;
#JsonKey(name: "message")
String? message;
}
#JsonSerializable(explicitToJson: true)
class AllCountryResponse extends BaseResponse {
#JsonKey(name: "data")
List<CountryResponse> data;
AllCountryResponse(this.data);
//from JSON
factory AllCountryResponse.fromJson(Map<String, dynamic> json) =>
_$AllCountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$AllCountryResponseToJson(this);
}
#JsonSerializable()
class CountryResponse {
#JsonKey(name: "id")
String? id;
#JsonKey(name: "name")
String? name;
CountryResponse(this.id, this.name);
//from JSON
factory CountryResponse.fromJson(Map<String, dynamic> json) =>
_$CountryResponseFromJson(json);
//to JSON
Map<String, dynamic> toJson() => _$CountryResponseToJson(this);
}
I am able to generate the responses.g dart file.
Following is my mapper class file:
class Countries {
String id,name;
Countries(this.id,this.name);
}
class AllCountries{
List<Countries> countries;
AllCountries(this.countries);
}
extension CountryResponseMapper on CountryResponse? {
Countries toDomain() {
return Countries(
this?.id.orEmpty() ?? EMPTY, this?.name.orEmpty() ?? EMPTY);
}
}
extension AllCountriesResponseMapper on AllCountryResponse? {
AllCountries toDomain() {
return AllCountries(this?.data.map((e) => e.toDomain()).toList() ?? []);
}
}
Once I run my api I do get 200 status while using my bio, but after that it shows me the default error I have set, i.e. "Something went wrong". Which means there is an issue in mapping the response.
Can someone help me with mapping this list please?
This code should work.
This code is generated by a very small and simple script (which was written in a few minutes).
class Response {
Response(
{required this.code,
required this.message,
required this.count,
required this.data});
factory Response.fromJson(Map json) {
return Response(
code: json['code'] as int?,
message: json['message'] as String?,
count: json['count'] as int?,
data: json['data'] == null
? []
: (json['data'] as List).map((e) => Data.fromJson(e as Map)).toList(),
);
}
final int? code;
final String? message;
final int? count;
final List<Data> data;
static List<Response> fromJsonList(List json) {
return json.map((e) => Response.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'code': code,
'message': message,
'count': count,
'data': data.map((e) => e.toJson()).toList(),
};
}
static List<Map<String, dynamic>> toJsonList(List<Response> list) {
return list.map((e) => e.toJson()).toList();
}
}
class Data {
Data({required this.id, required this.name});
factory Data.fromJson(Map json) {
return Data(
id: json['id'] == null ? 0 : json['id'] as int,
name: json['name'] == null ? '' : json['name'] as String,
);
}
final int id;
final String name;
static List<Data> fromJsonList(List json) {
return json.map((e) => Data.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
};
}
static List<Map<String, dynamic>> toJsonList(List<Data> list) {
return list.map((e) => e.toJson()).toList();
}
}
Code generation script:
import 'dart:io';
import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';
void main() {
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);
final values = {
'classes': classesCode,
};
var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}
const _classes = r'''
Response:
fields:
code: int?
message: String?
count: int?
data: List<Data>
Data:
fields:
id: int
name: String
''';
const _template = r'''
{{classes}}
''';
Related
I've been trying to get a column from a array into a list, I'm can't seem to figure how to do it, and I couldn't find a solution online. Most of the array i find only aren't nested.
{
"status": true,
"data": {
"1": [
{
"id": "1",
"name": "500MB [SME]",
"price": "220",
"telco_price": "0"
},
{
"id": "2",
"name": "1GB [SME]",
"price": "410",
"telco_price": "0"
},
{
"id": "3",
"name": "2GB [SME]",
"price": "800",
"telco_price": "0"
},
],
"2": [
{
"id": "AIR1000",
"name": "1.5GB ",
"price": "920",
"telco_price": "920"
},
{
"id": "AIR2000",
"name": "4.5GB",
"price": "1840",
"telco_price": "1840"
},
{
"id": "AIR2500",
"name": "6GB",
"price": "2300",
"telco_price": "2300"
}
],
"3": [
{
"id": "9MOB500",
"name": "500MB",
"price": "400",
"telco_price": "400"
},
{
"id": "9MOB1000",
"name": "1.5GB",
"price": "850",
"telco_price": "850"
},
{
"id": "9MOB2000",
"name": "2GB",
"price": "1020",
"telco_price": "1020"
},
]
}
}
firstly, i want to get all names into a list variable which i can then populate easily on one of my page...
i want it into var nameList = []; where its' stated "1" then the next into another variable like that
Do on fetch like
import 'package:http/http.dart' as http;
....
List<DataClass> nameList = [];
fetch() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
MyResponse myResponse = MyResponse.fromJson(data);
final values = myResponse.data?.values;
if (values != null) {
for (final v in values) {
if(v!=null) nameList.addAll(v.toList());
}
}
}
}
Try this model class
import 'dart:convert';
class MyResponse {
final bool? status;
final Map<String, List<DataClass>?>? data;
MyResponse({
this.status,
required this.data,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if(status != null){
result.addAll({'status': status});
}
if(data != null){
result.addAll({'data': data});
}
return result;
}
factory MyResponse.fromMap(Map<String, dynamic> map) {
return MyResponse(
status: map['status'],
data: Map<String, List<DataClass>?>.from(map['data']),
);
}
String toJson() => json.encode(toMap());
factory MyResponse.fromJson(String source) => MyResponse.fromMap(json.decode(source));
}
class DataClass {
final String? id;
final String? name;
final String? price;
final String? telco_price;
DataClass({
this.id,
this.name,
this.price,
this.telco_price,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (id != null) {
result.addAll({'id': id});
}
if (name != null) {
result.addAll({'name': name});
}
if (price != null) {
result.addAll({'price': price});
}
if (telco_price != null) {
result.addAll({'telco_price': telco_price});
}
return result;
}
factory DataClass.fromMap(Map<String, dynamic> map) {
return DataClass(
id: map['id'],
name: map['name'],
price: map['price'],
telco_price: map['telco_price'],
);
}
String toJson() => json.encode(toMap());
factory DataClass.fromJson(String source) =>
DataClass.fromMap(json.decode(source));
}
hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend
"meta": {
"code": 200,
"status": "success",
"message": "Data list transaksi berhasil diambil"
},
"data": {
"current_page": 1,
"data": [
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1,
}
}
]
}
],
}
}
response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'
for better understanding my question ill provide full model, provider and my services
this is my service getOrderList() function that i call in the futureBuilder
var url = '$baseUrl/transaction';
var headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ${userModel.token}'
};
var response = await http.get(Uri.parse(url), headers: headers);
// print(response.body);
// print('berhasil get kategori');
if (response.statusCode == 200) {
List data = json.decode(response.body)['data']['data'];
List<TransactionModel> transaction = [];
for (var item in data) {
transaction.add(TransactionModel.fromJson(item));
}
// print(transaction);
return transaction;
} else {
throw Exception('Gagal get Categori');
}
}
and this is my model code
class TransactionModel {
int id;
int users_id;
String invoice;
int seat_number;
double total_price;
String payment_method;
String status;
List items;
// List menu;
TransactionModel({
this.id,
this.users_id,
this.invoice,
this.seat_number,
this.total_price,
this.payment_method,
this.status,
this.items,
// this.menu,
});
TransactionModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
users_id = json['users_id'];
invoice = json['invoice'];
seat_number = json['seat_number'];
total_price = double.parse(json['total_price'].toString());
payment_method = json['payment_method'];
status = json['status'];
items = json['items'];
// menu = json['items']['menus'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'users_id': users_id,
'invoice': invoice,
'seat_number': seat_number,
'items': items,
'total_price': total_price,
'payment_method': payment_method,
'status': status,
// 'menu': menu,
};
}
}
i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?
It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.
Json
{
"id": 1,
"users_id": 1,
"invoice": "INV38972",
"seat_number": 2,
"total_price": 1000,
"payment_method": "TUNAI",
"status": "PENDING",
"items": [
{
"id": 1,
"menus_id": 1,
"transactions_id": 1,
"quantity": 5,
"menus": {
"id": 1,
"name": "Adidas NMD",
"price": 200,
"description": "Ini adalah sepatu sport",
"categories_id": 1
}
}
]
}
Model class
// To parse this JSON data, do
//
// final transactionModel = transactionModelFromMap(jsonString);
import 'dart:convert';
class TransactionModel {
TransactionModel({
this.id,
this.usersId,
this.invoice,
this.seatNumber,
this.totalPrice,
this.paymentMethod,
this.status,
this.items,
});
final int id;
final int usersId;
final String invoice;
final int seatNumber;
final int totalPrice;
final String paymentMethod;
final String status;
final List<Item> items;
factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
id: json["id"],
usersId: json["users_id"],
invoice: json["invoice"],
seatNumber: json["seat_number"],
totalPrice: json["total_price"],
paymentMethod: json["payment_method"],
status: json["status"],
items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"id": id,
"users_id": usersId,
"invoice": invoice,
"seat_number": seatNumber,
"total_price": totalPrice,
"payment_method": paymentMethod,
"status": status,
"items": List<dynamic>.from(items.map((x) => x.toMap())),
};
}
class Item {
Item({
this.id,
this.menusId,
this.transactionsId,
this.quantity,
this.menus,
});
final int id;
final int menusId;
final int transactionsId;
final int quantity;
final Menus menus;
factory Item.fromJson(String str) => Item.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Item.fromMap(Map<String, dynamic> json) => Item(
id: json["id"],
menusId: json["menus_id"],
transactionsId: json["transactions_id"],
quantity: json["quantity"],
menus: Menus.fromMap(json["menus"]),
);
Map<String, dynamic> toMap() => {
"id": id,
"menus_id": menusId,
"transactions_id": transactionsId,
"quantity": quantity,
"menus": menus.toMap(),
};
}
class Menus {
Menus({
this.id,
this.name,
this.price,
this.description,
this.categoriesId,
});
final int id;
final String name;
final int price;
final String description;
final int categoriesId;
factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Menus.fromMap(Map<String, dynamic> json) => Menus(
id: json["id"],
name: json["name"],
price: json["price"],
description: json["description"],
categoriesId: json["categories_id"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"description": description,
"categories_id": categoriesId,
};
}
I want to get data from API, my API data as DoctorModel inside it daysModel, inside daysModel is workTimeModel, each doctor has many days and has worktime.
I tried a lot of ways but still can't fix it.
note: I made my API from this website https://app.quicktype.io/
my code to get API data:
Response res = await get(
doctorsUrl ,
);
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
return doctors;
}
my API:
{
"id": 15,
"name": "Prof. Elton Quigley",
"about": "uHiKeKA1gq",
"stars": 5,
"location": "R59lmj1eud",
"latitude": 5,
"longitude": 5,
"notes": "yCl95VqUAz",
"days": [
{
"name": "سبت",
"pivot": {
"doctor_id": 15,
"day_id": 1,
"morning": "1",
"evening": "1"
}
},
{
"name": "أحد",
"pivot": {
"doctor_id": 15,
"day_id": 2,
"morning": "3",
"evening": "3"
}
},
{
"name": "إثنين",
"pivot": {
"doctor_id": 15,
"day_id": 3,
"morning": "5",
"evening": "5"
}
},
{
"name": "ثلاثاء",
"pivot": {
"doctor_id": 15,
"day_id": 4,
"morning": "4",
"evening": "4"
}
},
{
"name": "أربعاء",
"pivot": {
"doctor_id": 15,
"day_id": 5,
"morning": "5",
"evening": "5"
}
},
{
"name": "خميس",
"pivot": {
"doctor_id": 15,
"day_id": 6,
"morning": "4",
"evening": "4"
}
}
]
}
my DoctorModel:
// To parse this JSON data, do
//
// final doctorInfoModel = doctorInfoModelFromJson(jsonString);
import 'dart:convert';
DoctorInfoModel doctorInfoModelFromJson(String str) => DoctorInfoModel.fromJson(json.decode(str));
String doctorInfoModelToJson(DoctorInfoModel data) => json.encode(data.toJson());
class DoctorInfoModel {
DoctorInfoModel({
this.id,
this.name,
this.about,
this.stars,
this.location,
this.latitude,
this.longitude,
this.notes,
this.days,
});
int id;
String name;
String about;
int stars;
String location;
int latitude;
int longitude;
String notes;
List<Day> days;
factory DoctorInfoModel.fromJson(Map<String, dynamic> json) => DoctorInfoModel(
id: json["id"],
name: json["name"],
about: json["about"],
stars: json["stars"],
location: json["location"],
latitude: json["latitude"],
longitude: json["longitude"],
notes: json["notes"],
days: List<Day>.from(json["days"].map((x) => Day.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"about": about,
"stars": stars,
"location": location,
"latitude": latitude,
"longitude": longitude,
"notes": notes,
"days": List<dynamic>.from(days.map((x) => x.toJson())),
};
}
class Day {
Day({
this.name,
this.pivot,
});
String name;
Pivot pivot;
factory Day.fromJson(Map<String, dynamic> json) => Day(
name: json["name"],
pivot: Pivot.fromJson(json["pivot"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"pivot": pivot.toJson(),
};
}
class Pivot {
Pivot({
this.doctorId,
this.dayId,
this.morning,
this.evening,
});
int doctorId;
int dayId;
String morning;
String evening;
factory Pivot.fromJson(Map<String, dynamic> json) => Pivot(
doctorId: json["doctor_id"],
dayId: json["day_id"],
morning: json["morning"],
evening: json["evening"],
);
Map<String, dynamic> toJson() => {
"doctor_id": doctorId,
"day_id": dayId,
"morning": morning,
"evening": evening,
};
}
How can I get data correctly?
I figured out how to get data.
I replaced these two lines:
List<dynamic> data = body['data'];
List<DoctorInfoModel> doctors = data.map((dynamic item) => DoctorInfoModel.fromJson(item)).toList();
by these:
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
when my DoctorInfoModel is not a List, so I delete it.
Correct code to get API data:
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var data = body['data'];
DoctorInfoModel doctorInfo = DoctorInfoModel.fromJson(data);
print(doctorInfo.name);
print(doctorInfo.about);
print(doctorInfo.days[0].name);
print(doctorInfo.days[0].pivot.morning);
return doctorInfo;
}
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"]);
I have a json object here -
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "cciigcigc",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
I want to fetch it based on the ["data"]["status"] parameter; if the status is false, return a seperate list and if the status is true, return another list. I have tried to modify my current fetch method this way -
Future<List<Post>> gettask(bool identifier) async { // the identifier can be set to true and false
List<Post> statusComplete;
List<Post> statusInComplete;
String link = baseURL + fetchTodoByDate;
// print("printing from get task = $setter");
Stopwatch stopwatchbefore = new Stopwatch()..start();
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json", }, body: {"date" : setter.toString()});
print('fetch executed in ${stopwatchbefore.elapsed}');
if (res.statusCode == 200) {
Stopwatch stopwatchafter = new Stopwatch()
..start();
var data = json.decode(res.body);
var rest = data["data"] as List;
if(identifier == true){
statusComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusComplete;
}else if(identifier == false){
statusInComplete = rest.map<Post>((json) {
// need help in implementing logic here
return Post.fromJson(json);
}).toList();
return statusInComplete;
}
print('statuscode executed in ${stopwatchafter.elapsed}');
Future.delayed(Duration(seconds: 5));
}
// print("List Size: ${list.length}");
}
This is the first time I am trying to fetch and separate the data this way. I have tried to look at some tutorials but none seemed to be satisfying my case.
Could i get some suggestion on how to fetch the data and then separate it based on a parameter?
check out the example below which will give the basic idea how the flow works.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Datum> dataList = List();
bool _isLoading = false;
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadFromAssets();
final yourData = dataFromJson(jsonString);
dataList = yourData.data;
var statusComplete = dataList.where((i) => i.status == true).toList();
for (int i = 0; i < statusComplete.length; i++) {
print('This is the list for true status :${statusComplete[i].title}');
}
var statusInComplete = dataList.where((i) => i.status == false).toList();
print(statusInComplete[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(dataList[index].status.toString());
}),
)),
);
}
}
below is the model class
// To parse this JSON data, do
//
// final data = dataFromJson(jsonString);
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
String error;
String message;
List<Datum> data;
Data({
this.error,
this.message,
this.data,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
and this is the json that you specified
{
"error": "0",
"message": "Got it!",
"data": [
{
"status": false,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "first",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "second",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
},
{
"status": true,
"_id": "5e2fbb74d465702288c54038",
"group_id": "5e0d9e993944e46ed9a86d95",
"date": "2020-01-28T00:00:00.000Z",
"title": "third",
"priority": 3,
"description": "",
"tasks": [],
"created_date": "2020-01-28T04:41:24.576Z",
"__v": 0
}
]
}
Try this model class
import 'dart:convert';
Jsonmodel jsonmodelFromJson(String str) => Jsonmodel.fromJson(json.decode(str));
String jsonmodelToJson(Jsonmodel data) => json.encode(data.toJson());
class Jsonmodel {
String error;
String message;
List<Datum> data;
Jsonmodel({
this.error,
this.message,
this.data,
});
factory Jsonmodel.fromJson(Map<String, dynamic> json) => Jsonmodel(
error: json["error"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"error": error,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
bool status;
String id;
String groupId;
DateTime date;
String title;
int priority;
String description;
List<dynamic> tasks;
DateTime createdDate;
int v;
Datum({
this.status,
this.id,
this.groupId,
this.date,
this.title,
this.priority,
this.description,
this.tasks,
this.createdDate,
this.v,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
status: json["status"],
id: json["_id"],
groupId: json["group_id"],
date: DateTime.parse(json["date"]),
title: json["title"],
priority: json["priority"],
description: json["description"],
tasks: List<dynamic>.from(json["tasks"].map((x) => x)),
createdDate: DateTime.parse(json["created_date"]),
v: json["__v"],
);
Map<String, dynamic> toJson() => {
"status": status,
"_id": id,
"group_id": groupId,
"date": date.toIso8601String(),
"title": title,
"priority": priority,
"description": description,
"tasks": List<dynamic>.from(tasks.map((x) => x)),
"created_date": createdDate.toIso8601String(),
"__v": v,
};
}
use like this
var res = await http.post(Uri.encodeFull(link), headers: {"Accept":
"application/json", }, body: {"date" : setter.toString()});
Jsonmodel modeldata = jsonmodelFromJson(res);
// do your stuff
modeldata.data.foreach((data){
if(data.status){
//do your stuff
}else{
//do your stuff
}
});