无法将功能放入验证器中

Unable to put function in validator in flutter

class StudentValidationMixin{
  String validateFirstName(String value){
if(value.length<2){
  return "Name must be at least two characters";
}
}
}

我正在尝试使用容器函数的特性,当我进入验证器部分时,我无法 运行 我上面提到的代码。我在下面写道时遇到了问题

The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type.

      body: Container(
    margin: EdgeInsets.all(20.0),
    child: Form(
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(labelText:"Öğrenci Adı",hintText: "Engin"),
            validator: validateFirstName,
            onSaved: (String value){
              student.firstName=value;
            },

自然地,我在这个 (validator: validateFirstName) 部分也遇到了错误,这就是我得到的错误

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

我到处都找不到这个答案,但我知道答案藏在某个地方,我终于放弃了,想在这里问一下。我该如何解决这个错误?我学Flutter的trainer可以运行这个功能没有这些问题

你说得对,答案隐藏在某处,确实如此。

问题:

The body might complete normally, causing 'null' to be returned, but the return 
type, 'String', is a potentially non-nullable type.

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

原因:

我不知道“Jack of all Trade”VSC,但是,在 Android studio 中,当您将光标悬停在任何参数上时,pop-up 会告诉您输入的类型需要。

因此,对于 TextFormField 中的参数 validator,支持 Null Safety 的新 Flutter 版本可接受的类型是 String? Function(String?)?,如下图所示:

但是,它在您观看的(旧)视频中有效,因为在低于 Flutter 2.0(Null Safety)的版本中,类型为 String Function(String),如下图所示:

现在,您可以确定您收到的错误确实与版本有关。因为,你正试图在新版本中使用旧类型,就像这个函数一样:

class StudentValidationMixin{
  String validateFirstName(String value){
    if(value.length<2){
      return "Name must be at least two characters";
    }
  }
}

解决方案:

更改您的 validator() 类型如下:

class StudentValidationMixin{
  String? validateFirstName(String? value) {
    if(value.length<2){
      return "Name must be at least two characters";
    } else {
      return null;
    }
  }
}

看,我们在那里做了什么?我们将 return 类型更改为 nullable,这意味着该值可以为 null,并且应该是在验证器正确验证字符串的情况下。因为它 returns 是验证错误,当没有错误时, null 应该是 returned.

添加 ? 标记意味着告诉编译器特定变量的值可以为 null 并且可以是给定的类型。例如 int? count 的值可以是整数或 null,而 int count 的值只能是 integer 并且如果不是 NullPointerException =22=].

此外,NullSafety 附带的是感叹号 !,它告诉编译器即使变量被声明为 nullable,此时值也不是 null。对于前。声明为 int? count 的变量,输入到其中的值以及使用它的时间。用它作为 count! 告诉编译器,此时,它有一个值。