文本字段上的赋值无效



我试图在Flutter中创建一个设置表单来存储两个整数,但有点困难。

我不断收到以下信息。

The argument type 'String?' can't be assigned to the parameter type 'String'.

它特别与这条线有关

onSaved: (val) => _metabolicRate = int.parse(val),

class _MetabolixSettingsState extends State<MetabolixSettings> {
int _metabolicRate = 0;
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
onSaved: (val) => _metabolicRate = int.parse(val),
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter your metabolic rate.',
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter your FATMAX heart rate.',
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
),
ElevatedButton(
onPressed: () {
// Validate returns true if the
// form is valid, or false otherwise.
_formKey.currentState!.save();
if (_formKey.currentState!.validate()) {
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Saving Settings')));
_formKey.currentState!.save();
ScaffoldMessenger.of(context).hideCurrentSnackBar();
}
FocusScopeNode currentFocus = FocusScope.of(context);
currentFocus.unfocus();
},
child: Text('Save'),
),
],
));
}
}

您会收到此错误,因为val可能是null值,但您无法将null值分配给parse((尝试添加"quot;如下

onSaved: (val) => _metabolicRate = int.parse(val!),

val是一个可为null的(String?(变量。在调用parse之前执行空检查。

onSaved: (val) {
if (val != null) {
_metabolicRate = int.parse(val);
}
},

最新更新