How to POST raw json using retrofit Flutter - 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.

Related

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

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,
};
}

How to convert string arraylist to model arraylist in flutter?

List<String> langList = [English, Gujarati, Hindi, Marathi, Punjabi, Urdu, Spanish]
var selectedLanguagesList = <LanguageDatum>[].obs;
langList is a string type of list. and selectedLanguagesList is a model type of list.
How do I convert string list to model list in flutter ?
class LanguageDatum {
LanguageDatum({
this.id,
this.name,
this.status,
this.createdAt,
this.updatedAt,
this.deletedAt,
});
int? id;
String? name;
int? status;
DateTime? createdAt;
DateTime? updatedAt;
dynamic deletedAt;
factory LanguageDatum.fromJson(Map<String, dynamic> json) => LanguageDatum(
id: json["id"]??0,
name: json["name"]??"",
status: json["status"]??"",
createdAt: json["created_at"] != null ? DateTime.parse(json["created_at"]) : null,
updatedAt: json["updated_at"] != null ? DateTime.parse(json["updated_at"]) : null,
deletedAt: json["deleted_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"status": status,
"created_at": createdAt,
"updated_at": updatedAt,
"deleted_at": deletedAt,
};
}
So, Above is model class.
If I understand your question correctly, I guess it would be
// To convert String array to Model array
final listOfLanguageDatum =
langList.map((e) => LanguageDatum(name: e)).toList();
List<String> langList = [
'Tamil'
'English',
'Gujarati',
'Hindi',
'Marathi',
'Punjabi',
'Urdu',
'Spanish'
];
class LanguageDatum extends GetxController {
LanguageDatum({
this.id,
this.name,
this.status,
this.createdAt,
this.updatedAt,
this.deletedAt,
});
int? id;
String? name;
int? status;
DateTime? createdAt;
DateTime? updatedAt;
dynamic deletedAt;
factory LanguageDatum.fromJson(Map<String, dynamic> json) => LanguageDatum(
id: json["id"] ?? 0,
name: json["name"] ?? "",
status: json["status"] ?? "",
createdAt: json["created_at"] != null
? DateTime.parse(json["created_at"])
: null,
updatedAt: json["updated_at"] != null
? DateTime.parse(json["updated_at"])
: null,
deletedAt: json["deleted_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"status": status,
"created_at": createdAt,
"updated_at": updatedAt,
"deleted_at": deletedAt,
};
#override
String toString() {
return 'LanguageDatum(id: $id, name: $name, status: $status, createdAt: $createdAt, updateAt: $updatedAt, deletedAt: $deletedAt)';
}
}
Right now your language is of String type, to make language object You need to make a model class say,
Class LanguageDatum{
String name;
...
}

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;

How do I display user's profile in flutter?

I am fetching one row from a database and sending it to flutter where I decode it to receive the following response using var userProfile = json.decode(response.body);
[{id: 1, first_name: First, last_name: Last, name: david, email: david4001#gmail.com, phone_number: 12, user_image: null, email_verification_code: null, email_verification_time: null, created_at: 2022-03-24T17:37:17.000000Z, updated_at: 2022-03-29T07:16:25.000000Z}]
I have a UserProfile class
class UserProfile {
final int id;
final String firstName;
final String lastName;
final String email;
final String phoneNumber;
UserProfile({
required this.id,
required this.firstName,
required this.lastName,
required this.email,
required this.phoneNumber,
});
factory UserProfile.fromJson(Map<String, dynamic> json) {
return UserProfile(
id: json["id"],
firstName: json["first_name"],
lastName: json["first_name"],
email: json["email"],
phoneNumber: json["phone_number"],
);
}
}
I am using the following code to find a suitable way to display the data
UserProfile? userProfile;
if (response.statusCode == 200) {
var userProfile = json.decode(response.body);
List<UserProfile> myProfile = [];
for (var k in userProfile) {
myProfile.add(UserProfile.fromJson(userProfile));
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load user data');
}
I am getting the error below
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
How do I handle the error?
You are passing whole list instead of value.
Try this.
var userProfile = json.decode(response.body);
List<UserProfile> myProfile = [];
for (var k in userProfile) {
myProfile.add(UserProfile.fromJson(k));
}
You will try like this way
const myJson = """
[
{
"id": 1,
"first_name": "First",
"last_name": "Last",
"name": "david",
"email": "david4001#gmail.com",
"phone_number": "12",
"user_image": null,
"email_verification_code": null,
"email_verification_time": null,
"created_at": "2022-03-24T17:37:17.000000Z",
"updated_at": "2022-03-29T07:16:25.000000Z"
}
]
""";
class UserProfile {
UserProfile({
this.id,
this.firstName,
this.lastName,
this.name,
this.email,
this.phoneNumber,
this.userImage,
this.emailVerificationCode,
this.emailVerificationTime,
this.createdAt,
this.updatedAt,
});
int? id;
String? firstName;
String? lastName;
String? name;
String? email;
String? phoneNumber;
dynamic userImage;
dynamic emailVerificationCode;
dynamic emailVerificationTime;
DateTime? createdAt;
DateTime? updatedAt;
factory UserProfile.fromMap(Map<String, dynamic> json) => UserProfile(
id: json["id"],
firstName: json["first_name"],
lastName: json["last_name"],
name: json["name"],
email: json["email"],
phoneNumber: json["phone_number"],
userImage: json["user_image"],
emailVerificationCode: json["email_verification_code"],
emailVerificationTime: json["email_verification_time"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
}
void main() {
final userData = List.from(json.decode(myJson));
print(userData[0]['id']);
print(userData[0]['name']);
}

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