Flutter : Get data on Nested json - flutter

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

Related

How to map a json list in flutter using JSONSerializable

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

Flutter - Dart parsing json data array returns type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>'

I'm trying to parse a json file using a custom model, I always get the error type 'List<dynamic>' is not a subtype of type 'List<BusinessTest>' and I don't know how I can fix my code. Also is it a good idea to always use nullable type in variables when you parse json files?
This is a Json example of my data:
{
"businesses": [{
"id": "1",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
},
{
"id": "2",
"alias": "123",
"name": "aaa",
"image_url": "xxx.jpg",
"is_closed": false,
"url": ".com",
"review_count": 26,
"rating": 5.0
}
]
}
Here is the model code I've made in order to parse the Json:
class BusinessSearch {
final List<BusinessTest> businesses;
final int total;
BusinessSearch(this.businesses, this.total);
BusinessSearch.fromJson(Map<String, dynamic> json)
: businesses = json['businesses'],
total = json['total'];
}
class BusinessTest {
final String? name;
final String? imageUrl;
final bool? isClosed;
final String? url;
final int? reviewCount;
BusinessTest(
this.name, this.imageUrl, this.isClosed, this.url, this.reviewCount);
BusinessTest.fromJson(Map<String, dynamic> json)
: name = json['name'],
imageUrl = json['image_url'],
isClosed = json['is_closed'],
url = json['url'],
reviewCount = json['review_count'];
}
This is how I'm trying to parse it:
void getData() async {
try {
String url = 'url';
NetworkHelp network = NetworkHelp(url: url);
var data = await network.getData();
Map<String, dynamic> businessMap = await jsonDecode(data);
var business = BusinessSearch.fromJson(businessMap);
} catch (e) {
print(e);
}
}
You have to update your BusinessSearch model like this.
class BusinessSearch {
BusinessSearch({
this.businesses,
this.total,
});
List<Business> businesses = [];
int total;
factory BusinessSearch.fromJson(Map<String, dynamic> json) => BusinessSearch(
businesses: List<Business>.from(json["businesses"].map((x) => Business.fromJson(x))),
total: json['total']
);
Map<String, dynamic> toJson() => {
"businesses": List<dynamic>.from(businesses.map((x) => x.toJson())),
"total": total,
};
}
class Business {
Business({
this.id,
this.alias,
this.name,
this.imageUrl,
this.isClosed,
this.url,
this.reviewCount,
this.rating,
});
String id;
String alias;
String name;
String imageUrl;
bool isClosed;
String url;
int reviewCount;
int rating;
factory Business.fromJson(Map<String, dynamic> json) => Business(
id: json["id"],
alias: json["alias"],
name: json["name"],
imageUrl: json["image_url"],
isClosed: json["is_closed"],
url: json["url"],
reviewCount: json["review_count"],
rating: json["rating"],
);
Map<String, dynamic> toJson() => {
"id": id,
"alias": alias,
"name": name,
"image_url": imageUrl,
"is_closed": isClosed,
"url": url,
"review_count": reviewCount,
"rating": rating,
};
}

Flutter Calendar Map/List convert

