In this post we are going to discuss how you can create a user model for a flutter app and also convert the DocumentSnapshot from Firebase Firestore into a UserModel object.
To create a user model in Flutter, you can follow these steps:
- Create a new Dart file and name it
user_model.dart
. - Import the
firebase_auth
package. - Define a class called
UserModel
. - Add the properties that you want to store in your user model.
- Create a constructor for the
UserModel
class. - Implement the
fromDocument
method to convert aDocumentSnapshot
from Firebase Firestore into aUserModel
object.
Here is an example of a user model in Flutter:
import 'package:firebase_auth/firebase_auth.dart'; class UserModel { String uid; String email; String name; UserModel({ required this.uid, required this.email, required this.name, }); factory UserModel.fromDocument(DocumentSnapshot doc) { return UserModel( uid: doc.data()['uid'], email: doc.data()['email'], name: doc.data()['name'], ); } }
This user model has three properties: uid
, email
, and name
. The uid
property is the unique identifier for the user in Firebase Firestore. The email
property is the user’s email address. The name
property is the user’s name.
The fromDocument
method converts a DocumentSnapshot
from Firebase Firestore into a UserModel
object. This method is useful when you need to retrieve a user model from Firebase Firestore.
Once you have created the user model, you can use it to store user data in Firebase Firestore. You can also use the user model to access user data from Firebase Firestore.
Here are some additional resources that you may find helpful:
- Firebase Authentication documentation: https://firebase.google.com/docs/auth/
- Firebase Firestore documentation: https://firebase.google.com/docs/firestore/
- Flutter Fire documentation: https://firebase.flutter.dev/