Related
I’m trying to parse one object from a Json response. My response.data is of type ‘_InternalLinkedHashMap<String, dynamic>’. I would like to transform it to the type of my object. So for doing that I use the method fromJson of my class.
Class code:
import 'dart:convert';
import 'package:.../stl/store_stl.dart';
class StoreSTLModel extends StoreSTL {const StoreSTLModel({
required String storeId,
required String storeName,
required String subContextUrl,
required List<dynamic> openingEvent,
required List<dynamic> closingEvent,
}) : super(
storeId: storeId,
storeName: storeName,
subContextUrl: subContextUrl,
openingEvent: openingEvent,
closingEvent:closingEvent ,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'storeId': storeId,
'storeName': storeName,
'subContextUrl': subContextUrl,
'openingEvent': openingEvent.toList(),
'closingEvent': closingEvent.toList(),
};
}
factory StoreSTLModel.fromMap(Map<String, dynamic> map) {
return StoreSTLModel(
storeId: map['storeId'] as String ,
storeName: map["storeName"] as String,
subContextUrl: map["subContextUrl"] as String,
openingEvent: List<dynamic>.from(map["openingEvent"] as List<dynamic>),
closingEvent: List<dynamic>.from(map["closingEvent"] as List<dynamic>),
);
}
String toJson() => json.encode(toMap());
factory StoreSTLModel.fromJson(String source) => StoreSTLModel.fromMap(json.decode(source) as Map<String, dynamic>);
}
the code of my request is as follow: (I’m using Dio package)
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
//get store from api STL (for now store id is hardcode)
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
Response? response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
print('apiSTLData type response.data ${ apiSTLData.runtimeType}');
//prints: apiSTLData type response.data _InternalLinkedHashMap<String, dynamic>
}on Exception {
null;
print('apiSTLData Exception');
}
}
print('apiSTLData type response.data[store] ${apiSTLData['store'].runtimeType}');
//prints: apiSTLData type response.data[store] _InternalLinkedHashMap<String, dynamic>
return StoreSTLModel.fromJson(apiSTLData['store']);
}
}
when I try to run, I’m having the error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
so I don’t understand why it is not being parsed. and I don’t understand why the response is of this type ‘_InternalLinkedHashMap<String, dynamic>’ I'm a beginner in Dart. Could you please help me to understand. Thanks in advance :)
{
"store": {
"storeId": "30264",
"storeName": "xxxxx",
"subContextUrl": "hxxxu-xxxxx",
"type": "STORE",
"address": {
"label": null,
"zipcode": "xxxx",
"city": "xxxx",
"countryCode": "xxxx",
"lines": [
"xxxxxxxx",
""
]
},
"openingEvent": [],
"closingEvent": [],
"dayHours": {
"day": "THURSDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
"driveHours": {
"timezone": "xxxxxx",
"openHourList": [
{
"day": "MONDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
{
"day": "SUNDAY",
"morningOpeningHour": null,
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": null
}
]
},
"eservices": [
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 2,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 4,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 39,
"serviceName": "xxxxx"
}
],
"services": [
"xxxxxx",
"xxxxx",
"xxxxxxx"
],
"additionalStoreInfo": {
"status": "xxxxx",
"commercialSignLabel": "xxxxx"
}
}
}
This is model class
import 'dart:convert';
class StoreSTLModel {
StoreSTLModel({
required this.store,
});
final Store store;
factory StoreSTLModel.fromJson(String str) => StoreSTLModel.fromMap(json.decode(str));
factory StoreSTLModel.fromMap(Map<String, dynamic> json) => StoreSTLModel(
store: Store.fromMap(json["store"]),
);
Map<String, dynamic> toMap() => {
"store": store.toMap(),
};
}
class Store {
Store({
required this.storeId,
required this.storeName,
required this.subContextUrl,
required this.type,
required this.address,
required this.openingEvent,
required this.closingEvent,
required this.dayHours,
required this.driveHours,
required this.eservices,
required this.services,
required this.additionalStoreInfo,
});
final String storeId;
final String storeName;
final String subContextUrl;
final String type;
final Address address;
final List<dynamic> openingEvent;
final List<dynamic> closingEvent;
final DayHours dayHours;
final DriveHours driveHours;
final List<Eservice> eservices;
final List<String> services;
final AdditionalStoreInfo additionalStoreInfo;
factory Store.fromMap(Map<String, dynamic> json) => Store(
storeId: json["storeId"],
storeName: json["storeName"],
subContextUrl: json["subContextUrl"],
type: json["type"],
address: Address.fromMap(json["address"]),
openingEvent: List<dynamic>.from(json["openingEvent"].map((x) => x)),
closingEvent: List<dynamic>.from(json["closingEvent"].map((x) => x)),
dayHours: DayHours.fromMap(json["dayHours"]),
driveHours: DriveHours.fromMap(json["driveHours"]),
eservices: List<Eservice>.from(json["eservices"].map((x) => Eservice.fromMap(x))),
services: List<String>.from(json["services"].map((x) => x)),
additionalStoreInfo: AdditionalStoreInfo.fromMap(json["additionalStoreInfo"]),
);
Map<String, dynamic> toMap() => {
"storeId": storeId,
"storeName": storeName,
"subContextUrl": subContextUrl,
"type": type,
"address": address.toMap(),
"openingEvent": List<dynamic>.from(openingEvent.map((x) => x)),
"closingEvent": List<dynamic>.from(closingEvent.map((x) => x)),
"dayHours": dayHours.toMap(),
"driveHours": driveHours.toMap(),
"eservices": List<dynamic>.from(eservices.map((x) => x.toMap())),
"services": List<dynamic>.from(services.map((x) => x)),
"additionalStoreInfo": additionalStoreInfo.toMap(),
};
}
class AdditionalStoreInfo {
AdditionalStoreInfo({
required this.status,
required this.commercialSignLabel,
});
final String status;
final String commercialSignLabel;
factory AdditionalStoreInfo.fromMap(Map<String, dynamic> json) => AdditionalStoreInfo(
status: json["status"],
commercialSignLabel: json["commercialSignLabel"],
);
Map<String, dynamic> toMap() => {
"status": status,
"commercialSignLabel": commercialSignLabel,
};
}
class Address {
Address({
required this.label,
required this.zipcode,
required this.city,
required this.countryCode,
required this.lines,
});
final dynamic label;
final String zipcode;
final String city;
final String countryCode;
final List<String> lines;
factory Address.fromMap(Map<String, dynamic> json) => Address(
label: json["label"],
zipcode: json["zipcode"],
city: json["city"],
countryCode: json["countryCode"],
lines: List<String>.from(json["lines"].map((x) => x)),
);
Map<String, dynamic> toMap() => {
"label": label,
"zipcode": zipcode,
"city": city,
"countryCode": countryCode,
"lines": List<dynamic>.from(lines.map((x) => x)),
};
}
class DayHours {
DayHours({
required this.day,
required this.morningOpeningHour,
required this.morningClosingHour,
required this.afternoonOpeningHour,
required this.afternoonClosingHour,
});
final String day;
final String morningOpeningHour;
final dynamic morningClosingHour;
final dynamic afternoonOpeningHour;
final String afternoonClosingHour;
factory DayHours.fromMap(Map<String, dynamic> json) => DayHours(
day: json["day"],
morningOpeningHour: json["morningOpeningHour"],
morningClosingHour: json["morningClosingHour"],
afternoonOpeningHour: json["afternoonOpeningHour"],
afternoonClosingHour: json["afternoonClosingHour"],
);
Map<String, dynamic> toMap() => {
"day": day,
"morningOpeningHour": morningOpeningHour,
"morningClosingHour": morningClosingHour,
"afternoonOpeningHour": afternoonOpeningHour,
"afternoonClosingHour": afternoonClosingHour,
};
}
class DriveHours {
DriveHours({
required this.timezone,
required this.openHourList,
});
final String timezone;
final List<DayHours> openHourList;
factory DriveHours.fromMap(Map<String, dynamic> json) => DriveHours(
timezone: json["timezone"],
openHourList: List<DayHours>.from(json["openHourList"].map((x) => DayHours.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"timezone": timezone,
"openHourList": List<dynamic>.from(openHourList.map((x) => x.toMap())),
};
}
class Eservice {
Eservice({
required this.website,
required this.linkTitle,
required this.linklabel,
required this.serviceId,
required this.serviceName,
});
final String website;
final dynamic linkTitle;
final dynamic linklabel;
final int serviceId;
final String serviceName;
factory Eservice.fromMap(Map<String, dynamic> json) => Eservice(
website: json["website"],
linkTitle: json["linkTitle"],
linklabel: json["linklabel"],
serviceId: json["serviceId"],
serviceName: json["serviceName"],
);
Map<String, dynamic> toMap() => {
"website": website,
"linkTitle": linkTitle,
"linklabel": linklabel,
"serviceId": serviceId,
"serviceName": serviceName,
};
}
This is Dio class
import 'dart:convert';
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
final response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
if (response.statusCode == 200) {
//Try them, one of them will work.
return StoreSTLModel.fromMap(apiSTLData);
return StoreSTLModel.fromJson(apiSTLData);
} else {
throw Exception("404 error");
}
} on DioError catch (e) {
return Future.error(e.message);
}
}
}
}
Try this.
the json I receive from the api looks like this:
{
"USD": [
{
"name": "something",
"value": 123
},
{
"name": "something else",
"value": 1234
}
],
"EUR": [
... same here
]
}
and my dart model looks like:
#JsonSerializable(anyMap: true, includeIfNull: true)
class StatisticsDto {
StatisticsDto({this.statistics});
final Map<String, List<StatisticsDetailDto>> statistics;
factory StatisticsDto.fromJson(Map<String, dynamic> json) =>
_$StatisticsDtoFromJson(json);
Map<String, dynamic> toJson() => _$StatisticsDtoToJson(this);
}
#JsonSerializable()
class StatisticsDetailDto {
StatisticsDetailDto({
this.name,
this.value,
});
final String name;
final num value;
factory StatisticsDetailDto.fromJson(Map<String, dynamic> json) =>
_$StatisticsDetailDtoFromJson(json);
Map<String, dynamic> toJson() => _$StatisticsDetailDtoToJson(this);
}
I don't seem to be able to make it work, I get a 200 from the api, but the serialization returns null.
What am I doing wrong here?
This is what your JSON objects should look like converted to Dart data class with json_serializable
{
"USD": [{
"name": "something",
"value": 123
},
{
"name": "something else",
"value": 1234
}
],
"EUR": [{
"name": "something",
"value": 123
},
{
"name": "something else",
"value": 1234
}
]
}
Dart data class with json_serializable without Map support:
import 'package:json_annotation/json_annotation.dart';
part 'statistic_dto.g.dart';
part 'currency.g.dart';
#JsonSerializable()
class StatisticDto {
StatisticDto({this.usd, this.eur});
#JsonKey(name: 'USD')
List<Currency>? usd;
#JsonKey(name: 'EUR')
List<Currency>? eur;
factory StatisticDto.fromJson(Map<String, dynamic> json) {
return _$StatisticDtoFromJson(json);
}
Map<String, dynamic> toJson() => _$StatisticDtoToJson(this);
}
#JsonSerializable()
class Currency {
Currency({this.name, this.value});
String? name;
int? value;
factory Currency.fromJson(Map<String, dynamic> json) => _$CurrencyFromJson(json);
Map<String, dynamic> toJson() => _$CurrencyToJson(this);
}
Run:
flutter pub run build_runner build --delete-conflicting-outputs
In your first example, your Map statistics have no key that why it always returns null. JSON file would look like this for your first class Data
// For: final Map<String, Map<String, dynamic>> statistics;
{
"statistics": {
"USD": {
"name": "One",
"value": 1
},
"EUR": {
"name": "Four",
"value": 4
}
}
}
If you are looking to serialize a json with fixed keys, please refer to Arnas' answer.
In my case, the json has dynamic keys, e.g. it's a map with an indefinite number of keys (corresponding to a currency code in my case), and a corresponding value (an array of objects).
Now, I reckon #JsonSerializable is not suitable for this kind of scenario, hence I implemented my own .fromJson() factories.
class StatisticsDto {
StatisticsDto({this.statistics});
final Map<String, List<StatisticsDetailDto>> statistics;
factory StatisticsDto.fromJson(Map<String, dynamic> json) =>
StatisticsDto(
statistics: json.map((String currency, dynamic details) {
final List<StatisticsDetailDto> currencyDetails = details
.map<StatisticsDetailDto>(
(detail) => StatisticsDetailDto.fromJson(detail))
.toList();
return MapEntry<String, List<StatisticsDetailDto>>(currency, currencyDetails);
})
);
}
class StatisticsDetailDto {
StatisticsDetailDto({
this.name,
this.value,
});
final String name;
final num value;
factory StatisticsDetailDto.fromJson(Map<String, dynamic> json) =>
StatisticsDetailDto(
type: json['name'],
value: json['value'],
);
}
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 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
}
});
I am trying to loop through weather forcast form OpenWeather API.
List view is not rendered. Only loading indicator is rendered. "list" is array where i want to fetch data and display in ListView. I think there is someting wrong with model mapping. Thank you
{
"list": [
{
"dt": 1566518400,
"main": {
"temp": 14.68,
"temp_min": 14.25,
"temp_max": 14.68,
"pressure": 1029.5,
"sea_level": 1029.5,
"grnd_level": 1018.5,
"humidity": 74,
"temp_kf": 0.43
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
"clouds": {
"all": 16
},
"wind": {
"speed": 2.42,
"deg": 93.981
},
"sys": {
"pod": "n"
},
"dt_txt": "2019-08-23 00:00:00"
},
Function to fetch forcast
Future<List<Forcast>> _fetchUsers() async {
http.Response response = await http.get(
'http://api.openweathermap.org/data/2.5/forecast?q=warsaw&units=metric&appid=');
if (response.statusCode == 200) {
final data = json.decode(response.body);
List<Forcast> list = data['list'].map<Forcast>((json) {
return Forcast.fromJson(json);
}).toList();
return list;
} else {
throw Exception('Failed to load internet');
}
}
Future builder
child: SizedBox(
height: 400.0,
child: FutureBuilder<List>(
future: _fetchUsers(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView(
children: snapshot.data
.map((user) => ListTile(
title: Text(user.dt),
subtitle: Text(user.temp),
))
.toList(),
);
},
),
),
Forcastt model
class Forcast {
int id;
String temp;
Forcast({
this.id,
this.temp,
});
factory Forcast.fromJson(Map<String, dynamic> json) {
print(json);
return Forcast(
id: json['dt'],
temp: json['main'].temp,
);
}
}
You can put your full json string to https://app.quicktype.io/
and you will get correct model
because json string you post in question is invalid
so I use json from demo json of https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22
bleow is demo Forcast structure from sample json
// To parse this JSON data, do
//
// final forcast = forcastFromJson(jsonString);
import 'dart:convert';
Forcast forcastFromJson(String str) => Forcast.fromJson(json.decode(str));
String forcastToJson(Forcast data) => json.encode(data.toJson());
class Forcast {
String cod;
double message;
int cnt;
List<ListElement> list;
City city;
Forcast({
this.cod,
this.message,
this.cnt,
this.list,
this.city,
});
factory Forcast.fromJson(Map<String, dynamic> json) => new Forcast(
cod: json["cod"],
message: json["message"].toDouble(),
cnt: json["cnt"],
list: new List<ListElement>.from(json["list"].map((x) => ListElement.fromJson(x))),
city: City.fromJson(json["city"]),
);
Map<String, dynamic> toJson() => {
"cod": cod,
"message": message,
"cnt": cnt,
"list": new List<dynamic>.from(list.map((x) => x.toJson())),
"city": city.toJson(),
};
}
class City {
int id;
String name;
Coord coord;
String country;
City({
this.id,
this.name,
this.coord,
this.country,
});
factory City.fromJson(Map<String, dynamic> json) => new City(
id: json["id"],
name: json["name"],
coord: Coord.fromJson(json["coord"]),
country: json["country"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"coord": coord.toJson(),
"country": country,
};
}
class Coord {
double lat;
double lon;
Coord({
this.lat,
this.lon,
});
factory Coord.fromJson(Map<String, dynamic> json) => new Coord(
lat: json["lat"].toDouble(),
lon: json["lon"].toDouble(),
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lon": lon,
};
}
class ListElement {
int dt;
MainClass main;
List<Weather> weather;
Clouds clouds;
Wind wind;
Sys sys;
DateTime dtTxt;
Rain rain;
Rain snow;
ListElement({
this.dt,
this.main,
this.weather,
this.clouds,
this.wind,
this.sys,
this.dtTxt,
this.rain,
this.snow,
});
factory ListElement.fromJson(Map<String, dynamic> json) => new ListElement(
dt: json["dt"],
main: MainClass.fromJson(json["main"]),
weather: new List<Weather>.from(json["weather"].map((x) => Weather.fromJson(x))),
clouds: Clouds.fromJson(json["clouds"]),
wind: Wind.fromJson(json["wind"]),
sys: Sys.fromJson(json["sys"]),
dtTxt: DateTime.parse(json["dt_txt"]),
rain: json["rain"] == null ? null : Rain.fromJson(json["rain"]),
snow: json["snow"] == null ? null : Rain.fromJson(json["snow"]),
);
Map<String, dynamic> toJson() => {
"dt": dt,
"main": main.toJson(),
"weather": new List<dynamic>.from(weather.map((x) => x.toJson())),
"clouds": clouds.toJson(),
"wind": wind.toJson(),
"sys": sys.toJson(),
"dt_txt": dtTxt.toIso8601String(),
"rain": rain == null ? null : rain.toJson(),
"snow": snow == null ? null : snow.toJson(),
};
}
class Clouds {
int all;
Clouds({
this.all,
});
factory Clouds.fromJson(Map<String, dynamic> json) => new Clouds(
all: json["all"],
);
Map<String, dynamic> toJson() => {
"all": all,
};
}
class MainClass {
double temp;
double tempMin;
double tempMax;
double pressure;
double seaLevel;
double grndLevel;
int humidity;
double tempKf;
MainClass({
this.temp,
this.tempMin,
this.tempMax,
this.pressure,
this.seaLevel,
this.grndLevel,
this.humidity,
this.tempKf,
});
factory MainClass.fromJson(Map<String, dynamic> json) => new MainClass(
temp: json["temp"].toDouble(),
tempMin: json["temp_min"].toDouble(),
tempMax: json["temp_max"].toDouble(),
pressure: json["pressure"].toDouble(),
seaLevel: json["sea_level"].toDouble(),
grndLevel: json["grnd_level"].toDouble(),
humidity: json["humidity"],
tempKf: json["temp_kf"].toDouble(),
);
Map<String, dynamic> toJson() => {
"temp": temp,
"temp_min": tempMin,
"temp_max": tempMax,
"pressure": pressure,
"sea_level": seaLevel,
"grnd_level": grndLevel,
"humidity": humidity,
"temp_kf": tempKf,
};
}
class Rain {
double the3H;
Rain({
this.the3H,
});
factory Rain.fromJson(Map<String, dynamic> json) => new Rain(
the3H: json["3h"] == null ? null : json["3h"].toDouble(),
);
Map<String, dynamic> toJson() => {
"3h": the3H == null ? null : the3H,
};
}
class Sys {
Pod pod;
Sys({
this.pod,
});
factory Sys.fromJson(Map<String, dynamic> json) => new Sys(
pod: podValues.map[json["pod"]],
);
Map<String, dynamic> toJson() => {
"pod": podValues.reverse[pod],
};
}
enum Pod { D, N }
final podValues = new EnumValues({
"d": Pod.D,
"n": Pod.N
});
class Weather {
int id;
MainEnum main;
Description description;
String icon;
Weather({
this.id,
this.main,
this.description,
this.icon,
});
factory Weather.fromJson(Map<String, dynamic> json) => new Weather(
id: json["id"],
main: mainEnumValues.map[json["main"]],
description: descriptionValues.map[json["description"]],
icon: json["icon"],
);
Map<String, dynamic> toJson() => {
"id": id,
"main": mainEnumValues.reverse[main],
"description": descriptionValues.reverse[description],
"icon": icon,
};
}
enum Description { CLEAR_SKY, BROKEN_CLOUDS, LIGHT_RAIN, MODERATE_RAIN, FEW_CLOUDS }
final descriptionValues = new EnumValues({
"broken clouds": Description.BROKEN_CLOUDS,
"clear sky": Description.CLEAR_SKY,
"few clouds": Description.FEW_CLOUDS,
"light rain": Description.LIGHT_RAIN,
"moderate rain": Description.MODERATE_RAIN
});
enum MainEnum { CLEAR, CLOUDS, RAIN }
final mainEnumValues = new EnumValues({
"Clear": MainEnum.CLEAR,
"Clouds": MainEnum.CLOUDS,
"Rain": MainEnum.RAIN
});
class Wind {
double speed;
double deg;
Wind({
this.speed,
this.deg,
});
factory Wind.fromJson(Map<String, dynamic> json) => new Wind(
speed: json["speed"].toDouble(),
deg: json["deg"].toDouble(),
);
Map<String, dynamic> toJson() => {
"speed": speed,
"deg": deg,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}