recently im learning to create a event from a tutorial, but the original one is made in firestore, and Im trying to use firebase rtdb,
here is original code:
class FirebaseApi {
static Future<String> createTodo(Todo todo) async {
final docTodo = FirebaseFirestore.instance.collection('todo').doc();
todo.id = docTodo.id;
await docTodo.set(todo.toJson());
return docTodo.id;
}
}
here is code I created, sorry my basic knowledge is now good, Idk what should i return
class FirebaseApi {
static Future<String> createTodo(Todo todo) async{
final todoRefMessages = FirebaseDatabase.instance.ref().child('todo');
final newTodo = FirebaseDatabase.instance.ref().child('todo').get().then((snapshot) async{
final json = Map<dynamic, dynamic>.from(snapshot.value);
final newTodo = Todo(
createdTime: Utils.toDateTime(json['createdTime']),
title: json['title'],
description: json['description'],
id: json['id'],
isDone: json['isDone'],
);
await todoRefMessages.set(newTodo.toJson());
return newTodo;
});
todo.id= newTodo.id;//here got error, The getter 'id' isn't defined for the type 'Future<Todo>
return newTodo.id;
}
}
could you please let me know how to create same method but for firebase rtdb, thanks in advance!
CodePudding user response:
This call to Firestore give you a reference to a new non-existing document in the todo collection:
final docTodo = FirebaseFirestore.instance.collection('todo').doc();
Is equivalent to this in the Realtime Database is:
final todoRef = FirebaseDatabase.instance.ref("todo").push();
Then to store the JSON to that document in Firestore you do:
await docTodo.set(todo.toJson());
The equivalent in the Realtime Database is:
await todoRef.set(todo.toJson());
If you have errors in other parts of your code, I recommend keeping the functionality of your createTodo method exactly the same between the Firestore and Realtime Database implementations.
For example, I assume that the Todo todo object is exactly the same between the implementations. If it isn't, the problem is less likely to be in the database API calls, but probably in the implementation of Todo.
