Flutter convert json with array child and object to class map - flutter

in my application i get this result from server which into categories, that have an array which named products :
{
"categories": [
{
"id": 1,
"store_id": 1,
"category_id": null,
"page_id": null,
"title": "cat_name",
"image_uri": "/uploads/store/category_images/2020/1600839088.jpg",
"created_at": "2020-09-23T02:01:28.000000Z",
"updated_at": "2020-09-23T02:01:57.000000Z",
"products": [
{
"id": 1,
"store_categories_id": 1,
"store_id": 1,
"title": "title",
"description": "111111",
//...
}
]
}
],
"slides": {
"id": 1,
"slide_1": "/uploads/store/store_sliders/2020/16025126045410.jpg",
//...
}
}
i created this class with above structure:
StoreCategories class:
#JsonSerializable()
class StoreCategories {
final List<StoreCategoriesList> categories;
#JsonKey(nullable: true)
final Slides slides;
StoreCategories(this.categories,this.slides);
factory StoreCategories.fromJson(Map<String, dynamic> json) => _$StoreCategoriesFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesToJson(this);
}
StoreCategoriesList class:
#JsonSerializable()
class StoreCategoriesList{
final int id;
#JsonKey(name: 'store_id')
final int storeId;
final String title;
#JsonKey(name: 'image_uri')
final String imageUri;
#JsonKey(nullable: true)
final List<ProductsList> products;
StoreCategoriesList(this.id, this.storeId, this.title, this.imageUri, this.products);
factory StoreCategoriesList.fromJson(Map<String, dynamic> json) => _$StoreCategoriesListFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesListToJson(this);
}
ProductsList class:
#JsonSerializable()
class ProductsList {
final int id;
#JsonKey(name: 'store_categories_id')
final int storeCategoriesId;
#JsonKey(name: 'store_id')
final int storeId;
final String title;
final String description;
final String image;
final int cost;
ProductsList(this.id, this.storeCategoriesId, this.storeId, this.title, this.description, this.image, this.cost);
factory ProductsList.fromJson(Map<String, dynamic> json) => _$ProductsListFromJson(json);
Map<String, dynamic> toJson() => _$ProductsListToJson(this);
}
now! how can i convert my json structure to class map?
this code is not correct:
StoreCategories.fromJson(_res.response.data.map((data) => StoreCategories.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.from(data)));

Sounds like your _res.response.data is already a Map or List right?
So just simply StoreCategories.fromJson(_res.response.data). Done!
Flutter json_serializable is smart enough to decode nested classes! :)
P.S. If you have a JSON String, do jsonDecode(your_json_string) to get a Map or List.

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'],
);

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;

Function expressions can't be named. doc error

Hello in my flutter project i got this problem when i want to recall users by thier ID.
Future<UserModel> getUserById(String id)=> _firestore.collection(collection).doc(id){
print("==========id is $id=============");
debugPrint("==========NAME is ${doc.data()['name']}=============");
debugPrint("==========NAME is ${doc.data()['name']}=============");
it gives an error on [ .doc(id){ ]
what shall i do?
an also in my order page it gives same error somehow
_firestore.collection(collection).doc(id).setData()({
"userId": userId,
"cart": convertedCart,
"id": id,
"total": totalPrice,
"createdAt": DateTime.now().millisecondsSinceEpoch,
"description": description,
"status": status
});
}
what do you guys think?
in that line
_firestore.collection(collection).doc(id).setData()({
setData is error
my flutter version is 2.5.1
Try the code below.
Future<UserModel> getUserById(String id){
return FirebaseFirestore.instance.collection("collectionPath")
.doc(id).get().then((doc) => UserModel.fromSnapShot(doc.data()));
}
Your fromSnapshot don't return a UserModel. It should look like this.
import 'package:flutter/foundation.dart';
#immutable
class UserModel{
final String id;
final String name;
final String email;
final String stripeId;
final List<CartItemModel> cart;
final int totalCartPrice;
const UserModel({required this.id, required this.name, required this.email, required this.stripeId, required this.cart,
required this.totalCartPrice});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'email': email,
'stripeId': stripeId,
'cart': cart,
'totalCartPrice': totalCartPrice,
};
}
factory UserModel.fromMap(Map<String, dynamic> map) {
return UserModel(
id: map['id'] as String,
name: map['name'] as String,
email: map['email'] as String,
stripeId: map['stripeId'] as String,
cart: (map['cart'] as List).map((cart) => CartItemModel.fromMap(cart)).toList() ,
totalCartPrice: map['totalCartPrice'] as int,
);
}
}
#immutable
class CartItemModel{
final String id;
const CartItemModel({required this.id});
Map<String, dynamic> toMap() {
return {
'id': id,
};
}
factory CartItemModel.fromMap(Map<String, dynamic> map) {
return CartItemModel(
id: map['id'] as String,
);
}
}

How to send array of data in post request in 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