Flutter Firestore 1: improved example

Frank Paepens
3 min readNov 28, 2018

--

I was trying to find a good example of all CRUD operations(Create, Read, Update & Delete) for the combination of Flutter & Firestore.

Then I found this article from “grokonez”:

Flutter Firestore example — Firebase Firestore CRUD with ListView

I tried this example & it worked just fine. But it requires a lot of custom code. So, in order to minimize the amount of custom code I refactored this solution during the weekend. You can find it here on github.

I created a generic FirestoreService that you can just copy over into your own project. But in order to use this service you need to derive your classes from the class BaseModel:

Derive your model classes from BaseModel

And then you can just use the FirestoreService for each of your own classes (without having to modify it), as long as they derive from BaseModel (just pass your class name as a generic parameter). So after refactoring the original code from “grokonez”, I have now in the new implementation this setup:

The code looks like (see github for the full code):

Or more general:

Here is the code for BaseModel:

abstract class BaseModel {String _id;String get id => _id;

set id(String id) {
this._id = id;
}
BaseModel();Map<String, dynamic> toMap();fromMap(Map<String, dynamic> map); BaseModel createNew();
}

Then you derive your own classes from BaseModel, where you implement at least the methods:

  • toMap()
  • fromMap(Map<String, dynamic> map)
  • createNew()

For instance:

import 'package:firebase1/model/basemodel.dart';class Note extends BaseModel {
String _title;
String _description;
Note();Note.fromValues(this._title, this._description);Note.fromValuesWithId(String id, this._title, this._description) {
super.id = id;
}
String get title => _title;
String get description => _description;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
if (id != null) {
map['id'] = id;
}
map['title'] = _title;
map['description'] = _description;
return map;
}
Note.fromMap(Map<String, dynamic> map) {
this.id = map['id'];
this._title = map['title'];
this._description = map['description'];
}
Note fromMap(Map<String, dynamic> map) {
return Note.fromMap(map);
}
Note createNew() {
return Note();
}
}

And finally you can start using the generic FirestoreService (without modification) in your widgets.

Feel free to use in your own projects!

--

--

Frank Paepens

Partner at Appdnd: agency specialized in App Design & Development. Interests: technology, startups, travel & watersports.