Related
I am trying to fetch data from api and add into my list, but I am getting error like this "'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable'". How i can solve this error.
Following are my json response:
{
"status": true,
"result": "found",
"data": [
{
"ref_id": "37",
"postId": "106764933065187174744",
"azakhana_name": "Sakina hall",
"city_name": "Mahuva",
"description": "no detail",
"end_date": "14-01-2023",
"image_path": "Posts_Images\/POST-IMG1423956606.jpg",
"name_of_schollar": "Molana sahab",
"postDateTime": "05-01-2023 11:49 AM",
"program_list": "Majlis",
"special_notes": "no notes",
"start_date": "07-01-2023",
"time": "10:00 AM",
"user_name": "Taki Rajani",
"status": "Ongoing"
},
{
"ref_id": "39",
"postId": "106764933065187174744",
"azakhana_name": "aaa",
"city_name": "sss",
"description": "ssss",
"end_date": "05-01-2023",
"image_path": "Posts_Images\/POST-IMG869535151.jpg",
"name_of_schollar": "ssss",
"postDateTime": "05-01-2023 12:07 PM",
"program_list": "Majlis",
"special_notes": "ss",
"start_date": "05-01-2023",
"time": "12:07 PM",
"user_name": "Taki Rajani",
"status": "Past"
},
],
"totalPosts": "5",
"totalPages": 2,
"perPageLimit": 3,
"currentPage": 1,
"hasNextPage": 1
}
My code for fetching api details and add into my array:
List<UserPostModel> myList = [];
Future<List<UserPostModel>> getUserPost() async {
var url =
"https:getUserPost.php?page=$currentPage";
var response = await http.get(Uri.parse(url));
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
for (var i in data){
myList.add(UserPostModel.fromJson(i));
}
print(myList);
return myList;
} else {
print("failed");
return myList;
}
}
Following are my model class, which basically created by one package in android studio which name is JsonToDart.
class UserPostModel {
UserPostModel({
bool? status,
String? result,
List<Data>? data,
String? totalPosts,
num? totalPages,
num? perPageLimit,
num? currentPage,
num? hasNextPage,}){
_status = status;
_result = result;
_data = data;
_totalPosts = totalPosts;
_totalPages = totalPages;
_perPageLimit = perPageLimit;
_currentPage = currentPage;
_hasNextPage = hasNextPage;
}
UserPostModel.fromJson(dynamic json) {
_status = json['status'];
_result = json['result'];
if (json['data'] != null) {
_data = [];
json['data'].forEach((v) {
_data?.add(Data.fromJson(v));
});
}
_totalPosts = json['totalPosts'];
_totalPages = json['totalPages'];
_perPageLimit = json['perPageLimit'];
_currentPage = json['currentPage'];
_hasNextPage = json['hasNextPage'];
}
bool? _status;
String? _result;
List<Data>? _data;
String? _totalPosts;
num? _totalPages;
num? _perPageLimit;
num? _currentPage;
num? _hasNextPage;
UserPostModel copyWith({ bool? status,
String? result,
List<Data>? data,
String? totalPosts,
num? totalPages,
num? perPageLimit,
num? currentPage,
num? hasNextPage,
}) => UserPostModel( status: status ?? _status,
result: result ?? _result,
data: data ?? _data,
totalPosts: totalPosts ?? _totalPosts,
totalPages: totalPages ?? _totalPages,
perPageLimit: perPageLimit ?? _perPageLimit,
currentPage: currentPage ?? _currentPage,
hasNextPage: hasNextPage ?? _hasNextPage,
);
bool? get status => _status;
String? get result => _result;
List<Data>? get data => _data;
String? get totalPosts => _totalPosts;
num? get totalPages => _totalPages;
num? get perPageLimit => _perPageLimit;
num? get currentPage => _currentPage;
num? get hasNextPage => _hasNextPage;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['status'] = _status;
map['result'] = _result;
if (_data != null) {
map['data'] = _data?.map((v) => v.toJson()).toList();
}
map['totalPosts'] = _totalPosts;
map['totalPages'] = _totalPages;
map['perPageLimit'] = _perPageLimit;
map['currentPage'] = _currentPage;
map['hasNextPage'] = _hasNextPage;
return map;
}
}
/// ref_id : "37"
/// postId : "106764933065187174744"
/// azakhana_name : "Sakina hall"
/// city_name : "Mahuva"
/// description : "no detail"
/// end_date : "14-01-2023"
/// image_path : "Posts_Images/POST-IMG1423956606.jpg"
/// name_of_schollar : "Molana sahab"
/// postDateTime : "05-01-2023 11:49 AM"
/// program_list : "Majlis"
/// special_notes : "no notes"
/// start_date : "07-01-2023"
/// time : "10:00 AM"
/// user_name : "Taki Rajani"
/// status : "Ongoing"
class Data {
Data({
String? refId,
String? postId,
String? azakhanaName,
String? cityName,
String? description,
String? endDate,
String? imagePath,
String? nameOfSchollar,
String? postDateTime,
String? programList,
String? specialNotes,
String? startDate,
String? time,
String? userName,
String? status,}){
_refId = refId;
_postId = postId;
_azakhanaName = azakhanaName;
_cityName = cityName;
_description = description;
_endDate = endDate;
_imagePath = imagePath;
_nameOfSchollar = nameOfSchollar;
_postDateTime = postDateTime;
_programList = programList;
_specialNotes = specialNotes;
_startDate = startDate;
_time = time;
_userName = userName;
_status = status;
}
Data.fromJson(dynamic json) {
_refId = json['ref_id'];
_postId = json['postId'];
_azakhanaName = json['azakhana_name'];
_cityName = json['city_name'];
_description = json['description'];
_endDate = json['end_date'];
_imagePath = json['image_path'];
_nameOfSchollar = json['name_of_schollar'];
_postDateTime = json['postDateTime'];
_programList = json['program_list'];
_specialNotes = json['special_notes'];
_startDate = json['start_date'];
_time = json['time'];
_userName = json['user_name'];
_status = json['status'];
}
String? _refId;
String? _postId;
String? _azakhanaName;
String? _cityName;
String? _description;
String? _endDate;
String? _imagePath;
String? _nameOfSchollar;
String? _postDateTime;
String? _programList;
String? _specialNotes;
String? _startDate;
String? _time;
String? _userName;
String? _status;
Data copyWith({ String? refId,
String? postId,
String? azakhanaName,
String? cityName,
String? description,
String? endDate,
String? imagePath,
String? nameOfSchollar,
String? postDateTime,
String? programList,
String? specialNotes,
String? startDate,
String? time,
String? userName,
String? status,
}) => Data( refId: refId ?? _refId,
postId: postId ?? _postId,
azakhanaName: azakhanaName ?? _azakhanaName,
cityName: cityName ?? _cityName,
description: description ?? _description,
endDate: endDate ?? _endDate,
imagePath: imagePath ?? _imagePath,
nameOfSchollar: nameOfSchollar ?? _nameOfSchollar,
postDateTime: postDateTime ?? _postDateTime,
programList: programList ?? _programList,
specialNotes: specialNotes ?? _specialNotes,
startDate: startDate ?? _startDate,
time: time ?? _time,
userName: userName ?? _userName,
status: status ?? _status,
);
String? get refId => _refId;
String? get postId => _postId;
String? get azakhanaName => _azakhanaName;
String? get cityName => _cityName;
String? get description => _description;
String? get endDate => _endDate;
String? get imagePath => _imagePath;
String? get nameOfSchollar => _nameOfSchollar;
String? get postDateTime => _postDateTime;
String? get programList => _programList;
String? get specialNotes => _specialNotes;
String? get startDate => _startDate;
String? get time => _time;
String? get userName => _userName;
String? get status => _status;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['ref_id'] = _refId;
map['postId'] = _postId;
map['azakhana_name'] = _azakhanaName;
map['city_name'] = _cityName;
map['description'] = _description;
map['end_date'] = _endDate;
map['image_path'] = _imagePath;
map['name_of_schollar'] = _nameOfSchollar;
map['postDateTime'] = _postDateTime;
map['program_list'] = _programList;
map['special_notes'] = _specialNotes;
map['start_date'] = _startDate;
map['time'] = _time;
map['user_name'] = _userName;
map['status'] = _status;
return map;
}
}
I tried following solution but its give me error like : 'String' is not a subtype of type 'bool?'
Future<List<UserPostModel>> getUserPost() async {
var url =
"APIgetUserPost.php?page=$currentPage";
var response = await http.get(Uri.parse(url));
Map<String,dynamic> data = jsonDecode(response.body);
List<dynamic> data1 = data["data"];
//This print give me perfect answer
print(data1[0]["azakhana_name"]);
if (response.statusCode == 200) {
for (var i in data1){
myList.add(UserPostModel.fromJson(i));
}
print(myList);
return myList;
} else {
print("failed");
return myList;
}
}
This may help you
Future<List> getPosts(int categoryId) async {
List<PostModel> templist = [];
ApiBaseHelper _helper = ApiBaseHelper();
Map<String, dynamic> data = <String, dynamic>{};
data['username'] = user!.username;
data['category_id'] = categoryId;
data['ofset'] = offset;
final response = await _helper.post(url_getAllPublicPosts, data);
if (!response['error']) {
List<dynamic> record = List.from(response['records']);
for (var i = 0; i < record.length; i++) {
try {
if (record[i]['shared_post'].toString().isEmpty) {
templist.add(PostModel.fromJson(record[i]));
} else {
templist.add(PostModel.fromJson(record[i]['shared_post']));
templist[i].addShareDetails(record[i]);
}
} catch (Exception) {
print(Exception.toString());
}
}
basically the issue is i am getting cities array and in the cities array i have multiple cities and each city also contain array i need model for this json response i am using "https://app.quicktype.io/"
{
"code": "0",
"message": "Success!",
"data": {
"firstName": "hello",
"lastName": "world",
"mobile1": "123456789",
"mobile2": "123456789",
"cities": [
{
"Dubai": [
{
"id": 17,
"value": "Dubai",
"selected": false
}
]
},
{
"Ajman": [
{
"id": 29,
"value": "Ajman",
"selected": false
}
]
},
{
"Fujairah": [
{
"id": 30,
"value": "Fujairah",
"selected": false
}
]
},
{
"Ras Al Khaimah": [
{
"id": 31,
"value": "Ras Al Khaimah",
"selected": false
}
]
},
{
"Um Ul Quwein": [
{
"id": 32,
"value": "Umm Al Quwein",
"selected": false
}
]
},
{
"AbuDhabi": [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
},
{
"Sharjah": [
{
"id": 35,
"value": "Sharjah",
"selected": true
}
]
}
],
"picture": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png"
}
}
If you are in control of the API I'd highly suggest restructuring the response in such a way that you don't have any dynamic keys. It's much more conventional and also easier to work with. For your example you could change this part
{
"AbuDhabi": [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
}
to
{
"name" : "AbuDhabi",
"cities" : [
{
"id": 33,
"value": "Al Ain",
"selected": false
},
{
"id": 34,
"value": "Abu Dhabi",
"selected": false
}
]
}
And then maybe rename the outer "cities" to "emirates"
Use this JsontoDart to convert json response to Model.
You can use the following website to convert your JSON to POJO class -
https://javiercbk.github.io/json_to_dart/
Your Response class will be like this -
class Response{
String? code;
String? message;
Data? data;
Response({this.code, this.message, this.data});
Response.fromJson(Map<String, dynamic> json) {
code = json['code'];
message = json['message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data!.toJson();
}
return data;
}
}
class Data {
String? firstName;
String? lastName;
String? mobile1;
String? mobile2;
List<Cities>? cities;
String? picture;
Data(
{this.firstName,
this.lastName,
this.mobile1,
this.mobile2,
this.cities,
this.picture});
Data.fromJson(Map<String, dynamic> json) {
firstName = json['firstName'];
lastName = json['lastName'];
mobile1 = json['mobile1'];
mobile2 = json['mobile2'];
if (json['cities'] != null) {
cities = <Cities>[];
json['cities'].forEach((v) {
cities!.add(new Cities.fromJson(v));
});
}
picture = json['picture'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['firstName'] = this.firstName;
data['lastName'] = this.lastName;
data['mobile1'] = this.mobile1;
data['mobile2'] = this.mobile2;
if (this.cities != null) {
data['cities'] = this.cities!.map((v) => v.toJson()).toList();
}
data['picture'] = this.picture;
return data;
}
}
class Cities {
List<Dubai>? dubai;
List<Ajman>? ajman;
List<Fujairah>? fujairah;
List<RasAlKhaimah>? rasAlKhaimah;
List<UmUlQuwein>? umUlQuwein;
List<AbuDhabi>? abuDhabi;
List<Sharjah>? sharjah;
Cities(
{this.dubai,
this.ajman,
this.fujairah,
this.rasAlKhaimah,
this.umUlQuwein,
this.abuDhabi,
this.sharjah});
Cities.fromJson(Map<String, dynamic> json) {
if (json['Dubai'] != null) {
dubai = <Dubai>[];
json['Dubai'].forEach((v) {
dubai!.add(new Dubai.fromJson(v));
});
}
if (json['Ajman'] != null) {
ajman = <Ajman>[];
json['Ajman'].forEach((v) {
ajman!.add(new Ajman.fromJson(v));
});
}
if (json['Fujairah'] != null) {
fujairah = <Fujairah>[];
json['Fujairah'].forEach((v) {
fujairah!.add(new Fujairah.fromJson(v));
});
}
if (json['Ras Al Khaimah'] != null) {
rasAlKhaimah = <RasAlKhaimah>[];
json['Ras Al Khaimah'].forEach((v) {
rasAlKhaimah!.add(new RasAlKhaimah.fromJson(v));
});
}
if (json['Um Ul Quwein'] != null) {
umUlQuwein = <UmUlQuwein>[];
json['Um Ul Quwein'].forEach((v) {
umUlQuwein!.add(new UmUlQuwein.fromJson(v));
});
}
if (json['AbuDhabi'] != null) {
abuDhabi = <AbuDhabi>[];
json['AbuDhabi'].forEach((v) {
abuDhabi!.add(new AbuDhabi.fromJson(v));
});
}
if (json['Sharjah'] != null) {
sharjah = <Sharjah>[];
json['Sharjah'].forEach((v) {
sharjah!.add(new Sharjah.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.dubai != null) {
data['Dubai'] = this.dubai!.map((v) => v.toJson()).toList();
}
if (this.ajman != null) {
data['Ajman'] = this.ajman!.map((v) => v.toJson()).toList();
}
if (this.fujairah != null) {
data['Fujairah'] = this.fujairah!.map((v) => v.toJson()).toList();
}
if (this.rasAlKhaimah != null) {
data['Ras Al Khaimah'] =
this.rasAlKhaimah!.map((v) => v.toJson()).toList();
}
if (this.umUlQuwein != null) {
data['Um Ul Quwein'] = this.umUlQuwein!.map((v) => v.toJson()).toList();
}
if (this.abuDhabi != null) {
data['AbuDhabi'] = this.abuDhabi!.map((v) => v.toJson()).toList();
}
if (this.sharjah != null) {
data['Sharjah'] = this.sharjah!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Dubai {
int? id;
String? value;
bool? selected;
Dubai({this.id, this.value, this.selected});
Dubai.fromJson(Map<String, dynamic> json) {
id = json['id'];
value = json['value'];
selected = json['selected'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['value'] = this.value;
data['selected'] = this.selected;
return data;
}
}
I will really be happy for my question to be answered. i don't really know how to display all fetched data in a widget in flutter, i am only getting a single data.
This is how my Api response looks like
{
"cartItems": [
{
"product": {
"_id": "61b0a14b4ce2a01b914ab953",
"name": "Total1",
"size": "1kg",
"price": 700,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 2,
"price": 1400,
"type": "Refil",
"_id": "61c99030eebcb51e0f2a9a37"
},
{
"product": {
"_id": "61b0a18c4ce2a01b914ab959",
"name": "Total3",
"size": "3kg",
"price": 1800,
"isLPG": true
},
"vendor": "61a72ffd8eab8af9af4cc2e7",
"vendorName": "Total Energies",
"vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
"quantity": 1,
"price": 1800,
"type": "Refil",
"_id": "61c9903feebcb51e0f2a9a3d"
},
{
"product": {
"_id": "61aa6cb89b2046e5116fabc4",
"name": "NNPC",
"size": "15kg",
"price": 17000,
"isLPG": true
},
"vendor": "61bde0f39dfb5060de241d24",
"vendorName": "NNPC NG",
"vendorLogo": "/public/o7452L7tJ-nnpc-logo.png",
"quantity": 3,
"price": 51000,
"type": "Refil",
"_id": "61c99067eebcb51e0f2a9a51"
}
]
}
This is the generated model
class GetCartItems {
List<CartItems>? cartItems;
GetCartItems({this.cartItems});
GetCartItems.fromJson(Map<String, dynamic> json) {
if (json['cartItems'] != null) {
cartItems = <CartItems>[];
json['cartItems'].forEach((v) {
cartItems!.add(new CartItems.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.cartItems != null) {
data['cartItems'] = this.cartItems!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItems {
Product? product;
String? vendor;
String? vendorName;
String? vendorLogo;
int? quantity;
int? price;
String? type;
String? sId;
CartItems(
{this.product,
this.vendor,
this.vendorName,
this.vendorLogo,
this.quantity,
this.price,
this.type,
this.sId});
CartItems.fromJson(Map<String, dynamic> json) {
product =
json['product'] != null ? new Product.fromJson(json['product']) : null;
vendor = json['vendor'];
vendorName = json['vendorName'];
vendorLogo = json['vendorLogo'];
quantity = json['quantity'];
price = json['price'];
type = json['type'];
sId = json['_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.product != null) {
data['product'] = this.product!.toJson();
}
data['vendor'] = this.vendor;
data['vendorName'] = this.vendorName;
data['vendorLogo'] = this.vendorLogo;
data['quantity'] = this.quantity;
data['price'] = this.price;
data['type'] = this.type;
data['_id'] = this.sId;
return data;
}
}
class Product {
String? sId;
String? name;
String? size;
int? price;
bool? isLPG;
Product({this.sId, this.name, this.size, this.price, this.isLPG});
Product.fromJson(Map<String, dynamic> json) {
sId = json['_id'];
name = json['name'];
size = json['size'];
price = json['price'];
isLPG = json['isLPG'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.sId;
data['name'] = this.name;
data['size'] = this.size;
data['price'] = this.price;
data['isLPG'] = this.isLPG;
return data;
}
}
This is my controller class
class GCP extends GetxController {
var log = Logger();
FlutterSecureStorage storage = FlutterSecureStorage();
var getCartItems = GetCartItems();
#override
void onInit() {
// TODO: implement onInit
super.onInit();
getCartItems2();
}
void getCartItems2() async {
try {
String? token = await storage.read(key: "token");
String postURL = NetworkHandler().baseurl + ApiUtil.getCartItems;
Map<String, String> headers = {
"Authorization": "Bearer $token",
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8'
};
var response = await http.get(Uri.parse(postURL), headers: headers);
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
getCartItems = GetCartItems.fromJson(body);
update();
} else {
print('Something went wrong');
}
} catch (ex) {
print({ex, 'An error occured, cannot get cart items'});
}
}
}
This is my view, where i am displaying just a single data
import 'package:flutter/material.dart';
import 'package:gasapp_customer/src/controllers/GetCartPostController.dart';
import 'package:get/get.dart';
class GetCart extends StatelessWidget {
final gcp = Get.put(GCP());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child:
Text(gcp.getCartItems.cartItems![0].product!.name.toString()),
),
],
),
),
);
}
}
So my question is how can i display all the data from my response?
You can use ListView or GridView. If the widget that you will show will be same for all instances except the data provided to it, use GridView.builder.
for more info on ListView and GridView, go to:
https://api.flutter.dev/flutter/widgets/GridView-class.html
https://api.flutter.dev/flutter/widgets/ListView-class.html
I have problem with send request in Flutter ,I have this model :
import 'dart:convert';
List<Teams> teamsFromJson(String str) =>
List<Teams>.from(json.decode(str).map((x) => Teams.fromJson(x)));
String teamsToJson(List<Teams> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Teams {
Teams({
this.club,
this.price,
this.surename,
this.id,
this.league,
});
final club;
final price;
final surename;
final id;
final league;
factory Teams.fromJson(Map<String, dynamic> json) => Teams(
club: json["club"],
price: json["price"],
surename: json["surename"],
id: json["id"],
league: json["league"],
);
Map<String, dynamic> toJson() => {
"club": club,
"price": price,
"surename": surename,
"id": id,
"league": league,
};
}
I add initial values and update them in provider :
List<Teams> get teams => _teams;
List<Teams> _teams = [
Teams(club: "", price: 0, surename: "", id: "", league: ""),
Teams(club: "", price: 0, surename: "", id: "", league: ""),]
addToTeam(data, index) {
teams[index]=Team(club: data.club,
price: data.price,
surename: data.surname,
id: data.id,
league: data.leagueName);
}
and it works fine ,now I want to send the list teams as a request ,I add button and create method like this :
onPressed: () {
ApiService().saveTeam(teamsProvider.teams);
}
on ApiService I have this request :
class ApiService {
var url = 'http://10.0.2.2:8000/api/v1';
Future saveTeam(data) async {
var newurl = Uri.parse(url + '/send_test');
try {
var response = await http.post(newurl, body: data);
var result = jsonDecode(response.body);
print(result);
} catch (e) {
print('error : $e');
}
}
}
the api request is just return the request in laravel :
public function send_test(Request $request)
{
return $request;
}
as a result I get this error mesage : type 'Teams' is not a subtype of type 'int' in type cast
How can I solve this?
I solved it by myself ,I converted the Team list to Sting and decoded it with json:
class ApiService {
var url = 'http://10.0.2.2:8000/api/v1';
Future saveTeam(List<Teams> data) async {
var list = [];
data.map((e) {
list.add({
"club": e.club,
"price": e.price,
"surename": e.surename,
"id": e.id,
"league": e.league
});
}).toList();
try {
var newurl = Uri.parse(url + '/send_test');
var response = await http.post(newurl, body: jsonEncode(list));
var result = jsonDecode(response.body);
print(result);
} catch (e) {
print('error : $e');
}
}
}
then in api in laaravel/lumen received the json and decoded it again :
public function send_test(Request $request)
{
$result = json_decode($request->getContent(), true);
return $result;
}
As a learner, I'm trying to build my first project, however I'm facing a problem trying to parse this json object
{
"_id": 14080,
"ankamaId": 14080,
"name": "Amulette Séculaire",
"level": 200,
"type": "Amulette",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus-touch/www/game/items/200/1230.png",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/equipements/14080-amulette-seculaire",
"description": "Finalement, le secteur de la bijouterie n'a pas tellement évolué ces cent dernières années.",
"statistics": [
{
"Vitalité": {
"min": 251,
"max": 300
}
},
{
"Intelligence": {
"min": 61,
"max": 80
}
},
{
"Agilité": {
"min": 16,
"max": 25
}
},
{
"Sagesse": {
"min": 31,
"max": 40
}
},
{
"PA": {
"min": 1,
"max": null
}
},
{
"Prospection": {
"min": 16,
"max": 20
}
},
{
"Dommages Feu": {
"min": 8,
"max": 12
}
},
{
"Dommages Air": {
"min": 8,
"max": 12
}
},
{
"% Résistance Neutre": {
"min": 6,
"max": 8
}
},
{
"% Résistance Feu": {
"min": 6,
"max": 8
}
},
{
"Résistance Critiques": {
"min": 11,
"max": 15
}
}
],
}
Below is the way I'm parsing the object.
item_model.dart
#JsonSerializable(explicitToJson: true)
class Item {
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
factory Item.fromJson(Map<String,dynamic> data) => _$ItemFromJson(data);
Map<String,dynamic> toJson() => _$ItemToJson ( this);
}
#JsonSerializable()
class Statistic {
int max;
int min;
Statistic({
this.min,
this.max,
});
factory Statistic.fromJson(Map<String,dynamic> data) => _$StatisticFromJson(data);
Map<String,dynamic> toJson() => _$StatisticToJson(this);
}
item_model.g.dart
Item _$ItemFromJson(Map<String, dynamic> json) {
return Item(
id: json['id'] as int,
ankamaId: json['ankamaId'] as int,
name: json['name'] as String,
level: json['level'] as int,
type: json['type'] as String,
imgUrl: json['imgUrl'] as String,
url: json['url'] as String,
description: json['description'] as String,
statistics: (json['statistics'] as List)
?.map((e) => (e as Map<String, dynamic>)?.map(
(k, e) => MapEntry(
k,
e == null
? null
: Statistic.fromJson(e as Map<String, dynamic>)),
))
?.toList(),
);
}
Map<String, dynamic> _$ItemToJson(Item instance) => <String, dynamic>{
'id': instance.id,
'ankamaId': instance.ankamaId,
'name': instance.name,
'level': instance.level,
'type': instance.type,
'imgUrl': instance.imgUrl,
'url': instance.url,
'description': instance.description,
'statistics': instance.statistics
?.map((e) => e?.map((k, e) => MapEntry(k, e?.toJson())))
?.toList(),
};
Statistic _$StatisticFromJson(Map<String, dynamic> json) {
return Statistic(
min: json['min'] as int,
max: json['max'] as int,
);
}
Map<String, dynamic> _$StatisticToJson(Statistic instance) => <String, dynamic>{
'max': instance.max,
'min': instance.min,
};
Basically, what I want to do is show in a listview the max, and the min attribute of each element of the statistics list.
Thank you so much in advance.
Make sure the order of the model class, is same as that of the Api data. Also the data types used is compatible. Here errors can creep in. I don't see any other issues in the code
You can use this site for get your model from json, just copy and past
There's a brilliant tool (not the one that other ppl linked) that creates dart code for your JSON:
https://javiercbk.github.io/json_to_dart/
It helped me a ton when working with different APIs.
The dart code in your case would be this:
class myJson {
int iId;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Statistics> statistics;
myJson(
{this.iId,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics});
myJson.fromJson(Map<String, dynamic> json) {
iId = json['_id'];
ankamaId = json['ankamaId'];
name = json['name'];
level = json['level'];
type = json['type'];
imgUrl = json['imgUrl'];
url = json['url'];
description = json['description'];
if (json['statistics'] != null) {
statistics = new List<Statistics>();
json['statistics'].forEach((v) {
statistics.add(new Statistics.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.iId;
data['ankamaId'] = this.ankamaId;
data['name'] = this.name;
data['level'] = this.level;
data['type'] = this.type;
data['imgUrl'] = this.imgUrl;
data['url'] = this.url;
data['description'] = this.description;
if (this.statistics != null) {
data['statistics'] = this.statistics.map((v) => v.toJson()).toList();
}
return data;
}
}
class Statistics {
Vitalit vitalit;
Vitalit intelligence;
Vitalit agilit;
Vitalit sagesse;
PA pA;
Vitalit prospection;
Vitalit dommagesFeu;
Vitalit dommagesAir;
Vitalit rSistanceNeutre;
Vitalit rSistanceFeu;
Vitalit rSistanceCritiques;
Statistics(
{this.vitalit,
this.intelligence,
this.agilit,
this.sagesse,
this.pA,
this.prospection,
this.dommagesFeu,
this.dommagesAir,
this.rSistanceNeutre,
this.rSistanceFeu,
this.rSistanceCritiques});
Statistics.fromJson(Map<String, dynamic> json) {
vitalit = json['Vitalité'] != null
? new Vitalit.fromJson(json['Vitalité'])
: null;
intelligence = json['Intelligence'] != null
? new Vitalit.fromJson(json['Intelligence'])
: null;
agilit =
json['Agilité'] != null ? new Vitalit.fromJson(json['Agilité']) : null;
sagesse =
json['Sagesse'] != null ? new Vitalit.fromJson(json['Sagesse']) : null;
pA = json['PA'] != null ? new PA.fromJson(json['PA']) : null;
prospection = json['Prospection'] != null
? new Vitalit.fromJson(json['Prospection'])
: null;
dommagesFeu = json['Dommages Feu'] != null
? new Vitalit.fromJson(json['Dommages Feu'])
: null;
dommagesAir = json['Dommages Air'] != null
? new Vitalit.fromJson(json['Dommages Air'])
: null;
rSistanceNeutre = json['% Résistance Neutre'] != null
? new Vitalit.fromJson(json['% Résistance Neutre'])
: null;
rSistanceFeu = json['% Résistance Feu'] != null
? new Vitalit.fromJson(json['% Résistance Feu'])
: null;
rSistanceCritiques = json['Résistance Critiques'] != null
? new Vitalit.fromJson(json['Résistance Critiques'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.vitalit != null) {
data['Vitalité'] = this.vitalit.toJson();
}
if (this.intelligence != null) {
data['Intelligence'] = this.intelligence.toJson();
}
if (this.agilit != null) {
data['Agilité'] = this.agilit.toJson();
}
if (this.sagesse != null) {
data['Sagesse'] = this.sagesse.toJson();
}
if (this.pA != null) {
data['PA'] = this.pA.toJson();
}
if (this.prospection != null) {
data['Prospection'] = this.prospection.toJson();
}
if (this.dommagesFeu != null) {
data['Dommages Feu'] = this.dommagesFeu.toJson();
}
if (this.dommagesAir != null) {
data['Dommages Air'] = this.dommagesAir.toJson();
}
if (this.rSistanceNeutre != null) {
data['% Résistance Neutre'] = this.rSistanceNeutre.toJson();
}
if (this.rSistanceFeu != null) {
data['% Résistance Feu'] = this.rSistanceFeu.toJson();
}
if (this.rSistanceCritiques != null) {
data['Résistance Critiques'] = this.rSistanceCritiques.toJson();
}
return data;
}
}
class Vitalit {
int min;
int max;
Vitalit({this.min, this.max});
Vitalit.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
class PA {
int min;
Null max;
PA({this.min, this.max});
PA.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
You can use this tool which you just provide it with the JSON message and it will give you a class with all the variables and two function by which can parse the JSON message to the object or vice versa.
Steps:
insert a JSON message to the tool and give the class a name (don't forget to choose dart as the language)
create a new dart file and paste the class from the tool (let's assume the class name is Item)
Call final item = itemFromJson(jsonString); for parsing the JSON to the new object
Which then you can access the variables by via e.g. item.id
Edit:
so for your code, it will be:
item_model.dart
// To parse this JSON data, do
//
// final item = itemFromJson(jsonString);
import 'dart:convert';
Item itemFromJson(String str) => Item.fromJson(json.decode(str));
String itemToJson(Item data) => json.encode(data.toJson());
class Item {
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["_id"],
ankamaId: json["ankamaId"],
name: json["name"],
level: json["level"],
type: json["type"],
imgUrl: json["imgUrl"],
url: json["url"],
description: json["description"],
statistics: List<Map<String, Statistic>>.from(json["statistics"].map((x) => Map.from(x).map((k, v) => MapEntry<String, Statistic>(k, Statistic.fromJson(v))))),
);
Map<String, dynamic> toJson() => {
"_id": id,
"ankamaId": ankamaId,
"name": name,
"level": level,
"type": type,
"imgUrl": imgUrl,
"url": url,
"description": description,
"statistics": List<dynamic>.from(statistics.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
};
}
class Statistic {
Statistic({
this.min,
this.max,
});
int min;
int max;
factory Statistic.fromJson(Map<String, dynamic> json) => Statistic(
min: json["min"],
max: json["max"] == null ? null : json["max"],
);
Map<String, dynamic> toJson() => {
"min": min,
"max": max == null ? null : max,
};
}
You can access the variables via:
void main(){
String jsonString = "{\"_id\":14080,\"ankamaId\":14080,\"name\":\"Amulette S\u00e9culaire\",\"level\":200,\"type\":\"Amulette\",\"imgUrl\":\"https:\/\/s.ankama.com\/www\/static.ankama.com\/dofus-touch\/www\/game\/items\/200\/1230.png\",\"url\":\"https:\/\/www.dofus-touch.com\/fr\/mmorpg\/encyclopedie\/equipements\/14080-amulette-seculaire\",\"description\":\"Finalement, le secteur de la bijouterie n'a pas tellement \u00e9volu\u00e9 ces cent derni\u00e8res ann\u00e9es.\",\"statistics\":[{\"Vitalit\u00e9\":{\"min\":251,\"max\":300}},{\"Intelligence\":{\"min\":61,\"max\":80}},{\"Agilit\u00e9\":{\"min\":16,\"max\":25}},{\"Sagesse\":{\"min\":31,\"max\":40}},{\"PA\":{\"min\":1,\"max\":null}},{\"Prospection\":{\"min\":16,\"max\":20}},{\"Dommages Feu\":{\"min\":8,\"max\":12}},{\"Dommages Air\":{\"min\":8,\"max\":12}},{\"% R\u00e9sistance Neutre\":{\"min\":6,\"max\":8}},{\"% R\u00e9sistance Feu\":{\"min\":6,\"max\":8}},{\"R\u00e9sistance Critiques\":{\"min\":11,\"max\":15}}]}";
final device = deviceFromJson(jsonString);
print(device.id);
}