1

颤振表单保存错误有一个formKey,但我仍然收到错误

这是我的代码

class _TextFormFieldsState extends State<TextFormFields> {
  String _name = "";

  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(    
          primaryColor: Colors.red,
          accentColor: Colors.purpleAccent,
          errorColor: Colors.black
      ),
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.save),
        ),
        appBar: AppBar(
          title: Text("Text Form Field"),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          child: Form(
            key: formKey,
            autovalidateMode: AutovalidateMode.always,
            child: ListView(
              children: [
                TextFormField(
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.account_circle),
                    hintText: "Your Name",
                    labelText: "FullName",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter some text';
                    }
                    return null;
                  },
                  onSaved: (String? value) {
                    _name = value.toString();
                  },
                ),
                ElevatedButton(
                  onPressed: () {
                    // Validate returns true if the form is valid, or false otherwise.
                    if (formKey.currentState!.validate()) {
                      formKey.currentState.save();
                      debugPrint("Girilen ad $_name");
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
4

1 回答 1

3

这是由于Dart.flow analysis

您是一个实例变量,因此即使在您检查之后formKey也无法通过流分析检测到它。nullif

像这样使用它formKey.currentState!.save();

于 2021-05-16T17:59:08.013 回答