飞镖 不能无条件调用方法"validate",因为可以'null'接收方



我学习扑动,我有一个问题,我不能解决它。我正在尝试制作一个基于一些代码的计算器,这个错误出现

方法'validate'不能被无条件调用,因为接收者可以是'null'。尝试使用条件调用(使用'?.')或者向目标('!')添加空检查。

这是代码

import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
TextEditingController pesoController = TextEditingController();
TextEditingController alturaController = TextEditingController();
String _info = "Informe seus dados";
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _reset() {
setState(() {
pesoController.text = "";
alturaController.text = "";
_info = "Informe seus dados";
});
}
void _calculate() {
double peso = double.parse(pesoController.text);
double altura = double.parse(alturaController.text) / 100;
double imc = peso / (altura * altura);
setState(() {
if (imc < 18.6) {
_info = "Abaixo do Peso (${imc.toStringAsPrecision(2)})";
} else if (imc >= 18.6 && imc <= 24.9) {
_info = "Peso Ideal (${imc.toStringAsPrecision(2)})";
} else if (imc >= 24.9 && imc <= 29.9) {
_info = "Levemente acima do peso (${imc.toStringAsPrecision(2)})";
} else if (imc >= 24.9 && imc <= 34.9) {
_info = "Obesidade Grau I (${imc.toStringAsPrecision(2)})";
} else if (imc >= 34.9 && imc <= 39.9) {
_info = "Obesidade Grau II (${imc.toStringAsPrecision(2)})";
} else if (imc >= 40) {
_info = "Obesidade Grau III (${imc.toStringAsPrecision(2)})";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Calculador IMC"),
centerTitle: true,
backgroundColor: Colors.deepPurple,
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: _reset,
)
],
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
padding: EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Icon(Icons.person, size: 120, color: Colors.deepPurple),
TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: "Peso (KG)",
labelStyle: TextStyle(color: Colors.deepPurple)),
textAlign: TextAlign.center,
style: TextStyle(color: Colors.deepPurple, fontSize: 25),
controller: pesoController,
validator: (value) {
if (value!.isEmpty) {
return "Informe seu peso!";
}
},
),
TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: "Altura (CM)",
labelStyle: TextStyle(color: Colors.deepPurple)),
textAlign: TextAlign.center,
style: TextStyle(color: Colors.deepPurple, fontSize: 25),
controller: alturaController,
validator: (value) {
if (value!.isEmpty) {
return "Informe sua altura!";
}
},
),
Padding(
padding: EdgeInsets.fromLTRB(0.0, 15, 0.0, 15),
child: Container(
height: 50,
child: RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_calculate();
}
},
child: Text(
"Calcular",
style: TextStyle(color: Colors.white, fontSize: 25),
),
color: Colors.deepPurple,
),
)),
Text(_info,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.deepPurple, fontSize: 25))
],
),
),
),
);
}
}

解释如下:

让我们考虑一下这句话适用的行:

_formKey.currentState.validate()

的消息

方法'validate'不能被无条件调用,因为接收者可以是'null'。尝试将调用设置为有条件的(使用'?.')或向目标添加空检查('!')。

意味着在某些情况下,"validate"之前的属性,也就是"currentState"可能为空(详见https://dart.dev/null-safety)。

在实际为null的情况下,不能调用validate"方法,因为null没有validate"方法。换句话说,既然做了这个

null.validate()

是不允许的,调用"validate"方法处理为null(或者只能为null,如果您激活了null安全功能)的内容:dart试图告诉您必须处理null值的情况。在null安全语句之前,你可以这样写,你可以在运行时找到这种情况

事实上,在运行时_formKey.currentState"可以是您所期望的对象,但在某些特定情况下也可以为空。你必须决定如何处理它:你是否100%确定在这种情况下_formkey。currentstate "永远不能为空?还是你不确定?

此时您有两个选择:

  1. 使用"null断言操作符";(!.):手动告诉编译器调用"validate"方法在这一点上是完全安全的,例如,因为您已经确定,即使变量在某些情况下理论上可以为空,您已经检查了它,并且该特定情况是100%安全的。换句话说,它在代码的特定点中永远不会为空。注意,如果你错了,它会在运行时抛出一个错误(Null检查操作符用于Null值)。
_formKey.currentState!.validate();
  1. 使用' null感知操作符';(?.):您不确定在这种情况下currentState是否可以为null。你告诉你的编译器在底层写这个:
if(_formKey.currentState != null) {
_formKey.currentState.validate();
}

只需添加'!'或'?',在.validate()之前。所以这条线变化:

if (_formKey.currentState.validate()) {

:

if (_formKey.currentState!.validate()) {

这是因为dart 2.0中添加了null安全操作符。你可以在这个链接中阅读更详细的内容:https://dart.dev/null-safety

试试这样:

validator: (value) {
if (value!.length < 1) return 'Empty field';
return null;
}

尝试在validate()方法之前添加null安全

GlobalKey<FormState> _formKey = GlobalKey();
TextButton(
onPressed: () {
if(_formKey.currentState!.validate()){
***code
}

},
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
Colors.green.shade900),
),
child: const Text(
"Save",
style: TextStyle(color: Colors.white),
),
),
Use this one 

相关内容

最新更新