Auto generate only specific part from Json, not the whole json - flutter

I am using https://app.quicktype.io to generate my model class. All I give this website is my JSON code. But, all I want is a list, which is called data, within this json file, not the whole JSON. What should I do?

This should work:
UserModel.dart file:
import 'package:meta/meta.dart';
import 'dart:convert';
List<UserModel> userModelFromJson(String str) => List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
UserModel({
#required this.id,
#required this.email,
#required this.firstName,
#required this.lastName,
#required this.avatar,
});
int id;
String email;
String firstName;
String lastName;
String avatar;
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
email: json["email"],
firstName: json["first_name"],
lastName: json["last_name"],
avatar: json["avatar"],
);
Map<String, dynamic> toJson() => {
"id": id,
"email": email,
"first_name": firstName,
"last_name": lastName,
"avatar": avatar,
};
}

Related

Error "The argument type 'DateTime?' can't be assigned to the parameter type 'DateTime'." flutter firestore

I tried to fetch users'Users data from Firebase Firestore. For that I created a model class.And also in those data has a birthday parameter I tried to define that in model but show this error "The argument type 'DateTime?' can't be assigned to the parameter type 'DateTime'"
My code:
import 'dart:convert';
Users UsersFromJson(String str) => Users.fromJson(json.decode(str));
String UsersToJson(Users data) => json.encode(data.toJson());
class Users {
Users({
required this.id,
required this.url,
required this.name,
required this.birthday,
});
String id;
String name;
String url;
DateTime birthday;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"] ?? "",
name: json["name"] ?? "",
url: json["url"] ?? "",
birthday: json["birthday"] != null ? DateTime.parse(json["birthday"]) : null,
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"birthday": birthday?.toString(),
};
}
You can choose one of two codes:
class Users {
Users({
required this.id,
required this.url,
required this.name,
required this.birthday,
});
String id;
String name;
String url;
DateTime? birthday;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"] ?? "",
name: json["name"] ?? "",
url: json["url"] ?? "",
birthday: json["birthday"] != null ? DateTime.parse(json["birthday"]) : null,
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"birthday": birthday?.toString(),
};
}
class Users {
Users({
required this.id,
required this.url,
required this.name,
required this.birthday,
});
String id;
String name;
String url;
DateTime birthday;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"] ?? "",
name: json["name"] ?? "",
url: json["url"] ?? "",
birthday: json["birthday"] != null ? DateTime.parse(json["birthday"]) : DateTime.now(),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"birthday": birthday?.toString(),
};
}
However, I recommend that you use the first code more, because if the birthday field is null, you can show the user that there is no data.
If you use the second code, I don't think there is any way to check if the birthday field is empty.
Make your birthday nullable. So replace
DateTime birthday;
with
DateTime? birthday;
If you don't want it to be nullable you could instead put a non-null fallback like DateTime.now() for example like
birthday:
json["birthday"] != null ? DateTime.parse(json["birthday"]) : DateTime.now(),
2 work arounds
pass non nullable value to birthday:
birthday: DateTime.parse(json["birthday"]) ?? DateTime.now(),
make birthday nullable
DateTime? birthday
with this method you can keep the existing line of the code. Your error will no longer display.

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.

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