How to send array of data in post request in flutter - flutter

In my flutter code I need to send array of objects on a http post request, but it can not be encoded as json object.
here is my flutter class to send data to the service
class JobCreateRequestModel {
String? category;
String? title;
String? description;
String? latitude;
String? longitude;
List<Job.Images>? images;
JobCreateRequestModel(
{this.category,
this.title,
this.description,
this.latitude,
this.longitude,
this.images});
Map<String?, dynamic> toJson() {
Map<String?, dynamic> map = {
category: category,
title: title,
description: description,
latitude: latitude,
longitude: longitude,
images: images
};
return map;
}
}
class Images {
String? id;
String? name;
String? type;
String? url;
double? size;
String? uploadedAt;
Images(Images item,
{this.id, this.name, this.type, this.url, this.size, this.uploadedAt});
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['type'] = this.type;
data['url'] = this.url;
data['size'] = this.size;
data['uploadedAt'] = this.uploadedAt;
return data;
}
}
This class should be created this kind of object
{
"category": "1604173705548",
"title": "title",
"description": "For See More, We need to calculate how much text can be inserted in a given number of lines or Space.",
"latitude": "23.00343",
"longitude": "23.00343",
"images": [
{
"id": "16114286013370",
"name": "200820_4.jpeg",
"type": ".jpeg",
"url": "https://sample.com/job_images/16114286013370.jpeg",
"size": "72.369",
"uploadedAt": "1611428601337"
}
]
}
I have used form to get the required data to the model and need to convert it in to json encodable object. Any suggestion would be highly appreciated.

