Dart - 需要两次点击提交按钮才能在firestore中保存数据

问题描述 投票:0回答:1

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

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

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个回答
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,),
          ],
        )
    ),
  ),
);
© www.soinside.com 2019 - 2024. All rights reserved.