#JsonKey how to access to elements of a Map, flutter - firebase

I have the next map config, I was wondering how I could access to it using the #JsonKey keyword.
import 'package:json_annotation/json_annotation.dart';
part 'user_model.g.dart';
#JsonSerializable()
class UserModel {
#JsonKey(name: 'username')
String username;
#JsonKey(name: 'realName')
String realname;
#JsonKey(name: 'gender')
String gender;
#JsonKey(name: 'date_birth')
String dateBirth;
#JsonKey(name: 'isObserver')
bool isObserver;
#JsonKey(name: 'friends')
List<dynamic> friendsList;
#JsonKey(name: 'pendingFriends')
List<dynamic> pendingFriendsList;
#JsonKey(name: 'config') // Here, config is a map, how can I access to their data?
bool notifyFriend;
UserModel(this.username, this.realname, this.dateBirth, this.gender,
this.isObserver, this.friendsList, this.pendingFriendsList, this.notifyFriend);
factory UserModel.fromJson(Map<String, dynamic> json) =>
_$UserModelFromJson(json);
Map<String, dynamic> toJson() => _$UserModelToJson(this);
}

First of all you have to create another class with the name config having those 3 variables in it and then import that class in this class and replace the variable there with that like :
class Config{
#JsonKey(name: 'notifyFriends')
bool notifyFriend;
#JsonKey(name: 'recordAudio')
bool recordAudio;
#JsonKey(name: 'sendTweet')
bool sendTweet;
Config(this.sendTweet, this.recordAudio, this.notifyFriend);
factory Config.fromJson(Map<String, dynamic> json) =>
_$ConfigFromJson(json);
Map<String, dynamic> toJson() => _$ConfigToJson(this);
}
and use it like this:
#JsonKey(name: 'config') // Here,
Config config;
I hope this clear your problem.

Related

Undefined name 'contact' - Flutter toJson Map in Stateful widget

