...
/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.
We'll cover the following...
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.
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, includingid
(nullable),region
,username
,age
,biography
, andno_of_trees
.Lines 11–18: The properties are initialized using a constructor that takes the required values for
username
,age
,biography
,no_of_trees
, andregion
, and an optionalid
parameter.Lines 20–28: The
toJson()
method converts an instance ofUserData
into aMap
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 ...