I used your JSON format to generate the model class :
import 'dart:convert';
JobCreateRequestModel jobCreateRequestModelFromJson(String str) => JobCreateRequestModel.fromJson(json.decode(str));
String jobCreateRequestModelToJson(JobCreateRequestModel data) => json.encode(data.toJson());
class JobCreateRequestModel {
JobCreateRequestModel({
this.category,
this.title,
this.description,
this.latitude,
this.longitude,
this.images,
});
String category;
String title;
String description;
String latitude;
String longitude;
List<Image> images;
factory JobCreateRequestModel.fromJson(Map<String, dynamic> json) => JobCreateRequestModel(
category: json["category"],
title: json["title"],
description: json["description"],
latitude: json["latitude"],
longitude: json["longitude"],
images: List<Image>.from(json["images"].map((x) => Image.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"title": title,
"description": description,
"latitude": latitude,
"longitude": longitude,
"images": List<dynamic>.from(images.map((x) => x.toJson())),
};
}
class Image {
Image({
this.id,
this.name,
this.type,
this.url,
this.size,
this.uploadedAt,
});
String id;
String name;
String type;
String url;
String size;
String uploadedAt;
factory Image.fromJson(Map<String, dynamic> json) => Image(
id: json["id"],
name: json["name"],
type: json["type"],
url: json["url"],
size: json["size"],
uploadedAt: json["uploadedAt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"type": type,
"url": url,
"size": size,
"uploadedAt": uploadedAt,
};
}
What you can do is simply while posting data to server use :
jobCreateRequestModelToJson(yourClassObject)
This should work! Hope this is what you wanted

Related

how to create an entity based on a model?

Tell me please. At first, I decided to make a simple application, but now I want to use a clean architecture and I need to know what my HomeEntity should look like. I have a model, it was generated by the site. And I also need all the fields of my model in my entity.
I can’t just use JUST all the fields that I described there, because some of them need to be “entered”
Here is my model -
// To parse this JSON data, do
//
// final plan = planFromJson(jsonString);
import 'dart:convert';
Plan planFromJson(String str) => Plan.fromJson(json.decode(str));
String planToJson(Plan data) => json.encode(data.toJson());
class Plan {
Plan({
required this.data,
required this.meta,
});
List<Datum> data;
Meta meta;
factory Plan.fromJson(Map<String, dynamic> json) => Plan(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class Datum {
Datum({
required this.id,
required this.attributes,
});
int id;
DatumAttributes attributes;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
attributes: DatumAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DatumAttributes {
DatumAttributes({
required this.header,
required this.description,
required this.added,
required this.createdAt,
required this.updatedAt,
required this.publishedAt,
required this.image,
});
String header;
String description;
bool added;
DateTime createdAt;
DateTime updatedAt;
DateTime publishedAt;
Image image;
factory DatumAttributes.fromJson(Map<String, dynamic> json) => DatumAttributes(
header: json["header"],
description: json["description"],
added: json["added"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
publishedAt: DateTime.parse(json["publishedAt"]),
image: Image.fromJson(json["image"]),
);
Map<String, dynamic> toJson() => {
"header": header,
"description": description,
"added": added,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"publishedAt": publishedAt.toIso8601String(),
"image": image.toJson(),
};
}
class Image {
Image({
required this.data,
});
Data data;
factory Image.fromJson(Map<String, dynamic> json) => Image(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
required this.id,
required this.attributes,
});
int id;
DataAttributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
attributes: DataAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DataAttributes {
DataAttributes({
required this.name,
required this.alternativeText,
required this.caption,
required this.width,
required this.height,
required this.formats,
required this.hash,
required this.ext,
required this.mime,
required this.size,
required this.url,
required this.previewUrl,
required this.provider,
required this.providerMetadata,
required this.createdAt,
required this.updatedAt,
});
String name;
dynamic alternativeText;
dynamic caption;
int width;
int height;
Formats formats;
String hash;
Ext? ext;
Mime? mime;
double size;
String url;
dynamic previewUrl;
String provider;
dynamic providerMetadata;
DateTime createdAt;
DateTime updatedAt;
factory DataAttributes.fromJson(Map<String, dynamic> json) => DataAttributes(
name: json["name"],
alternativeText: json["alternativeText"],
caption: json["caption"],
width: json["width"],
height: json["height"],
formats: Formats.fromJson(json["formats"]),
hash: json["hash"],
ext: extValues.map[json["ext"]],
mime: mimeValues.map[json["mime"]],
size: json["size"].toDouble(),
url: json["url"],
previewUrl: json["previewUrl"],
provider: json["provider"],
providerMetadata: json["provider_metadata"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"alternativeText": alternativeText,
"caption": caption,
"width": width,
"height": height,
"formats": formats.toJson(),
"hash": hash,
"ext": extValues.reverse[ext],
"mime": mimeValues.reverse[mime],
"size": size,
"url": url,
"previewUrl": previewUrl,
"provider": provider,
"provider_metadata": providerMetadata,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
enum Ext { JPG }
final extValues = EnumValues({
".jpg": Ext.JPG
});
class Formats {
Formats({
required this.thumbnail,
required this.small,
required this.medium,
required this.large,
});
Small thumbnail;
Small small;
Small? medium;
Small? large;
factory Formats.fromJson(Map<String, dynamic> json) => Formats(
thumbnail: Small.fromJson(json["thumbnail"]),
small: Small.fromJson(json["small"]),
medium: json["medium"] == null ? null : Small.fromJson(json["medium"]),
large: json["large"] == null ? null : Small.fromJson(json["large"]),
);
Map<String, dynamic> toJson() => {
"thumbnail": thumbnail.toJson(),
"small": small.toJson(),
"medium": medium == null ? null : medium?.toJson(),
"large": large == null ? null : large?.toJson(),
};
}
class Small {
Small({
required this.name,
required this.hash,
required this.ext,
required this.mime,
required this.path,
required this.width,
required this.height,
required this.size,
required this.url,
});
String name;
String hash;
Ext? ext;
Mime? mime;
dynamic path;
int width;
int height;
double size;
String url;
factory Small.fromJson(Map<String, dynamic> json) => Small(
name: json["name"],
hash: json["hash"],
ext: extValues.map[json["ext"]],
mime: mimeValues.map[json["mime"]],
path: json["path"],
width: json["width"],
height: json["height"],
size: json["size"].toDouble(),
url: json["url"],
);
Map<String, dynamic> toJson() => {
"name": name,
"hash": hash,
"ext": extValues.reverse[ext],
"mime": mimeValues.reverse[mime],
"path": path,
"width": width,
"height": height,
"size": size,
"url": url,
};
}
enum Mime { IMAGE_JPEG }
final mimeValues = EnumValues({
"image/jpeg": Mime.IMAGE_JPEG
});
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
class EnumValues<T> {
Map<String, T> map;
late 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;
}
}
It will be cool if you help me create an entity for this model and explain the principle of how I can create it myself
define your class and its fields like this case:
class MobileViewModel {
final String countryCallingCode;
final String mobileNumber;
}
define the constructor of your class like this:
MobileViewModel({
required this.countryCallingCode,
required this.mobileNumber,
});
if you needs optional fields just remove requierd keyword and make your fields nullable.
then write fromJson method as a factory constructor.
(factory constructor returns an instance of your class from a json.)
factory MobileViewModel.fromJson(final Map<String, dynamic> json) =>
MobileViewModel(
countryCallingCode: json['countryCallingCode'],
mobileNumber: json['mobileNumber'],
);

How to POST raw json using retrofit Flutter

static const signUp = "${apiVerion}auth/signup";
#POST(ApiConstant.signUp)
Future<BaseObjectResponse> signUp(#Body() SignUpParams params);
{
"fullname": "abc",
"phone": "0999999999",
"password": "123456",
"type": 1,
"agentName": "ABC",
"countryId": "hcm",
"address": "hcm",
"referralCode": "123"
}
import 'package:json_annotation/json_annotation.dart';
part 'sign_up_params.g.dart';
#JsonSerializable()
class SignUpParams {
#JsonKey(name: 'fullname')
String? fullname;
#JsonKey(name: 'phone')
String? phone;
#JsonKey(name: 'password')
String? password;
#JsonKey(name: 'type')
String? type;
#JsonKey(name: 'agentName')
String? agentName;
#JsonKey(name: 'countryId')
String? countryId;
#JsonKey(name: 'address')
String? address;
#JsonKey(name: 'referralCode')
String? referralCode;
SignUpParams({
this.fullname,
this.phone,
this.password,
this.type,
this.agentName,
this.countryId,
this.address,
this.referralCode,
});
factory SignUpParams.fromJson(Map<String, dynamic> json) {
return _$SignUpParamsFromJson(json);
}
Map<String, dynamic> toJson() => _$SignUpParamsToJson(this);
}
Update work.

best practice to fetch data from api in flutter

i am working on news application (full-stack) and i am using strapi for back-end and flutter as front-end and i wondering if there is some standard or pattern to fetch data from api in flutter (or any front-end )
cuz there are many methods can be used but i am asking for best approach ,
for example i can fetch list of data with it's related entities to the front end ( with http://localhost:1337/api/news-items?populate=*
but the problem with this approach is
if any related entity is null an exception occurred [thank for
null-safety ]
the model or dto become very complex that leads to get god class
class NewsItemList {
NewsItemList({
required this.data,
required this.meta,
});
List<NewsItemListDatum> data;
Meta meta;
factory NewsItemList.fromJson(Map<String, dynamic> json) => NewsItemList(
data: List<NewsItemListDatum>.from(json["data"].map((x) => NewsItemListDatum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class NewsItemListDatum {
NewsItemListDatum({
required this.id,
required this.attributes,
});
int id;
PurpleAttributes attributes;
factory NewsItemListDatum.fromJson(Map<String, dynamic> json) => NewsItemListDatum(
id: json["id"],
attributes: PurpleAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class PurpleAttributes {
PurpleAttributes({
required this.title,
required this.description,
required this.pubDate,
required this.author,
required this.createdAt,
required this.updatedAt,
required this.content,
required this.link,
required this.source,
required this.thumbnail,
required this.newsCats,
required this.comments,
required this.governorate,
required this.likes,
});
String title;
String description;
String pubDate;
String author;
DateTime createdAt;
DateTime updatedAt;
String content;
String link;
String source;
String thumbnail;
NewsCats newsCats;
Comments comments;
Governorate governorate;
Likes likes;
factory PurpleAttributes.fromJson(Map<String, dynamic> json) => PurpleAttributes(
title: json["title"],
description: json["description"],
pubDate: json["pubDate"],
author: json["author"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
content: json["content"],
link: json["link"],
source: json["source"],
thumbnail: json["thumbnail"],
newsCats: NewsCats.fromJson(json["news_cats"]),
comments: Comments.fromJson(json["comments"]),
governorate: Governorate.fromJson(json["governorate"]),
likes: Likes.fromJson(json["likes"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"description": description,
"pubDate": pubDate,
"author": author,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"content": content,
"link": link,
"source": source,
"thumbnail": thumbnail,
"news_cats": newsCats.toJson(),
"comments": comments.toJson(),
"governorate": governorate.toJson(),
"likes": likes.toJson(),
};
}
class Comments {
Comments({
required this.data,
});
List<CommentsDatum> data;
factory Comments.fromJson(Map<String, dynamic> json) => Comments(
data: List<CommentsDatum>.from(json["data"].map((x) => CommentsDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class CommentsDatum {
CommentsDatum({
required this.id,
required this.attributes,
});
int id;
FluffyAttributes attributes;
factory CommentsDatum.fromJson(Map<String, dynamic> json) => CommentsDatum(
id: json["id"],
attributes: FluffyAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class FluffyAttributes {
FluffyAttributes({
required this.content,
required this.createdAt,
required this.updatedAt,
});
String content;
DateTime createdAt;
DateTime updatedAt;
factory FluffyAttributes.fromJson(Map<String, dynamic> json) => FluffyAttributes(
content: json["content"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"content": content,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
class Governorate {
Governorate({
required this.data,
});
Dat data;
factory Governorate.fromJson(Map<String, dynamic> json) => Governorate(
data: Dat.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Dat {
Dat({
required this.id,
required this.attributes,
});
int id;
DataAttributes attributes;
factory Dat.fromJson(Map<String, dynamic> json) => Dat(
id: json["id"],
attributes: DataAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DataAttributes {
DataAttributes({
required this.name,
required this.createdAt,
required this.updatedAt,
});
String name;
DateTime createdAt;
DateTime updatedAt;
factory DataAttributes.fromJson(Map<String, dynamic> json) => DataAttributes(
name: json["name"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
class Likes {
Likes({
required this.data,
});
List<LikesDatum> data;
factory Likes.fromJson(Map<String, dynamic> json) => Likes(
data: List<LikesDatum>.from(json["data"].map((x) => LikesDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class LikesDatum {
LikesDatum({
required this.id,
required this.attributes,
});
int id;
TentacledAttributes attributes;
factory LikesDatum.fromJson(Map<String, dynamic> json) => LikesDatum(
id: json["id"],
attributes: TentacledAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class TentacledAttributes {
TentacledAttributes({
required this.likeit,
required this.createdAt,
required this.updatedAt,
required this.publishedAt,
});
bool likeit;
DateTime createdAt;
DateTime updatedAt;
DateTime publishedAt;
factory TentacledAttributes.fromJson(Map<String, dynamic> json) => TentacledAttributes(
likeit: json["likeit"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
publishedAt: DateTime.parse(json["publishedAt"]),
);
Map<String, dynamic> toJson() => {
"likeit": likeit,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"publishedAt": publishedAt.toIso8601String(),
};
}
class NewsCats {
NewsCats({
required this.data,
});
List<Dat> data;
factory NewsCats.fromJson(Map<String, dynamic> json) => NewsCats(
data: List<Dat>.from(json["data"].map((x) => Dat.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
the code generated using https://app.quicktype.io/
3- delay occurred cuz of transection in the backend and amount of data handled in application
4- although it is hard coded but it is useful cuz i don't need to make a lot of api calls [ like get comments where item id is 5 ]
or i can fetch a list of data without it's related entities
in this case i will get list of items and every time i need get related entity i make another api call
class NewsItemsListApiData {
NewsItemsListApiData({
required this.data,
required this.meta,
});
List<NewsItem> data;
Meta meta;
factory NewsItemsListApiData.fromJson(Map<String, dynamic> json) =>
NewsItemsListApiData(
data:
List<NewsItem>.from(json["data"].map((x) => NewsItem.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class NewsItem {
NewsItem({
required this.id,
required this.attributes,
});
int id;
Attributes attributes;
factory NewsItem.fromJson(Map<String, dynamic> json) => NewsItem(
id: json["id"],
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class Attributes {
Attributes({
required this.title,
required this.description,
required this.pubDate,
required this.author,
required this.createdAt,
required this.updatedAt,
required this.content,
required this.link,
required this.source,
required this.thumbnail,
});
String title;
String description;
String pubDate;
String author;
DateTime createdAt;
DateTime updatedAt;
String content;
String link;
String source;
String thumbnail;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
title: json["title"],
description: json["description"],
pubDate: json["pubDate"],
author: json["author"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
content: json["content"],
link: json["link"],
source: json["source"],
thumbnail: json["thumbnail"],
);
Map<String, dynamic> toJson() => {
"title": title,
"description": description,
"pubDate": pubDate,
"author": author,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"content": content,
"link": link,
"source": source,
"thumbnail": thumbnail,
};
}
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
so any ideas about best practice and clean code or any other methods makes the code less error prone and more clean ?

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

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

I got an error while getting data from the API, how should I get the data if flutter?

I am getting data from an API using a model. But I ran into a problem that when I get the 'gallery' data, I get an error, that is, I get the data incorrectly. I need to get the 'gallery' field and inside it take the 'url' field - a link to the photo, in order to use it in the future. Can you tell me how to get the 'url' field correctly?
{
"data": {
"id": 35,
"picture_url": null,
"email_confirmed": false,
"gallery": [
{
"url": "https://picture-staging.s3.eu-central.jpeg",
"mime_type": "image/jpeg",
"type": "gallery",
"updated_at": "2022",
"created_at": "2022"
}
],
"updated_at": "2022",
"created_at": "2022"
}
}
model
class User {
final int id;
List? gallery;
User({
required this.id,
this.gallery,
});
User.fromJson(Map<String, dynamic> json)
: this(
id: json['id'] as int,
gallery: json['gallery']['url'],
);
In your API response, there is a list of gallery objects therefore you have to traverse through all of them.
User.fromJson(Map<String, dynamic> json) {
json = json['data'];
id = json['id'];
pictureUrl = json['picture_url'];
emailConfirmed = json['email_confirmed'];
if (json['gallery'] != null) {
gallery = <Gallery>[];
json['gallery'].forEach((v) {
gallery!.add(new Gallery.fromJson(v));
});
}
updatedAt = json['updated_at'];
createdAt = json['created_at'];
}
There are multiple tools that helps you create that .fromJson method, like this. Paste your json there and it will generate dart code for you, really helps me.
The usage should like this:
User user = User.fromJson(yourApiResponseJson);
print(user.id);
print(user.gallery); //prints entire list of gallery
print(user.gallery.first.url); //prints only first object url
I hope that is not your whole model, because that model is not accessing the "data" key on the json response, your model should start getting the key data then pass it to another class that in this case should be named User
here is a brief example
class User {
User({
required this.data,
});
final Data data;
factory User.fromJson(Map<String, dynamic> json) => User(
data: Data.fromJson(json["data"]),
);
}
The Data class could be like this:
class Data {
Data({
required this.id,
required this.pictureUrl,
required this.emailConfirmed,
required this.gallery,
required this.updatedAt,
required this.createdAt,
});
final int id;
final dynamic pictureUrl;
final bool emailConfirmed;
final List<Gallery> gallery;
final String updatedAt;
final String createdAt;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
pictureUrl: json["picture_url"],
emailConfirmed: json["email_confirmed"],
gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
}
I reccomend you using Quicktype
Hey you can use this tool to generate your dart model from json.
Below is generated code from above tool
// final user = userFromJson(jsonString);
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
User({
required this.data,
});
Data data;
factory User.fromJson(Map<String, dynamic> json) => User(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
this.id,
this.pictureUrl,
this.emailConfirmed,
this.gallery,
this.updatedAt,
this.createdAt,
});
int? id;
String? pictureUrl;
bool? emailConfirmed;
List<Gallery>? gallery;
String? updatedAt;
String? createdAt;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
pictureUrl: json["picture_url"],
emailConfirmed: json["email_confirmed"],
gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"picture_url": pictureUrl,
"email_confirmed": emailConfirmed,
"gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
"updated_at": updatedAt,
"created_at": createdAt,
};
}
class Gallery {
Gallery({
this.url,
this.mimeType,
this.type,
this.updatedAt,
this.createdAt,
});
String? url;
String? mimeType;
String? type;
String? updatedAt;
String? createdAt;
factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
url: json["url"],
mimeType: json["mime_type"],
type: json["type"],
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"url": url,
"mime_type": mimeType,
"type": type,
"updated_at": updatedAt,
"created_at": createdAt,
};
}
// You can use like this
final user = userFromJson(jsonString);
String? url = user.data?.gallery?.url;