You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Firestore的Todo创建方法转换为Firebase Realtime Database(RTDB)实现?

Solution

Let's start by clearing up a core difference between Firestore and Realtime Database that's causing your confusion:

  • Firestore creates a unique document ID when you call doc() without passing an ID.
  • For RTDB, you generate a unique child key using the push() method — this creates a new reference with a unique, timestamp-based key that works just like Firestore's auto-generated document ID.

Your original code was trying to fetch existing todo data first, which isn't necessary here. We just need to create and save a new todo entry. Here's the corrected implementation that matches your Firestore version's behavior:

class FirebaseApi {
  static Future<String> createTodo(Todo todo) async {
    // Create a new reference under the 'todo' node with a unique auto-generated key
    final newTodoRef = FirebaseDatabase.instance.ref().child('todo').push();
    
    // Assign the unique key to the todo's ID (just like Firestore's doc ID)
    todo.id = newTodoRef.key!;
    
    // Save the todo's JSON data to this new unique reference
    await newTodoRef.set(todo.toJson());
    
    // Return the unique ID, same as the original Firestore method
    return todo.id;
  }
}

Breakdown of key changes:

  • push() for unique keys: This replaces Firestore's doc() call. push() generates a unique key (e.g., -NxZ7k...) that ensures your new todo doesn't overwrite existing entries.
  • newTodoRef.key: This gives us the unique key we just created, which we assign to todo.id before saving — mirroring how you set todo.id = docTodo.id in Firestore.
  • set(todo.toJson()): We write the todo data directly to the new unique reference, storing it in RTDB at the path todo/{uniqueKey}.
  • Return the ID: The method returns the unique ID, just like your original Firestore implementation, so you can use it elsewhere in your code.

This code will work exactly as your Firestore version did: it creates a new todo with a unique ID, saves it to the database, and returns that ID for further use.


内容的提问来源于stack exchange,提问作者matti peterbull

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 08:38:10