【问题标题】:Save data based on userid to firebase根据用户 ID 将数据保存到 Firebase
【发布时间】:2021-09-03 20:09:28
【问题描述】:

我正在尝试制作一个财务跟踪应用程序。在使用应用程序之前,我使用 Firebase 身份验证(它有效)为用户登录。但我想根据用户ID记录用户财务。我怎样才能做到这一点?任何人都可以帮助我,因为我是 Flutter 的新手。对于下面的代码,事务存储在 firebase 中,但我不是基于用户 ID。我只关注 Youtube 上的教程,但我找不到基于用户 ID 的教程请帮助,谢谢!

class RecordExpense extends StatefulWidget {
      @override
      _RecordExpenseState createState() => _RecordExpenseState();
    }
    
    class _RecordExpenseState extends State<RecordExpense> {
      DatabaseReference _ref;
      final date = TextEditingController();
      final category = TextEditingController();
      final amount = TextEditingController();
      final description = TextEditingController();
      final FirebaseAuth auth = FirebaseAuth.instance;
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
    
      @override
      String selectExpense;
    
      final expenseSelected = TextEditingController();
    
      List <String> expensecategories = [
        "Food",
        "Social Life",
        "Transportation",
        "Beauty",
        "Household",
        "Education",
        "Health",
        "Gift",
        "Other"
      ];
      DateTime _selectedDate;
    
      void initState(){
        _ref = FirebaseDatabase.instance.reference().child('Transaction');
      }
      Widget build(BuildContext context) {
        return new Form(
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(20.0),
    
              child: Column(
                key: _formKey,
                mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                  Container(
                    child : TextField(
                      cursorColor: Colors.grey,
                      controller: date,
                      onTap: () {
                        _selectDate(context);
                      },
                      decoration: InputDecoration(
                        labelText: "Date",
                        labelStyle: TextStyle(fontSize: 18.0, color: Colors.black),
                        hintText: "Select Date",
                        enabledBorder: UnderlineInputBorder(
    
                          borderSide: BorderSide(color: secondary),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: secondary),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    //padding: EdgeInsets.all(20.0),
                    child: TextField(
                      cursorColor: Colors.grey,
                      controller: amount,
                      decoration: InputDecoration(
                        labelText: "Amount",
                        labelStyle: TextStyle(fontSize: 18.0, color: Colors.black),
                        hintText: "Amount",
                        enabledBorder: UnderlineInputBorder(
    
                          borderSide: BorderSide(color: secondary),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: secondary),
                        ),
                      ),
                      keyboardType: TextInputType.number,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 20.0),
                    child: Container(
                      decoration: BoxDecoration(
                        border : Border.all(color: secondary),
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                      child: DropDownField(
                        controller: expenseSelected,
                        hintText: "Select Category",
                        labelText: "Category",
                        enabled: true,
                        itemsVisibleInDropdown: 4,
                        items: expensecategories,
                        onValueChanged: (dynamic value)
                        {
                          selectExpense = value;
                        },
                        value: selectExpense,
                        required: false,
                      ),
                    ),
                  ),
    
    
                  Container(
                    //padding: EdgeInsets.all(20,0),
                    child: TextField(
                      cursorColor: Colors.grey,
                      controller: description,
                      maxLines: 2,
                      decoration: InputDecoration(
                        labelText: "Descriptions",
                        labelStyle: TextStyle(fontSize: 18.0, color: Colors.black),
                        hintText: "Expense Description",
                        enabledBorder: UnderlineInputBorder(
    
                          borderSide: BorderSide(color: secondary),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: secondary),
                        ),
                      ),
                    ),
                  ),
                  Container(
                      padding: EdgeInsets.only(top: 25.0, left: 20.0, right: 20.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget> [
                          Expanded (
                            child: ElevatedButton(
    
                              onPressed: () {
                                saveRecord();
                              },
                              child: Text("Save".toUpperCase(), style: TextStyle (
                                fontSize: 14,
                              )),
                              style: ButtonStyle(
                                padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(15)),
                                foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
                                backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
                                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(15.0),
                                      side: BorderSide(color: secondary)
                                  ),
                                ),
                              ),
    
                            ),
                          ),
                          SizedBox(width: 20, height: 10),
                          Expanded(
                            child: ElevatedButton(
                              onPressed: () {
                                clearButton();
                              },
                              child: Text("Clear".toUpperCase(), style: TextStyle (
                                  fontSize: 14
                              )),
                              style: ButtonStyle(
                                padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(15)),
                                foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
                                backgroundColor: MaterialStateProperty.all<Color>(Colors.pink),
                                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                  RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(15.0),
                                      side: BorderSide(color: secondary)
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      )
                  ),
                ],
              ),
            ),
          ),
        );
      }
      void saveRecord() async {
        User user = await auth.currentUser;
        //DocumentReference documentReference = Firestore.instance.collection("Transaction").document(user.uid);
        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,
        };
        _ref.push().set(transaction).then((value) {
          Navigator.pop(context, TransactionDaily());
        });
      }
      void clearButton(){
        date.clear();
        amount.clear();
        category.clear();
        description.clear();
      }
      void dispose(){
        super.dispose();
        date.dispose();
        amount.dispose();
        category.dispose();
        description.dispose();
      }
      _selectDate(BuildContext context) async {
        DateTime newSelectedDate = await showDatePicker(
            context: context,
            initialDate: _selectedDate != null ? _selectedDate : DateTime.now(),
            firstDate: DateTime(2000),
            lastDate: DateTime(2040),
            builder: (BuildContext context, Widget child) {
              return Theme(
                data: ThemeData.dark().copyWith(
                  colorScheme: ColorScheme.dark(
                    primary: secondary,
                    onPrimary: Colors.black,
                    surface: primary,
                    onSurface: Colors.white,
                  ),
                  dialogBackgroundColor: Colors.black,
                ),
                child: child,
              );
            });
    
        if (newSelectedDate != null) {
          _selectedDate = newSelectedDate;
          date
            ..text = DateFormat.yMMMd().format(_selectedDate)
            ..selection = TextSelection.fromPosition(TextPosition(
                offset: date.text.length,
                affinity: TextAffinity.upstream));
        }
      }
    }
    class AlwaysDisabledFocusNode extends FocusNode {
      @override
      bool get hasFocus => false;
    }

【问题讨论】:

    标签: firebase flutter google-cloud-firestore firebase-authentication


    【解决方案1】:
    DatabaseReference userId = _ref.push();
      print('Pushed Key' + userId.key);
      id = userId.key;
      userId.set(data);
    

    将此添加到您的 void saveRecord() 函数中。

    这里你还会在控制台上获取推送的按键数据。

    【讨论】:

    • 嗨,感谢您的回复。但我仍然在“id”和“data”中遇到错误,它显示未定义的名称“id”和未定义的名称“数据”。我该怎么办?
    • 声明为字符串id;在您的有状态类和“数据”中,这里是您的 firebase 实时数据库根节点名称。根据您的 firebase 实时数据库节点名称进行更改。
    • @Newuser 您是否设法使用 Yash Dhande 建议的解决方案修复了错误?
    • 嗨,我没有。我将实时 firebase 更改为 Firestore @Farid Shumbar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多