从 Firestore API 转换为 firebase rtdb api

transform from Firestore API to firebase rtdb api

最近我正在学习通过教程创建事件,但原始事件是在 firestore 中创建的,我正在尝试使用 firebase rtdb,

这里是原代码:

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;
  }
}

这是我创建的代码,对不起,我的基础知识现在很好,不知道我应该做什么 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;

  }
}

能否让我知道如何创建相同的方法,但对于 firebase rtdb,提前致谢!

此 Firestore 调用为您提供了对 todo 集合中不存在的新文档的引用:

final docTodo = FirebaseFirestore.instance.collection('todo').doc();

相当于实时数据库中的这个是:

final todoRef = FirebaseDatabase.instance.ref("todo").push();

然后要将 JSON 存储到 Firestore 中的该文档,您需要执行以下操作:

await docTodo.set(todo.toJson());

实时数据库中的等价物是:

await todoRef.set(todo.toJson());

如果您的代码的其他部分有错误,我建议您的 createTodo 方法的功能在 Firestore 和实时数据库实现之间保持完全相同。

例如,我假设 Todo todo 对象在实现之间完全相同。如果不是,则问题不太可能出在数据库 API 调用中,但可能出在 Todo.

的实现中