at first I want to show you my code, which i created and then I ask my question.
This here is a basic Map which contains no information.
Map<DateTime, List<Event>> selectedEvents;
List<Event> _getEventsfromDay(DateTime date) {
return selectedEvents[date] ?? [];
}
This here is my Code:
void main() {
var jsonSource = """
{
"Events": [
{
"id": 1,
"event_name": "Cake tasting",
"event_photo": "https://dispensaries.s3.amazonaws.com/event_photo/Southern_Cali_Kush_3.jpg",
"vendor_name": {
"id": 1,
"vendor": "Tastey Cakes"
},
"refund_available": false,
"website": "www.foodcakes.com",
"share_count": 0,
"check_in_count": 0,
"street_address": "123 Fake Street",
"city": "Brooklynn",
"state": "NY",
"zipcode": "12312",
"event_tagline": "Taste my cakes",
"details": "Cake tasting",
"start_date": "2020-11-03",
"start_time": "23:33:00",
"end_time": "23:33:00",
"attendees": []
}
]
}
""";
print(convertJsonToDateMap(jsonSource));
}
Map<DateTime, List> convertJsonToDateMap(String jsonSource) {
var json = jsonDecode(jsonSource);
var jsonEvents = json['Events'];
Map<DateTime, List<String>> events = {};
for(var event in jsonEvents){
var date = parseDate(event['start_date']);
events.putIfAbsent(date, () => <String>[]);
events[date].add(event['event_name']);
}
return events;
}
DateTime parseDate(String date) {
var parts = date.split('-').map(int.tryParse).toList();
return DateTime(parts[0], parts[1], parts[2]);
}
How to write my code that the 2. code is working like the first, so that the json is stored as Map/List.
I am Flutter beginnen and dont know how to do this.
Thanks for helping!!!
Change Your Model Like This :
import 'dart:convert';
EventModel eventModelFromJson(String str) => EventModel.fromJson(json.decode(str));
String eventModelToJson(EventModel data) => json.encode(data.toJson());
class EventModel {
EventModel({
this.events,
});
List<Event> events;
factory EventModel.fromJson(Map<String, dynamic> json) => EventModel(
events: List<Event>.from(json["Events"].map((x) => Event.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Events": List<dynamic>.from(events.map((x) => x.toJson())),
};
}
class Event {
Event({
this.id,
this.eventName,
this.eventPhoto,
this.vendorName,
this.refundAvailable,
this.website,
this.shareCount,
this.checkInCount,
this.streetAddress,
this.city,
this.state,
this.zipcode,
this.eventTagline,
this.details,
this.startDate,
this.startTime,
this.endTime,
this.attendees,
});
int id;
String eventName;
String eventPhoto;
VendorName vendorName;
bool refundAvailable;
String website;
int shareCount;
int checkInCount;
String streetAddress;
String city;
String state;
String zipcode;
String eventTagline;
String details;
DateTime startDate;
String startTime;
String endTime;
List<dynamic> attendees;
factory Event.fromJson(Map<String, dynamic> json) => Event(
id: json["id"],
eventName: json["event_name"],
eventPhoto: json["event_photo"],
vendorName: VendorName.fromJson(json["vendor_name"]),
refundAvailable: json["refund_available"],
website: json["website"],
shareCount: json["share_count"],
checkInCount: json["check_in_count"],
streetAddress: json["street_address"],
city: json["city"],
state: json["state"],
zipcode: json["zipcode"],
eventTagline: json["event_tagline"],
details: json["details"],
startDate: DateTime.parse(json["start_date"]),
startTime: json["start_time"],
endTime: json["end_time"],
attendees: List<dynamic>.from(json["attendees"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"id": id,
"event_name": eventName,
"event_photo": eventPhoto,
"vendor_name": vendorName.toJson(),
"refund_available": refundAvailable,
"website": website,
"share_count": shareCount,
"check_in_count": checkInCount,
"street_address": streetAddress,
"city": city,
"state": state,
"zipcode": zipcode,
"event_tagline": eventTagline,
"details": details,
"start_date": "${startDate.year.toString().padLeft(4, '0')}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')}",
"start_time": startTime,
"end_time": endTime,
"attendees": List<dynamic>.from(attendees.map((x) => x)),
};
}
class VendorName {
VendorName({
this.id,
this.vendor,
});
int id;
String vendor;
factory VendorName.fromJson(Map<String, dynamic> json) => VendorName(
id: json["id"],
vendor: json["vendor"],
);
Map<String, dynamic> toJson() => {
"id": id,
"vendor": vendor,
};
}
To parse this JSON data, do
final eventModel = eventModelFromJson(jsonString);
Then Check the Map

how flutter map in for widget

my json=
{
"result": {
"name": "json1",
"pages": [{
"zones": [{
"title": "title1"
},
{
"title": "title2"
}],
"id": 4
},
{
"zones": [{
"title": "title3"
},
{
"title": "title4"
}],
"id": 12
}],
"creatorUserName": "admin",
"id": 2
}
}
futurebuilder code
List post = snapshot.data["result"]["pages"];
return new Stack(
children: post.where((val) => val["id"] == 4).map((post) {
for (var item in post['zones']) {
print("title "+ item['title']);
Container(
child: Text(item["title"]),
); //Container
}
}).toList(),
); //Stack
Error code: Stack's children must not contain any null values, but a null value was found at index 0
enter image description here
help how can to build an algorithms
if get id = 4 zones -> Text(title1), Text(title2),
else id empty zones -> Text(title1), Text(title2), zones -> Text(title3), Text(title4),
Try
List post = snapshots.data["result"]["pages"];
First Make a model class for your JSON response using this amazing webpage, after that you can easily. call the needed data
import 'dart:convert';
YourModelClassName yourModelClassNameFromJson(String str) => YourModelClassName.fromJson(json.decode(str));
String yourModelClassNameToJson(YourModelClassName data) => json.encode(data.toJson());
class YourModelClassName {
Result result;
YourModelClassName({
this.result,
});
factory YourModelClassName.fromJson(Map<String, dynamic> json) => YourModelClassName(
result: Result.fromJson(json["result"]),
);
Map<String, dynamic> toJson() => {
"result": result.toJson(),
};
}
class Result {
String name;
List<Page> pages;
String creatorUserName;
int id;
Result({
this.name,
this.pages,
this.creatorUserName,
this.id,
});
factory Result.fromJson(Map<String, dynamic> json) => Result(
name: json["name"],
pages: List<Page>.from(json["pages"].map((x) => Page.fromJson(x))),
creatorUserName: json["creatorUserName"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"name": name,
"pages": List<dynamic>.from(pages.map((x) => x.toJson())),
"creatorUserName": creatorUserName,
"id": id,
};
}
class Page {
List<Zone> zones;
int id;
Page({
this.zones,
this.id,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
zones: List<Zone>.from(json["zones"].map((x) => Zone.fromJson(x))),
id: json["id"],
);
Map<String, dynamic> toJson() => {
"zones": List<dynamic>.from(zones.map((x) => x.toJson())),
"id": id,
};
}
class Zone {
String title;
Zone({
this.title,
});
factory Zone.fromJson(Map<String, dynamic> json) => Zone(
title: json["title"],
);
Map<String, dynamic> toJson() => {
"title": title,
};
}

How to fetch json data and separate it based on a Parameter?

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