Home > database >  What am I supposed to using this toJson function for?
What am I supposed to using this toJson function for?

Time:11-07

I copied this code from somewhere online that said that it is good to use a model for your data interfacing. I've used the fromJson function a lot so far, but never the toJson function since anytime I need to write data to Firebase the built-in functions let me write in the JSON right then and there. When should I be using this toJson and how would I use it?

  ModelFriend.fromJson(Map<dynamic, dynamic>? json): //Transform JSON into model
        createDate = json?['createDate'] as String,
        modifiedDate = json?['modifiedDate'] as String,
        stat = json?['stat'] as String,
        uid = json?['uid'] as String,
        username = json?['username'] as String;

  Map<dynamic, dynamic> toJson() => <dynamic, dynamic>{ //Transforms model into JSON
    'createDate': createDate,
    'modifiedDate': modifiedDate,
    'stat': stat,
    'uid': uid,
    'username': username,
  };

CodePudding user response:

When we want to add documents to Cloud Firestore in Flutter, we can use the following code:

await firestore.doc(documentPath).set(data);

The type of the data variable is Map<String, dynamic>, so you need to convert the model to a map like this:

final Model model = Model(
  name,
  email,
);

await firestore.doc(documentPath).set(model.toJson());

Also, if you use the code below, you may enter the wrong field and get an error:

await firestore.doc(documentPath).set({
  "naem": name, // Typo, "name" becomes "naem"
  "email": email,
});

So, the answer is, we need toJson to convert the model to a map and add it to Cloud Firestore.

  • Related