如何将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'sdoc()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 totodo.idbefore saving — mirroring how you settodo.id = docTodo.idin Firestore.set(todo.toJson()): We write the todo data directly to the new unique reference, storing it in RTDB at the pathtodo/{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
相关产品推荐
相关产品推荐

