Flutter新手求助:如何基于Firebase Authentication用户ID存储财务追踪应用交易数据至Firebase Database
Hey there! Let's get your transaction data tied to each user's ID—this is a common pattern with Firebase, and it's totally manageable even as a Flutter beginner. Here's how to adjust your code and structure things properly:
Step 1: Restructure Your Firebase Database
Right now, you're storing all transactions directly under a Transaction node. Instead, we'll create a user-specific structure:Transactions -> [USER_UID] -> [TRANSACTION_PUSH_ID]
This keeps each user's data isolated and makes it easy to fetch only their transactions later.
Step 2: Update the saveRecord Method
You already have code to get the current user—we just need to use that uid to target the right database node. Here's the revised method with explanations:
void saveRecord() async { // Get the currently logged-in user User? user = await auth.currentUser; // Make sure the user is actually logged in before saving if (user == null) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Please log in first to save transactions!')), ); return; } String dates = date.text; String values = amount.text; String descriptions = description.text; Map<String, String> transaction = { 'dates': dates, 'amount': 'RM' + values, 'category': selectExpense, 'descriptions': descriptions, // Optional: Store the user ID in the transaction itself for extra clarity 'userId': user.uid, }; // Create a reference to the current user's transaction node DatabaseReference userTransactionsRef = FirebaseDatabase.instance .reference() .child('Transactions') .child(user.uid); // Push the transaction to their personal node userTransactionsRef.push().set(transaction).then((value) { Navigator.pop(context, TransactionDaily()); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Transaction saved successfully!')), ); }).catchError((error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Failed to save: ${error.toString()}')), ); }); }
Step 3: (Critical) Set Up Firebase Security Rules
To make sure users can only access their own data, update your Firebase Realtime Database rules to this:
{ "rules": { "Transactions": { "$uid": { ".read": "auth != null && auth.uid == $uid", ".write": "auth != null && auth.uid == $uid" } } } }
This blocks any unauthorized access to other users' transactions.
Step 4: Fetching User Transactions (Bonus!)
When you want to display the user's transactions later, you'll fetch from their specific node like this:
void loadUserTransactions() async { User? user = await auth.currentUser; if (user == null) return; DatabaseReference userTransactionsRef = FirebaseDatabase.instance .reference() .child('Transactions') .child(user.uid); // Listen for real-time updates to the user's transactions userTransactionsRef.onValue.listen((event) { DataSnapshot snapshot = event.snapshot; if (snapshot.value != null) { Map<dynamic, dynamic> transactionMap = snapshot.value as Map; // Convert the map to a list of transaction objects for your UI List<dynamic> userTransactions = transactionMap.values.toList(); // Update your state with the transactions here } }); }
This setup ensures every transaction is linked to the user who created it, keeps data secure, and makes it easy to manage per-user records.
内容的提问来源于stack exchange,提问作者New user

