Flutter Rest Api Connection - How to get data? - json

I am a beginner in Flutter. I was trying to extract data from api. I got response like this
"status": "success",
"data": {
"integration": "051st93cqk90gqeyuikkkii1s5il5d3p",
"rootcategory": 2,
"slider": [
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787d5beb55.png",
"type": "category",
"id": "6",
"sort_order": "0.00"
},
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787fb306c7.png",
"type": "product",
"id": "5",
"sort_order": "1.00"
}
],
"noimg": "https://omanphone.smsoman.com/api/media/omanphone_icon.png",
"catimages": [
{
"id": "6",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b4857e526dd.jpg"
},
{
"id": "7",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d4142c0b.jpeg"
},
{
"id": "8",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d6440439.jpeg"
},
{
"id": "11",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d7c6974c.jpeg"
}
],
"store_id": 1,
"minimum_order_amount": null,
"stores": [
],
"currency": "OMR",
"payment_imgs": [
"https://omanphone.smsoman.com/api/media/payment_all.png",
"https://omanphone.smsoman.com/api/media/cards.png"
],
"voucher_cat": 151,
"whatsapp": "96812345678",
"celebrity_id": 0,
"register_otp": "0",
"mobile_formats": [
{
"webiste": "base",
"len": 8,
"country_code": "+968",
"country": "OM",
"id": 1
}
],
"cmspages": {
"faq": 73,
"about": 72,
"terms": 71,
"privacy": 70
},
"pay_method_imgs": [
"https://omanphone.smsoman.com/pub/media/itoons/payment-icon.png",
"https://omanphone.smsoman.com/pub/media/itoons/cod-icon.png"
]
}
}
Using app.quicktype.io - I converted this data to model.
like below.
// To parse this JSON data, do
//
// final slideData = slideDataFromJson(jsonString);
import 'dart:convert';
SlideData slideDataFromJson(String str) => SlideData.fromJson(json.decode(str));
String slideDataToJson(SlideData data) => json.encode(data.toJson());
class SlideData {
SlideData({
this.status,
this.data,
});
String status;
Data data;
factory SlideData.fromJson(Map<String, dynamic> json) => SlideData(
status: json["status"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": data.toJson(),
};
}
class Data {
Data({
this.integration,
this.rootcategory,
this.slider,
this.noimg,
this.catimages,
this.storeId,
this.minimumOrderAmount,
this.stores,
this.currency,
this.paymentImgs,
this.voucherCat,
this.whatsapp,
this.celebrityId,
this.registerOtp,
this.mobileFormats,
this.cmspages,
this.payMethodImgs,
});
String integration;
int rootcategory;
List<Slider> slider;
String noimg;
List<Catimage> catimages;
int storeId;
dynamic minimumOrderAmount;
List<dynamic> stores;
String currency;
List<String> paymentImgs;
int voucherCat;
String whatsapp;
int celebrityId;
String registerOtp;
List<MobileFormat> mobileFormats;
Cmspages cmspages;
List<String> payMethodImgs;
factory Data.fromJson(Map<String, dynamic> json) => Data(
integration: json["integration"],
rootcategory: json["rootcategory"],
slider: List<Slider>.from(json["slider"].map((x) => Slider.fromJson(x))),
noimg: json["noimg"],
catimages: List<Catimage>.from(json["catimages"].map((x) => Catimage.fromJson(x))),
storeId: json["store_id"],
minimumOrderAmount: json["minimum_order_amount"],
stores: List<dynamic>.from(json["stores"].map((x) => x)),
currency: json["currency"],
paymentImgs: List<String>.from(json["payment_imgs"].map((x) => x)),
voucherCat: json["voucher_cat"],
whatsapp: json["whatsapp"],
celebrityId: json["celebrity_id"],
registerOtp: json["register_otp"],
mobileFormats: List<MobileFormat>.from(json["mobile_formats"].map((x) => MobileFormat.fromJson(x))),
cmspages: Cmspages.fromJson(json["cmspages"]),
payMethodImgs: List<String>.from(json["pay_method_imgs"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"integration": integration,
"rootcategory": rootcategory,
"slider": List<dynamic>.from(slider.map((x) => x.toJson())),
"noimg": noimg,
"catimages": List<dynamic>.from(catimages.map((x) => x.toJson())),
"store_id": storeId,
"minimum_order_amount": minimumOrderAmount,
"stores": List<dynamic>.from(stores.map((x) => x)),
"currency": currency,
"payment_imgs": List<dynamic>.from(paymentImgs.map((x) => x)),
"voucher_cat": voucherCat,
"whatsapp": whatsapp,
"celebrity_id": celebrityId,
"register_otp": registerOtp,
"mobile_formats": List<dynamic>.from(mobileFormats.map((x) => x.toJson())),
"cmspages": cmspages.toJson(),
"pay_method_imgs": List<dynamic>.from(payMethodImgs.map((x) => x)),
};
}
class Catimage {
Catimage({
this.id,
this.img,
});
String id;
String img;
factory Catimage.fromJson(Map<String, dynamic> json) => Catimage(
id: json["id"],
img: json["img"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
};
}
class Cmspages {
Cmspages({
this.faq,
this.about,
this.terms,
this.privacy,
});
int faq;
int about;
int terms;
int privacy;
factory Cmspages.fromJson(Map<String, dynamic> json) => Cmspages(
faq: json["faq"],
about: json["about"],
terms: json["terms"],
privacy: json["privacy"],
);
Map<String, dynamic> toJson() => {
"faq": faq,
"about": about,
"terms": terms,
"privacy": privacy,
};
}
class MobileFormat {
MobileFormat({
this.webiste,
this.len,
this.countryCode,
this.country,
this.id,
});
String webiste;
int len;
String countryCode;
String country;
int id;
factory MobileFormat.fromJson(Map<String, dynamic> json) => MobileFormat(
webiste: json["webiste"],
len: json["len"],
countryCode: json["country_code"],
country: json["country"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"webiste": webiste,
"len": len,
"country_code": countryCode,
"country": country,
"id": id,
};
}
class Slider {
Slider({
this.image,
this.type,
this.id,
this.sortOrder,
});
String image;
String type;
String id;
String sortOrder;
factory Slider.fromJson(Map<String, dynamic> json) => Slider(
image: json["image"],
type: json["type"],
id: json["id"],
sortOrder: json["sort_order"],
);
Map<String, dynamic> toJson() => {
"image": image,
"type": type,
"id": id,
"sort_order": sortOrder,
};
}
Future<void> getDataFromInternet() async {
//getting data from Internet
try {
var response =
await http.get('https://omanphone.smsoman.com/api/configuration');
} catch (error) {
print(error);
}
}
I just want to get slider images. So What did I need to do in above code?
I used http package and var response =
await http.get('https://omanphone.smsoman.com/api/configuration'); did this. But I don't know how to extract it.

Related

i cant figure out why this error type 'Null' is not a subtype of type 'int' in type cast

Flutter 3.3.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b8f7f1f986 (hace 2 semanas) • 2022-11-23 06:43:51 +0900
Engine • revision 8f2221fbef
Tools • Dart 2.18.5 • DevTools 2.15.0
hello, best regards and I hope you are well, I have spent the last few hours trying to solve the error in the title of the issue, and I have not been able to, could you explain to me a way to solve it, I have attached the model that I am using and the response of the request to an api, thank you very much in advance
base_response_model.dart
import 'package:json_annotation/json_annotation.dart';
part 'base_response_model.g.dart';
#JsonSerializable()
class BaseResponseModel {
final int page;
#JsonKey(name: 'page_size')
final int pageSize;
final int total;
final int pages;
#JsonKey(name: 'prev_page', defaultValue: 0)
final dynamic prevPage;
#JsonKey(name: 'next_page', defaultValue: 0)
final dynamic nextPage;
BaseResponseModel({
required this.page,
required this.pageSize,
required this.total,
required this.pages,
required this.prevPage,
required this.nextPage,
});
factory BaseResponseModel.fromJson(Map<String, dynamic> json) =>
_$BaseResponseModelFromJson(json);
Map<String, dynamic> toJson() => _$BaseResponseModelToJson(this);
}
get_municipalities_by_province_response_model.dart
import 'package:delivery/app/data/models/andariego/andariego_models/municipality_model.dart';
import 'package:delivery/app/data/models/andariego/andariego_response_models/base_response_model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'get_municipalities_by_province_response_model.g.dart';
#JsonSerializable()
class GetMunicipalitiesByProvinceResponseModel extends BaseResponseModel {
final List<MunicipalityModel> data;
GetMunicipalitiesByProvinceResponseModel({
required super.page,
required super.pageSize,
required super.total,
required super.pages,
required super.prevPage,
required super.nextPage,
required this.data,
});
factory GetMunicipalitiesByProvinceResponseModel.fromJson(
Map<String, dynamic> json) =>
_$GetMunicipalitiesByProvinceResponseModelFromJson(json);
#override
Map<String, dynamic> toJson() =>
_$GetMunicipalitiesByProvinceResponseModelToJson(this);
}
municipality_model.dart
import 'package:delivery/app/data/models/andariego/andariego_models/base_andariego_model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'municipality_model.g.dart';
#JsonSerializable()
class MunicipalityModel extends BaseAndariegoModel {
final int parent;
MunicipalityModel({
required super.id,
required super.name,
required this.parent,
});
factory MunicipalityModel.fromJson(Map<String, dynamic> json) =>
_$MunicipalityModelFromJson(json);
#override
Map<String, dynamic> toJson() => _$MunicipalityModelToJson(this);
}
api_response.json
{
"page": 1,
"page_size": 20,
"total": 11,
"pages": 1,
"prev_page": null,
"next_page": null,
"data": [
{
"id": 1188,
"name": "Consolación del Sur",
"parent": 58
},
{
"id": 1132,
"name": "Guane",
"parent": 58
},
{
"id": 1125,
"name": "La Palma",
"parent": 58
},
{
"id": 1124,
"name": "Los Palacios",
"parent": 58
},
{
"id": 1186,
"name": "Mantua",
"parent": 58
},
{
"id": 1182,
"name": "Minas de Matahambre",
"parent": 58
},
{
"id": 1189,
"name": "Pinar del Rio",
"parent": 58
},
{
"id": 1165,
"name": "Sandino",
"parent": 58
},
{
"id": 1133,
"name": "San Juan y Martínez",
"parent": 58
},
{
"id": 1187,
"name": "San Luis",
"parent": 58
},
{
"id": 1169,
"name": "Viñales",
"parent": 58
}
]
}
Generated code
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'base_response_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BaseResponseModel _$BaseResponseModelFromJson(Map<String, dynamic> json) =>
BaseResponseModel(
page: json['page'] as int,
pageSize: json['page_size'] as int,
total: json['total'] as int,
pages: json['pages'] as int,
prevPage: json['prev_page'] ?? 0,
nextPage: json['next_page'] ?? 0,
);
Map<String, dynamic> _$BaseResponseModelToJson(BaseResponseModel instance) =>
<String, dynamic>{
'page': instance.page,
'page_size': instance.pageSize,
'total': instance.total,
'pages': instance.pages,
'prev_page': instance.prevPage,
'next_page': instance.nextPage,
};
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'get_municipalities_by_province_response_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GetMunicipalitiesByProvinceResponseModel
_$GetMunicipalitiesByProvinceResponseModelFromJson(
Map<String, dynamic> json) =>
GetMunicipalitiesByProvinceResponseModel(
page: json['page'] as int,
pageSize: json['page_size'] as int,
total: json['total'] as int,
pages: json['pages'] as int,
prevPage: json['prev_page'] ?? 0,
nextPage: json['next_page'] ?? 0,
data: (json['data'] as List<dynamic>)
.map((e) => MunicipalityModel.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$GetMunicipalitiesByProvinceResponseModelToJson(
GetMunicipalitiesByProvinceResponseModel instance) =>
<String, dynamic>{
'page': instance.page,
'page_size': instance.pageSize,
'total': instance.total,
'pages': instance.pages,
'prev_page': instance.prevPage,
'next_page': instance.nextPage,
'data': instance.data,
};
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'municipality_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MunicipalityModel _$MunicipalityModelFromJson(Map<String, dynamic> json) =>
MunicipalityModel(
id: json['id'] as int,
name: json['name'] as String,
parent: json['parent'] as int,
);
Map<String, dynamic> _$MunicipalityModelToJson(MunicipalityModel instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'parent': instance.parent,
};
I am using flutter, null safety
It looks like a field is missing (or null) in the JSON causing that problem. The line number should point you to the right spot!

Not able to parse json data in flutter

I am not able to parse below mentioned json data in flutter.
[
{
"id": 96,
"name": "Entertainment",
"link": "https://thehappilyeverafter.in/listing-category/entertainment/",
"image": "https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg",
"children": [
{
"child_id": 114,
"child_name": "DJs",
"child_link": "https://thehappilyeverafter.in/listing-category/djs/"
},
{
"child_id": 117,
"child_name": "Live Music",
"child_link": "https://thehappilyeverafter.in/listing-category/live-music/"
},
{
"child_id": 115,
"child_name": "Wedding Choreographer",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-choreographer/"
},
{
"child_id": 116,
"child_name": "Wedding Entertainment",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-entertainment/"
}
]
}
]`
import 'dart:convert';
List<Root> rootFromJson(String str) => List<Root>.from(json.decode(str).map((x) => Root.fromJson(x)));
String rootToJson(List<Root> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Root {
Root({
this.id,
this.name,
this.link,
this.image,
this.children,
});
int id;
String name;
String link;
String image;
List<Children> children;
factory Root.fromJson(Map<String, dynamic> json) => Root(
id: json["id"],
name: json["name"],
link: json["link"],
image: json["image"] == null ? null : json["image"],
children: List<Children>.from(json["children"].map((x) => Children.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"link": link,
"image": image == null ? null : image,
"children": List<dynamic>.from(children.map((x) => x.toJson())),
};
}
class Children {
Children({
this.childId,
this.childName,
this.childLink,
});
int childId;
String childName;
String childLink;
factory Children.fromJson(Map<String, dynamic> json) => Children(
childId: json["child_id"],
childName: json["child_name"],
childLink: json["child_link"],
);
Map<String, dynamic> toJson() => {
"child_id": childId,
"child_name": childName,
"child_link": childLink,
};
}
[Getting this error][1]
`
type 'List' is not a subtype of type 'Children'
Since your json is a list, you should loop through it:
final List<Root> roots = yourJson.map((element) {
return Root.fromJson(element);
}).toList();
print(roots.first.image);
//https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg

Flutter: Join specific field of JSON file together to become a list itself

I have a json file with a list of different types of data.
I wanted to join the "name" field of all attractions of each city together as a list.
The expected result after joining, for example for Longo city will be like this:
Attraction1
Attraction2
The data in JSON file is structured like this:
{
"city": "London",
"attractions": [
{
"name": "Attraction1",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction2",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Hong Kong",
"attractions": [
{
"name": "Attraction3",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction4",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Cario",
"attractions": [
{
"name": "Attraction5",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction6",
"localrank": 4,
"intrank": 5
}
]
}
]
I used the following code, but I get an error :
cities.attractions.name.join("\n")
Json model class is this:
List<Cities> citiesFromJson(String str) =>
List<Cities>.from(json.decode(str).map((x) => Cities.fromJson(x)));
String citiesToJson(List<Cities> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Cities {
Cities({
this.city,
this.attractions,
});
String city;
List<Attraction> attractions;
factory Cities.fromRawJson(String str) => Cities.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Cities.fromJson(Map<String, dynamic> json) => Cities(
city: json["city"],
attractions: List<Attraction>.from(
json["attractions"].map((x) => Attraction.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"city": city,
"attractions": List<dynamic>.from(attractions.map((x) => x.toJson())),
};
}
class Attraction {
Attraction({
this.name,
this.localrank,
this.intrank,
});
String name;
int localrank;
int intrank;
factory Attraction.fromRawJson(String str) =>
Attraction.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Attraction.fromJson(Map<String, dynamic> json) => Attraction(
name: json["name"],
localrank: json["localrank"],
intrank: json["intrank"],
);
Map<String, dynamic> toJson() => {
"name": name,
"localrank": localrank,
"intrank": intrank,
};
}
And this also calling json file:
Future<String> fetchData() async {
String data =
await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = json.decode(data);
print('$jsonResult oop');
this.setState(() {
jsonResult.forEach(
(element) => Globals.citylist.add(new Cities.fromJson(element)));
});
return "Success!";
}
Something like that should work:
import 'dart:convert';
var data = """ [{
"city": "London",
"attractions": [
{
"name": "Attraction1",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction2",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Hong Kong",
"attractions": [
{
"name": "Attraction3",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction4",
"localrank": 4,
"intrank": 5
}
]
},
{
"city": "Cario",
"attractions": [
{
"name": "Attraction5",
"localrank": 10,
"intrank": 4
},
{
"name": "Attraction6",
"localrank": 4,
"intrank": 5
}
]
}
] """;
List<Cities> citiesFromJson(String str) =>
List<Cities>.from(json.decode(str).map((x) => Cities.fromJson(x)));
String citiesToJson(List<Cities> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Cities {
Cities({
this.city,
this.attractions,
});
String city;
List<Attraction> attractions;
factory Cities.fromRawJson(String str) => Cities.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Cities.fromJson(Map<String, dynamic> json) => Cities(
city: json["city"],
attractions: List<Attraction>.from(
json["attractions"].map((x) => Attraction.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"city": city,
"attractions": List<dynamic>.from(attractions.map((x) => x.toJson())),
};
}
class Attraction {
Attraction({
this.name,
this.localrank,
this.intrank,
});
String name;
int localrank;
int intrank;
factory Attraction.fromRawJson(String str) =>
Attraction.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Attraction.fromJson(Map<String, dynamic> json) => Attraction(
name: json["name"],
localrank: json["localrank"],
intrank: json["intrank"],
);
Map<String, dynamic> toJson() => {
"name": name,
"localrank": localrank,
"intrank": intrank,
};
}
class Globals {
static List<Cities> citylist = [];
}
Future<String> fetchData() async {
// String data =
// await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = json.decode(data);
print('$jsonResult oop');
// this.setState(() {
jsonResult.forEach(
(element) => Globals.citylist.add(new Cities.fromJson(element)));
// });
var result = getAttractionsByCity('London');
print(result.join('\n'));
return "Success!";
}
List<String> getAttractionsByCity(String value) {
var result = <String>[];
for (final city in Globals.citylist) {
if (city.city == value) {
final attractions = city.attractions;
for (final attraction in attractions) {
result.add(attraction.name);
}
}
}
return result;
}
void main() async {
await fetchData();
}
It's a working example. You can copy and paste this code to HTTP://dartpad.dev and run it to see the result.

NoSuchMethodError: The method 'map' was called on null

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (19718): Receiver: null
E/flutter (19718): Tried calling: map(Closure: (dynamic) => SeriesNo)
I tried json_annotation and json Serieizable but don't work.According my model one.json is ok.but two.json is reques error happen as title.How to solve.I known series no is error but i have no idea how to solve.
This is one.json
{
"bookDetail": {
"title": "aaa",
"author": "aaa",
"image": "https://",
"text": "aaa",
"series_no": [
{
"id": 2
}
],
"created_at": "2019-08-27 15:19:10"
}
}
This is two.json
{
"bookDetail": {
"title": "Test",
"author": "TEst",
"image": "https:/riv19q9x.png",
"text": "Test",
"series_no": null,
"created_at": "2019-08-27 15:13:56"
}
}
This is detail.model using bloc flutter
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) =>
new BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
#JsonSerializable(nullable: true)
class BookDetail {
String title;
String author;
String image;
String text;
List<SeriesNo> seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => new BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: new List<SeriesNo>.from(
json["series_no"].map((x) => SeriesNo.fromJson(x))),
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": new List<dynamic>.from(seriesNo.map((x) => x.toJson())),
"created_at": createdAt.toIso8601String(),
};
}
#JsonSerializable(nullable: true)
class SeriesNo {
int id;
SeriesNo({
this.id,
});
factory SeriesNo.fromJson(Map<String, dynamic> json) => new SeriesNo(
id: json["id"],
);
Map<String, dynamic> toJson() => {
"id": id,
};
}
Try to verify if is not null before:
seriesNo: json["series_no"] != null ? new List<SeriesNo>.from( json["series_no"].map((x) => SeriesNo.fromJson(x))) : List<SeriesNo>().
This is answer for my question.Crd #Stel
try placing seriesNo as dynamic and placing the remaining fields
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) => BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
class BookDetail {
String title;
String author;
String image;
String text;
dynamic seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: json["series_no"],
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": seriesNo,
"created_at": createdAt.toIso8601String(),
};
}
If it's a List and a double value, how can it be written even if it's correct? I got this problem. Please see my link.Link Linkclass
Food _$FoodFromJson(Map<String, dynamic> json) => Food(
ingredient: (json['ingredient'] as List<dynamic>)
.map((e) => e as String)
.toList(),
quantity:
(json['quantity'] as List<dynamic>).map((e) => e as String).toList(),
uom: (json['uom'] as List<dynamic>).map((e) => e as String).toList(),
step: (json['step'] as List<dynamic>).map((e) => e as String).toList(),
);

Flutter: How to map a Dictionary? Make dropdown options via dictionary

I need some help in flutter data mapping. I have a JSON object that is returning some fields. I have to create a form depending on those fields. The issue that I am facing right now is that I cannot map the JSON dictionary to my dropdown list.
So basically I want to create a dropdown options that are in form_field_options of my json.
Here is a code sample of what I am trying to active, JSON return by my server is:
{
"status": "200",
"request": "0",
"message": "Success",
"data": {
"assetID": "155",
"assetTitle": "TPO",
"formTitle": "Roof Asset",
"preFields": [
{
"unique_id": "uid_201955451258",
"form_name": "General Overview",
"form_field_type": "100",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201939764918",
"form_name": "Asset ID",
"form_field_type": "5",
"form_field_required": "1",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201789014253",
"form_name": "Facility ID",
"form_field_type": "5",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201996716360",
"form_name": "Location",
"form_field_type": "19",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201941758250",
"form_name": "Developed Area Type",
"form_field_type": "1",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_options": {
"1": {
"opt_name": "Suburban",
"opt_weightage": ""
},
"2": {
"opt_name": "Urban",
"opt_weightage": ""
},
"3": {
"opt_name": "Rural",
"opt_weightage": ""
}
},
"form_field_disabledrow": "0"
}
]
}
}
And here is my form class (auto generate class form quicktype) is:
// To parse this JSON data, do
//
// final form = formFromJson(jsonString);
import 'dart:convert';
Form formFromJson(String str) => Form.fromJson(json.decode(str));
String formToJson(Form data) => json.encode(data.toJson());
class Form {
String status;
String request;
String message;
Data data;
Form({
this.status,
this.request,
this.message,
this.data,
});
factory Form.fromJson(Map<String, dynamic> json) => new Form(
status: json["status"],
request: json["request"],
message: json["message"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"request": request,
"message": message,
"data": data.toJson(),
};
}
class Data {
String assetId;
String assetTitle;
String formTitle;
List<PreField> preFields;
Data({
this.assetId,
this.assetTitle,
this.formTitle,
this.preFields,
});
factory Data.fromJson(Map<String, dynamic> json) => new Data(
assetId: json["assetID"],
assetTitle: json["assetTitle"],
formTitle: json["formTitle"],
preFields: new List<PreField>.from(json["preFields"].map((x) => PreField.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"assetID": assetId,
"assetTitle": assetTitle,
"formTitle": formTitle,
"preFields": new List<dynamic>.from(preFields.map((x) => x.toJson())),
};
}
class PreField {
String uniqueId;
String formName;
String formFieldType;
String formFieldRequired;
String formFieldPrivate;
String formFieldDuplicateTimes;
String formFieldDisabledrow;
Map<String, FormFieldOption> formFieldOptions;
PreField({
this.uniqueId,
this.formName,
this.formFieldType,
this.formFieldRequired,
this.formFieldPrivate,
this.formFieldDuplicateTimes,
this.formFieldDisabledrow,
this.formFieldOptions,
});
factory PreField.fromJson(Map<String, dynamic> json) => new PreField(
uniqueId: json["unique_id"],
formName: json["form_name"],
formFieldType: json["form_field_type"],
formFieldRequired: json["form_field_required"],
formFieldPrivate: json["form_field_private"],
formFieldDuplicateTimes: json["form_field_duplicate_times"],
formFieldDisabledrow: json["form_field_disabledrow"],
formFieldOptions: json["form_field_options"] == null ? null : new Map.from(json["form_field_options"]).map((k, v) => new MapEntry<String, FormFieldOption>(k, FormFieldOption.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"unique_id": uniqueId,
"form_name": formName,
"form_field_type": formFieldType,
"form_field_required": formFieldRequired,
"form_field_private": formFieldPrivate,
"form_field_duplicate_times": formFieldDuplicateTimes,
"form_field_disabledrow": formFieldDisabledrow,
"form_field_options": formFieldOptions == null ? null : new Map.from(formFieldOptions).map((k, v) => new MapEntry<String, dynamic>(k, v.toJson())),
};
}
class FormFieldOption {
String optName;
String optWeightage;
FormFieldOption({
this.optName,
this.optWeightage,
});
factory FormFieldOption.fromJson(Map<String, dynamic> json) => new FormFieldOption(
optName: json["opt_name"],
optWeightage: json["opt_weightage"],
);
Map<String, dynamic> toJson() => {
"opt_name": optName,
"opt_weightage": optWeightage,
};
}
Now when I try to apply loop or mapping on my options list (Which runs perfectly if its list) like this, It will not map it:
Column(
children: <Widget>[
FormBuilderDropdown(
attribute: item.uniqueId,
decoration:
InputDecoration(labelText: item.formName),
// initialValue: 'Male',
hint: Text(item.formName),
// validators: [
// FormBuilderValidators.required()
// ],
items: item.formFieldOptions.map((option) => DropdownMenuItem(
value: option,
child: Text("$option.optName")))
.toList(),
),
],
),
It throws me error that:
> The argument type '(String) → MapEntry<?, ?>' can't be assigned to the
> parameter type '(String, FormFieldOption) → MapEntry<dynamic,
> dynamic>'.dart(argument_type_not_assignable)
Please help or let me know what am I doing wrong. How can I make those dropdown options.
Thanks in advance
You sould try to map with the correct lambda signature (k, v) =>
items: item.formFieldOptions.map((key, option) => DropdownMenuItem(
value: key,
child: Text("${option.optName}"),
)
).toList()