i have a list of map items in firebase.. like this
{
"0": [
{
"score": 4.5,
"review": "The pizza was amazing!"
},
{
"score": 5.0,
"review": "Very friendly staff, excellent service!"
}
],
"1": [
{
"score": 4.5,
"review": "The pizza was amazing!"
},
{
"score": 5.0,
"review": "Very friendly staff, excellent service!"
}
]
}
I cant convert it into dart objects correctly...
this is just an example my data is different
i tried this
final String uid;
final String name;
final String email;
final bool isAdmin;
final String easypaisa;
final String jazzCash;
final String bankAccount;
final String phoneNumber;
final String profileImage;
final List<String>? isFavorite;
final List<ListOfPackages> activatedPackages;
UserModel({
this.uid = '',
this.name = '',
this.email = '',
this.isAdmin = false,
this.easypaisa = '',
this.jazzCash = '',
this.bankAccount = '',
this.phoneNumber = '',
this.profileImage = '',
final List<String>? isFavorite,
final List<ListOfPackages>? activatedPackages,
}) : isFavorite = isFavorite ?? [],
activatedPackages = activatedPackages ?? [];
}
class ListOfPackages {
final bool acceptedPackage;
final String packageId;
final String packageTime;
final String proofImage;
final String uid;
final String username;
ListOfPackages(
{this.acceptedPackage = false,
this.packageId = '',
this.packageTime = '',
this.proofImage = '',
this.uid = '',
this.username = ''});
}
and here i'm mapping the data from firestore to the UserModel
return UserModel(
name: doc.get("name"),
email: doc.get('email'),
isAdmin: doc.get('isAdmin'),
easypaisa: doc.get('easypaisa'),
jazzCash: doc.get('jazzCash'),
bankAccount: doc.get('bankAccount'),
phoneNumber: doc.get('phoneNumber'),
profileImage: doc.get('profilePic'),
isFavorite: List.from(doc.data().toString().contains('favoritePackages')
? doc.get('favoritePackages')
: []),
activatedPackages: List.from(
doc.data().toString().contains('activatedPackages')
? doc.get('activatedPackages')
: []),
uid: doc.get('uid') ?? '');
}
With this, i'm getting this error
Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'ListOfPackages'
Can anyone guide me the right way to convert these? Actually most of the tutorials are in FactoryConstructor way so i can't take help from there... I'd appreciate any help.
Can you create a function that takes in a map and converts it to a ListOfPackages object? Then maybe you could do a forEach on doc.get(‘activatedPackages’) to add each ListOfPackages object one at a time to a List of ListOfPackagess, which you could then assign to activatedPackages.
found the solution!
UserModel _userDataFromSnapshot(DocumentSnapshot doc) {
return UserModel(
name: doc.get("name"),
email: doc.get('email'),
isAdmin: doc.get('isAdmin'),
easypaisa: doc.get('easypaisa'),
jazzCash: doc.get('jazzCash'),
bankAccount: doc.get('bankAccount'),
phoneNumber: doc.get('phoneNumber'),
profileImage: doc.get('profilePic'),
isFavorite: List.from(doc.data().toString().contains('favoritePackages')
? doc.get('favoritePackages')
: []),
activatedPackages: (doc.get('activatedPackages') as List<dynamic>)
.map((item) => ListOfPackages(
acceptedPackage: item['acceptedPackage'],
packageId: item['packageId'],
packageTime: item['packageTime'],
proofImage: item['proofImage'],
uid: item['uid'],
username: item['uid'],
))
.toList(),
uid: doc.get('uid') ?? '');
}
Related
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
I am trying to read data from a list fetched from an API. I want to fetch the title key in the nested list with key questions.
Here is the response expected from the API call.
[
{
"id": "string",
"quizId": "string",
"userId": "string",
"lessonId": "string",
"courseId": "string",
"correct_Answered": 0,
"wrong_Answered": 0,
"datePlayed": "2022-11-02T22:17:09.353Z",
"questions": [
{
"questionId": "string",
"title": "string",
"pass": true,
"completed": "2022-11-02T22:17:09.353Z",
"rightAnswers": [
"string"
],
"options": [
"string"
],
"selectedOptions": [
"string"
]
}
],
"quizScore": 0,
"questionCount": 0
}
]
The code I wrote to read the outer list works, but the one for the nested list is not working.
Here is the code
final quizHistoryData = json.decode(postQuizResponse.body);
final List<QuizHistory> quizHistoryHolder = [];
final List<QuizHistory> quizTitleHolder = [];
for (var item in quizHistoryData) {
quizHistoryHolder.add(QuizHistory(
id: item['id'],
quizId: item['quizId'],
userId: item['userId'],
courseId: item['courseId'],
lessonId: item['lessonId'],
correctlyAnswered: item['correct_Answered'],
wronglyAnswered: item['wrong_Answered'],
datePlayed: item['datePlayed'],
questions: item['questions'],
quizScore: item['quizScore'],
questionCount: item['questionCount']));
for (var item in item['questions']) {
quizTitleHolder.add(QuizHistory(questionTitle: item['title']));
print('Quiz history title is ${questionTitle}');
}
}
I recommend serializing JSON inside model classes and having seperate models for Question and Quiz data.
class QuizHistory {
QuizHistory(
this.id,
this.quizId,
this.userId,
this.lessonId,
this.courseId,
this.correctAnswered,
this.wrongAnswered,
this.datePlayed,
this.questions,
);
QuizHistory.fromJson(Map<String, dynamic> json)
: id = json['id'] as String,
quizId = json['quizId'] as String,
userId = json['userId'] as String,
lessonId = json['lessonId'] as String,
courseId = json['courseId'] as String,
correctAnswered = json['correctAnswered'] as int,
wrongAnswered = json['wrongAnswered'] as int,
datePlayed = json['datePlayed'] as String,
questions = (json['questions'] as List<dynamic>)
.map((e) => Question.fromJson(e as Map<String, dynamic>))
.toList();
final String id;
final String quizId;
final String userId;
final String lessonId;
final String courseId;
final int correctAnswered;
final int wrongAnswered;
final String datePlayed;
final List<Question> questions;
}
class Question {
Question(
this.questionId,
this.title,
this.pass,
this.completed,
this.rightAnswers,
this.options,
this.selectedOptions,
);
Question.fromJson(Map<String, dynamic> json)
: questionId = json['questionId'] as String,
title = json['title'] as String,
pass = json['pass'] as bool,
completed = json['completed'] as String,
rightAnswers = json['rightAnswers'] as List<String>,
options = json['options'] as List<String>,
selectedOptions = json['selectedOptions'] as List<String>;
final String questionId;
final String title;
final bool pass;
final String completed;
final List<String> rightAnswers;
final List<String> options;
final List<String> selectedOptions;
}
and finally
quizHistoryHolder = jsonData
.map((e) => QuizHistory.fromJson(e as Map<String, dynamic>))
.toList();
You might want to use JSON serialization library when you have a lot of models. Serializing JSON using code generation libraries
I'm struggling with json serialization.
It throws me na error: "Unhandled Exception: type 'String' is not a subtype of type 'num?' in type cast".
I was trying to use a custom JSON converter, but it doesn't work. It happens when I try to fetch data from API and when it starts do deserialize JSON.
Does anyone have a clue what's wrong?
The error happens when it tries to parse lat and lng values. When it parses these two values, it throws an exception that type String ist not a subtype of type num? in type cast. It happens in car_model.g.dart file when it runs these two lines:
lat: (json['lat'] as num?)?.toDouble(),
lng: (json['lng'] as num?)?.toDouble(),
[
{
"_id": "5e5e40c4c0ea272d00000956",
"brand": "Tofas",
"model": "Sahin",
"color": "#0fc0fc",
"registration": "WA12345",
"year": "2005-01-01T00:00:00.000Z",
"ownerId": "5e5e3d7fc0ea272d00000824",
"lat": 50.754,
"lng": 12.2145
},
]
Entity
import 'package:equatable/equatable.dart';
abstract class Car extends Equatable {
final String? id;
final String? brand;
final String? model;
final String? color;
final String? registration;
final String? year;
final String? ownerId;
final double? lat;
final double? lng;
const Car({
this.id,
this.brand,
this.model,
this.color,
this.registration,
this.year,
this.ownerId,
this.lat,
this.lng,
});
#override
List<Object?> get props => [
id,
brand,
model,
color,
registration,
year,
ownerId,
lat,
lng,
];
}
Model
part 'car_model.g.dart';
class CarModelList {
final List<CarModel> carModelList;
CarModelList({
required this.carModelList,
});
factory CarModelList.fromJson(List<dynamic> parsedJson) {
List<CarModel> carModelList = <CarModel>[];
carModelList = parsedJson.map((i) => CarModel.fromJson(i)).toList();
return CarModelList(carModelList: carModelList);
}
}
#JsonSerializable()
class CarModel extends Car {
const CarModel({
super.id,
super.brand,
super.model,
super.color,
super.registration,
super.year,
super.ownerId,
super.lat,
super.lng,
});
#JsonKey(name: '_id')
#override
String? get id;
factory CarModel.fromJson(Map<String, dynamic> json) =>
_$CarModelFromJson(json);
Map<String, dynamic> toJson() => _$CarModelToJson(this);
}
Model generated
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'car_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CarModel _$CarModelFromJson(Map<String, dynamic> json) => CarModel(
id: json['_id'] as String?,
brand: json['brand'] as String?,
model: json['model'] as String?,
color: json['color'] as String?,
registration: json['registration'] as String?,
year: json['year'] as String?,
ownerId: json['ownerId'] as String?,
lat: (json['lat'] as num?)?.toDouble(),
lng: (json['lng'] as num?)?.toDouble(),
);
Map<String, dynamic> _$CarModelToJson(CarModel instance) => <String, dynamic>{
'brand': instance.brand,
'model': instance.model,
'color': instance.color,
'registration': instance.registration,
'year': instance.year,
'ownerId': instance.ownerId,
'lat': instance.lat,
'lng': instance.lng,
'_id': instance.id,
};
It is because sometimes you are getting
"lat": "50.754",
"lng": "12.2145"
it means it is string.
So you can follow below thing
final dynamic lat;
final dynamic lng;
then again generate model using your model generator tool.
And for auto creation of model you can use https://ashamp.github.io/jsonToDartModel/ it provide functionality for null safety too.
[
{
"_id": "5e5e40c4c0ea272d00000956",
"brand": "Tofas",
"model": "Sahin",
"color": "#0fc0fc",
"registration": "WA12345",
"year": "2005-01-01T00:00:00.000Z",
"ownerId": "5e5e3d7fc0ea272d00000824",
"lat": 50.754,
"lng": 12.2145
}
]
Array has an extra comma at the end.
I hope this is the problem
You can use https://app.quicktype.io/ website for from json model to dart model convert.
TOFAŞK <3
You can try another code generator and fully control what you get.
This is how the CarModel class is described.
CarModel:
extends: Car
fields:
id: String?
brand: String?
model: String?
color: String?
registration: String?
year: String?
ownerId: String?
lat:
type: double
deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
serialize: "(x) { return '$x'; }"
lng:
type: double
deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
serialize: "(x) { return '$x'; }"
Generator.
import 'dart:io';
import 'package:object_serializer/json_serializer_generator.dart';
import 'package:yaml/yaml.dart';
void main() {
String generateName(String name) {
return '_${name}Serializer';
}
final classes = loadYaml(_classes) as Map;
final g = JsonSerializerGenerator();
final classesCode = g.generateClasses(classes);
final values = {
'classes': classesCode,
};
var source = g.render(_template, values);
source = g.format(source);
File('bin/stackoverflow.dart').writeAsStringSync(source);
}
const _classes = r'''
CarModel:
extends: Car
fields:
id: String?
brand: String?
model: String?
color: String?
registration: String?
year: String?
ownerId: String?
lat:
type: double
deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
serialize: "(x) { return '$x'; }"
lng:
type: double
deserialize: "(x) { return x == null ? 0.0 : double.parse('$x'); }"
serialize: "(x) { return '$x'; }"
''';
const _template = r'''
import 'dart:convert';
void main(List<String> args) {
final carModel = CarModel(
id: null,
brand: null,
model: null,
color: null,
registration: null,
year: null,
ownerId: null,
lat: 12.2145,
lng: 50.754);
final list = CarModel.toJsonList([carModel]);
final List<CarModel> carModels = CarModel.fromJsonList(list);
print('lat type: ${list[0]['lat'].runtimeType}');
print(jsonEncode(list));
print(carModels.first.lat);
print(carModels.first.lng);
print(carModels.first.lng.runtimeType);
}
{{classes}}
''';
Generated source code:
import 'dart:convert';
void main(List<String> args) {
final carModel = CarModel(
id: null,
brand: null,
model: null,
color: null,
registration: null,
year: null,
ownerId: null,
lat: 12.2145,
lng: 50.754);
final list = CarModel.toJsonList([carModel]);
final List<CarModel> carModels = CarModel.fromJsonList(list);
print('lat type: ${list[0]['lat'].runtimeType}');
print(jsonEncode(list));
print(carModels.first.lat);
print(carModels.first.lng);
print(carModels.first.lng.runtimeType);
}
class CarModel extends Car {
CarModel(
{required this.id,
required this.brand,
required this.model,
required this.color,
required this.registration,
required this.year,
required this.ownerId,
required this.lat,
required this.lng});
factory CarModel.fromJson(Map json) {
return CarModel(
id: json['id'] as String?,
brand: json['brand'] as String?,
model: json['model'] as String?,
color: json['color'] as String?,
registration: json['registration'] as String?,
year: json['year'] as String?,
ownerId: json['ownerId'] as String?,
lat: (x) {
return x == null ? 0.0 : double.parse('$x');
}(json['lat']),
lng: (x) {
return x == null ? 0.0 : double.parse('$x');
}(json['lng']),
);
}
final String? id;
final String? brand;
final String? model;
final String? color;
final String? registration;
final String? year;
final String? ownerId;
final double lat;
final double lng;
static List<CarModel> fromJsonList(List json) {
return json.map((e) => CarModel.fromJson(e as Map)).toList();
}
Map<String, dynamic> toJson() {
return {
'id': id,
'brand': brand,
'model': model,
'color': color,
'registration': registration,
'year': year,
'ownerId': ownerId,
'lat': (x) {
return '$x';
}(lat),
'lng': (x) {
return '$x';
}(lng),
};
}
static List<Map<String, dynamic>> toJsonList(List<CarModel> list) {
return list.map((e) => e.toJson()).toList();
}
}
Output:
lat type: String
[{"id":null,"brand":null,"model":null,"color":null,"registration":null,"year":null,"ownerId":null,"lat":"12.2145","lng":"50.754"}]
12.2145
50.754
double
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']);
}
Refactoring my code, I updated to
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.2.0
firebase_auth: ^1.2.0
cloud_firestore: ^2.2.0
cloud_functions: ^1.1.0
...
e.g. cloud_firestore from 1.0.4 to 2.2.0
I have a User class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/widgets.dart';
import 'package:mypckg/services/database.dart';
class User {
final String id;
final String email;
final String displayName;
final String language;
final List affiliatedOrganizations;
final bool isAdmin;
final bool isEditor;
const User(
{this.id = "",
this.email = "",
this.displayName = "",
this.language = "",
this.affiliatedOrganizations = const [],
this.isAdmin = false,
this.isEditor = false});
factory User.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data()!;
return User(
id: doc.id,
email: data['email'],
displayName: data['displayName'] ?? '',
language: data['language'] ?? '',
affiliatedOrganizations: data['affiliatedOrganizations'] ?? [],
isAdmin: data['isAdmin'] ?? false,
isEditor: data['isEditor'] ?? false,
);
}
}
and later I would like to get some data
...
var userData = await DatabaseService(uid: user.uid)
.getUserData()
.then((value) => value.data());
local.User fullLocalUser = local.User(
id: user.uid,
email: user.email,
displayName: userData!['displayName'] ?? "", // <-- error referencing this line
language: userData['language'] ?? "",
affiliatedOrganizations: userData['affiliatedOrganizations'] ?? [],
isAdmin: (await _userClaims)!['admin'] == true,
isEditor: (await _userClaims)!['editor'] == true);
return fullLocalUser;
...
Relevant extract from DatabaseService
class DatabaseService {
final String uid;
DatabaseService({this.uid = ""});
final CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
...
Future<DocumentSnapshot> getUserData() async {
print("get user data");
return await usersCollection.doc(uid).get();
}
...
When I compile the code, it results in
Error: The operator '[]' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '[]' operator.
displayName: userData!['displayName'] ?? "",
I found out, that in regards to https://pub.dev/packages/cloud_firestore/changelog "DocumentReference, CollectionReference, Query, DocumentSnapshot, CollectionSnapshot, QuerySnapshot, QueryDocumentSnapshot, Transaction.get, Transaction.set and WriteBatch.set now take an extra generic parameter. (#6015)." But I cannot figure out what I have to change now, that the code will work again :(
I could get rid of that error with the following changes.
User class:
...
class User {
final String id;
final String email;
final String displayName;
final String language;
final List affiliatedOrganizations;
final bool isAdmin;
final bool isEditor;
const User(
{this.id = "",
this.email = "",
this.displayName = "",
this.language = "",
this.affiliatedOrganizations = const [],
this.isAdmin = false,
this.isEditor = false});
User.fromJson(Map<String, Object?> json)
: this(
email: json['email']! as String,
displayName: json['displayName'] as String,
language: json['language'] as String,
affiliatedOrganizations: json['affiliatedOrganizations'] as List,
isAdmin: json['isAdmin'] as bool,
isEditor: json['isEditor'] as bool,
);
Map<String, Object?> toJson() {
return {
'email': email,
'displayName': displayName,
'language': language,
'affiliatedOrganizations': affiliatedOrganizations,
'isAdmin': isAdmin,
'isEditor': isEditor,
};
}
factory User.fromFirestore(DocumentSnapshot doc) {
print("---- factoring user ----");
return User(
id: doc.id,
email: doc.get('email') ?? '',
displayName: doc.get('displayName') ?? '',
language: doc.get('language') ?? '',
affiliatedOrganizations: doc.get('affiliatedOrganizations') ?? [],
isAdmin: doc.get('isAdmin') ?? false,
isEditor: doc.get('isEditor') ?? false,
);
}
}
Database service:
...
final CollectionReference usersCollection = FirebaseFirestore.instance
.collection('users')
.withConverter<User>(
fromFirestore: (snapshots, _) => User.fromJson(snapshots.data()!),
toFirestore: (user, _) => user.toJson());
...
Future<DocumentSnapshot> getUserData() async {
print("get user data");
return usersCollection.doc(uid).get();
}
...
and here I can use it:
...
var userData = await DatabaseService(uid: user.uid).getUserData();
local.User fullLocalUser = local.User(
id: user.uid,
email: user.email,
displayName: userData['displayName'] ?? "",
language: userData['language'] ?? "",
affiliatedOrganizations: userData['affiliatedOrganizations'] ?? [],
isAdmin: (await _userClaims)!['admin'] == true,
isEditor: (await _userClaims)!['editor'] == true);
return fullLocalUser;
...
Thanks for the support which lead to a working solution step by step.