I've created a map yet am having difficulty accessing the variable 'contact' within a stateful widget. I'm not sure where else to declare final Contact contact; .
The Contact model file.
class Contact {
int rating;
String name;
String location;
int phoneNumber;
String instagram;
int birthday;
String notes;
Contact(this.name, this.phoneNumber, this.location, this.rating,
this.instagram, this.birthday, this.notes);
Map<String, dynamic> toJson() => {
'Name': name,
'PhoneNumber': phoneNumber,
'Location': location,
'Rating': rating,
'Instagram': instagram,
'Birthday': birthday,
'Notes': notes,
};
Where final Contact contact; is currently declared
class NewContact extends StatefulWidget {
NewContact({Key key, #required this.contact}) : super(key: key);
final Contact contact;
#override
NewContactState createState() => NewContactState();
}
class NewContactState<T extends NewContact> extends State<T> {
final db = FirebaseFirestore.instance; //...etc
Where the Map is being called
await db
.collection("userData")
.doc(uid)
.collection("Contacts")
.add(contact.toJson());
Error = Undefined name 'contact'.
Since contact is defined in the class that extends statful widget, NewContact, and you want to access it's corresponding state class NewContactState, you should call it like this widget.contact.toJson().

The argument type 'Map<String, dynamic> Function()' can't be assigned to the parameter type 'Map<String, dynamic>'

This could initially was working but after firebase update, it is now giving me this error. I have added asterisks to the part giving the error. The error message has been added beneath the code.
import 'package:cloud_firestore/cloud_firestore.dart';
class Record {
final String name;
final int totalVotes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['totalVotes'] != null),
name = map['name'],
totalVotes = map['totalVotes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(**snapshot.data**, reference: snapshot.reference);
#override
String toString() => "Record<$name:$totalVotes>";
}
class Voters {
String uid;
String voteId;
String markedVoteOption;
}
The argument type 'Map<String, dynamic> Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.
Try the following:
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data(), reference: snapshot.reference);
data() is a method:
/// Contains all the data of this [DocumentSnapshot].
Map<String, dynamic> data() {
return _CodecUtility.replaceDelegatesWithValueInMap(
_delegate.data(), _firestore);
}
that returns a Map<String, dynamic>
It's because DocumentSnapshot.data() is a function that returns Map<String, dynamic>.
So, the answer is:
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data(), reference: snapshot.reference);
This works for me.
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data() as Map<String, dynamic>, reference: snapshot.reference);
Apparently all that was needed was parentheses on the maps
import 'package:cloud_firestore/cloud_firestore.dart';
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map(), {this.reference})
: assert(map()['name'] != null),
assert(map()['votes'] != null),
name = map()['name'],
votes = map()['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
This is how I solved it.
import 'package:cloud_firestore/cloud_firestore.dart';
class Record {
final String name;
final int totalVotes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map(), {this.reference})
: assert(map()['name'] != null),
assert(map()['totalVotes'] != null),
name = map()['name'],
totalVotes = map()['totalVotes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$totalVotes>";
}
class Voters {
String uid;
String voteId;
String markedVoteOption;
}
/// Contains all the data of this [DocumentSnapshot].
Map<String, dynamic> data() {
return _CodecUtility.replaceDelegatesWithValueInMap(
_delegate.data(), _firestore);
}

How can i reach data Firebase with Flutter

I am trying to fill my CurrentUser object with the same information as the uid of the logged in user when my users login to the application
My databaseService :
final CollectionReference userCollection =
Firestore.instance.collection('users');
Future<User> getCurrentUserData(String uid) async{
var doc = userCollection.document(uid);
And My Home Page :
class HomeScreen extends StatefulWidget {
final FirebaseUser currentUser;
HomeScreen({#required this.currentUser});
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
And My CurrentUser Model :
class CurrentUser {
static String name;
static String lastName;
static String uid;
static String phone;
static String addresses;
static String photoString;
static int cityId;
static int districtId;
static List<Loss> userLosses;
}
But i cant figure out connect them
If you are using the firebase authentication then you can use FiresbaseAuth.instance.currentUser, it will return a FirebaseUser object that will contain the info of the current user.
I figure it like this:
Future<User> getCurrentUserData(String uid)async {
var docRef = await userCollection.document(uid).get();
User currentUser = User.fromJson(docRef.data);
currentUser.uid=docRef.documentID;
return currentUser;
}
docRef.data is <String,dynamic> map and just i change my user class like this:
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['Name'].toString(),
lastName: json['LastName'].toString(),
phone: json['Phone'].toString(),
photoString: json['PhotoString'].toString(),
districtId: int.parse(json['DistrictId'].toString()),
cityId: int.parse(json['CityId'].toString()),
addresses: json['Addresess'].toString());
}

Flutter data to Json

How can I transfer QuerySnapshot object data from Firebase to JSON string?
Do I need to use
json.decode(qs)?
Thank you
1, Recommend you to use pkg: json_annotation to define model.
https://flutter.dev/docs/development/data-and-backend/json
2, When define model, let using bellow annotation for your model :
import 'package:json_annotation/json_annotation.dart';
part 'agent.g.dart';
#JsonSerializable(
anyMap: true
)
class Agent {
#JsonKey(
ignore: true
)
String id;
String name;
String avatar;
String email;
String phone;
String team;
String password;
Agent(this.name, this.avatar, this.email, this.phone, this.team, this.password);
factory Agent.fromJson(Map<String, dynamic> json) => _$AgentFromJson(json);
Map<String, dynamic> toJson() => _$AgentToJson(this);
}
3, Parser model with documentSnapshot:
Agent.fromJson(documentSnapshot.data)

I Want to add object has list of object in firebase ,flutter

I have object "Lawer" has List of objects "maker"
class Lawer{
final int x1;
final int x2;
final int x3;
final List<Maker>objects
Lawer({this.x1,this.x2,this.x3 ,this.objects});
Map<String, dynamic> toJson() =>
{
'x1':1 ,
'x2':1,
'x3':2,
};
}
class Maker{
final String lawerID;
final String customerID;
final bool connect;
Maker({this.lawerID,this.customerID,this.connect=false});
Map<String, dynamic> toJson() =>
{
'lawerID':lawerID,
'customerID':customerID,
'connect':connect,
};
}
CollectionReference dPReplies=FirebaseFirestore.instance.collection('lawers'); FirebaseFirestore.instance.runTransaction((Transaction tx)async {
var result=await dPReplies.add(lawer.toJson())
});
how to save this object in firebase"save object have some variables and list of objects"
Change this in your class:
Map<String, dynamic> toJson() =>
{
'x1':x1,
'x2':x2,
'x3':x3,
};
You need to capitalize Lawer
var result= await dPReplies.add(Lawer.toJson()) //instead of lawer.toJson

Resources