You can find all the details about fetching and storing data in Cloud Firestore here.
Firestore stores data within "documents", which are contained within "collections". Documents can also contain nested collections. For example, our users would each have their own "document" stored inside the "Users" collection. The collection method allows us to reference a collection within our code.
To add an entry to Firestore you need to pass a Map<String, dynamic>
to either the add()
function of the collection or set()
function of the document.
You can do something like this to send data.
await FirebaseFirestore.instance.collection('users').add({
'full_name': fullName, // John Doe
'company': company, // Stokes and Sons
'age': age // 42
});
Or, you can alternatively do:
await FirebaseFirestore.instance.collection('users').add(
userModel.toJson(),
);
where, toJson()
is
Map<String, dynamic> toJson() => {
"full_name": fullName,
"company": company,
"age": age,
};
To read a collection or document once, call the Query.get or DocumentReference.get methods.
class GetUserName extends StatelessWidget {
final String documentId;
GetUserName(this.documentId);
@override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return Text("Full Name: ${data['full_name']} ${data['last_name']}");
}
return Text("loading");
},
);
}
}
As to answer your question:
My question is: Why do they convert it to json? Is it always required? Is this for Firestore or Realtime Database?
JSON (JavaScript Object Notation) is a lightweight format that is used
for data interchanging. It is based on a subset of JavaScript language
(the way objects are built-in JavaScript). As stated in the MDN, some
JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the
'old' days, web services used XML as their primary data format for
transmitting back data, but since JSON appeared (The JSON format is
specified in RFC 4627 by Douglas Crockford), it has been the preferred
format because it is much more lightweight
You can refer to this answer for more information on JSON.
To sum up, JSON or Maps are used for data transfers as this provides the data in a well-structured way (key-value pair). And it's easy to read compared to other data transfer formats like CSV.