Skip to content

Instantly share code, notes, and snippets.

@loicgeek
Last active July 1, 2020 12:08
Show Gist options
  • Save loicgeek/3fe989825c6195b96538a87e2feada91 to your computer and use it in GitHub Desktop.
Save loicgeek/3fe989825c6195b96538a87e2feada91 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:todo_app_getx/todo/models/todo.model.dart';
class TodoService {
CollectionReference todosRef = Firestore.instance.collection("todos");
Stream<Iterable<Todo>> findAll(userId) {
return todosRef
.where("user_id", isEqualTo: userId)
.getDocuments()
.then((value) {
return value.documents.map((e) => Todo.fromSnapshot(e)).toList();
}).asStream();
//Here we are converting the firebase snapshot to a stream of user todo list.
}
Future<Todo> findOne(String id) async {
var result = await todosRef.document(id).get();
return Todo.fromSnapshot(result);
}
Future<Todo> addOne(String userId, String title, {bool done = false}) async {
var result =
await todosRef.add({"user_id": userId, "title": title, "done": done});
return Todo(id: result.documentID, title: title, done: done);
}
Future<void> updateOne(Todo todo) async {
todosRef.document(todo.id).updateData(todo.toJson());
}
deleteOne(String id) {
todosRef.document(id).delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment