...

/

Read and Write Data from Cloud Firestore

Read and Write Data from Cloud Firestore

Learn data querying and query structure in reading and writing the Firestore database.

Data modeling

In this lesson, we’re going to model the data we’ll be retrieving from the user and mapping it to our Firestore database.

Defining the data model class

We start by creating a class to represent the data. The data we’re going to model includes username, age, region, no_of_trees, and biogrphy.We also need to know the type of data. For our case, most of the data will be of String type, but we also have age, which must be of type integer.

Press + to interact
import 'package:cloud_firestore/cloud_firestore.dart';
class UserData {
String? id;
String region;
String username;
int age;
String biography;
int no_of_trees;
UserData({
this.id,
required this.username,
required this.age,
required this.biography,
required this.no_of_trees,
required this.region,
});
toJson() {
return {
'username': username,
'age': age,
'biography': biography,
'no_of_trees': no_of_trees,
'region': region,
};
}
factory UserData.fromSnapshot(
DocumentSnapshot<Map<String, dynamic>> document) {
final json = document.data();
return UserData(
id: document.id,
username: json!['name'],
region: json!['region'],
age: json['age'],
biography: json['biography'],
no_of_trees: json['no_of_trees'],
);
}
}
  • Lines 3–9: The UserData class is defined, representing a user’s data. It has several properties, including id (nullable), region, username, age, biography, and no_of_trees.

  • Lines 11–18: The properties are initialized using a constructor that takes the required values for username, age, biography, no_of_trees, and region, and an optional id parameter.

  • Lines 20–28: The toJson() method converts an instance of UserData into a Map representation, suitable for storing the user data in Firestore. It maps the properties of the class to the corresponding keys in the map.

  • Lines 30–40: The fromSnapshot() factory ...

Access this course and 1400+ top-rated courses and projects.