How do I display user's profile in flutter? - 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']);
}

Related

How to set the list of json data in flutter

I'm trying to return the items from this api https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812
but always the error:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
this my object and model:
Future<ProdutoModel> getProduto() async {
try {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
_accountListModel = ProdutoModel.fromJson(res);
var data = res['filhos'] as List;
setState(() {
_list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
});
return _accountListModel;
} catch (e) {
rethrow;
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
return this api
The returned is at List, so you have to do something like:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> main() async {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
var list = res as List;
for (var item in list) {
var _accountListModel = ProdutoModel.fromJson(item); // model per item
print(_accountListModel.phone);
var data = item['filhos'] as List;
var _list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
print(_list);
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
[
{
"phone": "48984974812",
"desperson": "Usuario admin",
"desemail": "admin#hcode.com.br",
"filhos": [
{
"age": 7,
"firstname": "Lorenzo",
"lastname": "Chaves"
},
{
"age": 14,
"firstname": "teste",
"lastname": "acompanhante"
},
{
"age": 14,
"firstname": "meu",
"lastname": "filho"
},
{
"age": 21,
"firstname": "teste",
"lastname": "teste"
}
]
}
]
You have type conversion issue make sure the types from the api is the same as the model
you can use this website : https://app.quicktype.io
to generate model to any json file without get any erorr and it gets you functions from json and to json

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;

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