【问题标题】:Dart - Need to hit submit button twice in order to save data in firestoreDart - 需要点击两次提交按钮才能将数据保存在 Firestore 中
【发布时间】:2019-04-23 21:45:12
【问题描述】:

上下文:我正在构建一个表单来为我的高级项目存储一些简单的用户信息。有 3 个字段和一个提交按钮。用户信息存储在用户文档中的firestore中。

问题:当我点击提交时,正在更新的用户文档中的字段设置为空。然后为了更新用户文档中的字段,需要再次点击提交按钮。

userSettingsPage.dart

void _submitForm() {
final FormState form = _formKey.currentState;

var userManager = new UserManager();
userManager.updateUser(updatedUser, mCurrentUser.uid);

if (!form.validate()) {
  showMessage('Form is not valid!  Please review and correct.');
} else {
  form.save(); //This invokes each onSaved event
 }
}

bool isValidUserCode(String input) {
RegExp regex = new RegExp('');
switch(input){
  case '123456789': {
    newUserRole = "professor";
    regex = new RegExp('123456789');
  }
  break;
  case '987654321': {
    newUserRole = "security";
    regex = new RegExp('987654321');
  }
  break;
  case '666': {
    newUserRole = "student";
    regex = new RegExp('666');
  }
  break;
  case '': {
     regex = new RegExp('');

  }
}
return regex.hasMatch(input);

}


Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
  key: _scaffoldKey,
  appBar: new AppBar(
    title: new Text('Settings'),
  ),
  body: new Container(
    padding: new EdgeInsets.all(20.0),
    child: new Form(
        key: _formKey,
        autovalidate: true,
        child: new ListView(
          children: <Widget>[
            new TextFormField(
              decoration: new InputDecoration(
                hintText: 'Name',
                labelText: 'Your Name'
              ),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter some text';
                  }
                },
                onSaved: (val) => updatedUser.name = val
            ),
            new TextFormField(
                decoration: new InputDecoration(
                    hintText: '1234567',
                    labelText: 'ID number'
                ),
              inputFormatters: [new LengthLimitingTextInputFormatter(7)],
                onSaved: (val) => updatedUser.ID = val
            ),
            new TextFormField(
                obscureText: true,
                decoration: new InputDecoration(
                    hintText: 'User Role Code',
                    labelText: 'Enter code (for faculty and staff only)',
                ),
                validator: (value) => isValidUserCode(value) ? null : 'Not a valid code',
                onSaved: (value) => updatedUser.role = newUserRole,
            ),
            new Text("Bugs suck, please hit submit button twice in order to send data.", textAlign: TextAlign.center,),
            new Container(
                padding: const EdgeInsets.only(left: 40.0, top: 20.0, right: 40.0),
                child: new RaisedButton(
                  child: const Text('Submit'),
                  onPressed: _submitForm,
                )
            ),
            new Text("Changes will take effect next time you close and reopen page.", textAlign: TextAlign.center,),
          ],
        )
    ),
  ),
);

userManager.dart

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final Firestore _firestoreDB = Firestore.instance;


Future<void> updateUser(User user, String uid) async {
  Map<String, dynamic> userData = Map();
  userData["name"] = user.name;
  userData["ID"] = user.ID;
  userData["role"] = user.role;
  Firestore.instance.collection("users").document(uid).setData(userData, merge: true);
}

不知道问题出在哪里。

【问题讨论】:

    标签: android firebase dart flutter google-cloud-firestore


    【解决方案1】:

    如下使用控制器从 TextFormField 中获取文本,它会在 _submitForm() 调用时从 TextFormField 中获取文本并将其分配给 updatedUser 属性:

    void _submitForm() {
    final FormState form = _formKey.currentState;
    
    setState(() {
        updatedUser.name = controllerName.text;
        updatedUser.ID = controllerID.text;
        updatedUser.role = controllerRole.text;
    });
    
    var userManager = new UserManager();
    userManager.updateUser(updatedUser, mCurrentUser.uid);
    
    if (!form.validate()) {
      showMessage('Form is not valid!  Please review and correct.');
    } else {
      form.save(); //This invokes each onSaved event
     }
    }
    
    final TextEditingController controllerName = TextEditingController();
    final TextEditingController controllerID = TextEditingController();
    final TextEditingController controllerRole = TextEditingController();
    
    
    Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text('Settings'),
      ),
      body: new Container(
        padding: new EdgeInsets.all(20.0),
        child: new Form(
            key: _formKey,
            autovalidate: true,
            child: new ListView(
              children: <Widget>[
                new TextFormField(
                    controller: controllerName,
                  decoration: new InputDecoration(
                    hintText: 'Name',
                    labelText: 'Your Name'
                  ),
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Please enter some text';
                      }
                    },
                    onSaved: (val) => updatedUser.name = val
                ),
                new TextFormField(
                    controller: controllerID,
                    decoration: new InputDecoration(
                        hintText: '1234567',
                        labelText: 'ID number'
                    ),
                  inputFormatters: [new LengthLimitingTextInputFormatter(7)],
                    onSaved: (val) => updatedUser.ID = val
                ),
                new TextFormField(
                    controller: controllerRole,
                    obscureText: true,
                    decoration: new InputDecoration(
                        hintText: 'User Role Code',
                        labelText: 'Enter code (for faculty and staff only)',
                    ),
                    validator: (value) => isValidUserCode(value) ? null : 'Not a valid code',
                    onSaved: (value) => updatedUser.role = newUserRole,
                ),
                new Text("Bugs suck, please hit submit button twice in order to send data.", textAlign: TextAlign.center,),
                new Container(
                    padding: const EdgeInsets.only(left: 40.0, top: 20.0, right: 40.0),
                    child: new RaisedButton(
                      child: const Text('Submit'),
                      onPressed: _submitForm,
                    )
                ),
                new Text("Changes will take effect next time you close and reopen page.", textAlign: TextAlign.center,),
              ],
            )
        ),
      ),
    );
    

    【讨论】:

    • 嘿,这很好用,只是现在我的 isValidUserCode 函数不起作用,只是给 Firestore 用户输入的代码而不是确定的角色
    • 我明白了,在您的代码中,我将 controllerRole.text 替换为 newUserRole。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2012-09-11
    相关资源
    最近更新 更多