微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter 验证器字符串需要 Null 感知但不需要编译器警告

如何解决Flutter 验证器字符串需要 Null 感知但不需要编译器警告

我有一个 TextFormField:

TextFormField(
  textAlign:
      TextAlign.center,autovalidateMode:
      AutovalidateMode
          .onUserInteraction,onChanged: (value) {},controller:
      firstNameTextInputController,validator: (input) =>                         //////////////////////////// HERE
      (input!.length <
                  51 &&
              input!.length >
                  1)
          ? null
          : "Invalid First Name",////// End
  style: TextStyle(
    color: HexColor
        .fromHex(
            "#000000"),),decoration:
      Inputdecoration(
    border: InputBorder
        .none,filled: true,hintStyle: Theme.of(
            context)
        .textTheme
        .subtitle1!
        .merge(TextStyle(
            color: HexColor
                .fromHex(
                    "#707070"))),hintText:
        "*Enter First Name",fillColor: HexColor
        .fromHex(
            "#ffffff"),focusedBorder:
        OutlineInputBorder(
      borderSide: BorderSide(
          color: HexColor
              .fromHex(
                  "#707070"),width: 5),borderRadius:
          BorderRadius
              .circular(
                  5),))),

这是一个警告:

警告:'!'将无效,因为接收器不能 无效的。 (unnecessary_non_null_assertion at [athelite] lib\Pages\PlayereditPageDefaultState.dart:427)

所以我删除了感叹号,然后它变成了一个错误

错误:无法无条件访问属性“length”,因为接收器可以为“null”。 (unchecked_use_of_nullable_value at [athelite] lib\Pages\PlayereditPageDefaultState.dart:425)

编译器根本无法取悦!使用 Flutter 2.0 执行此操作的正确方法是什么?

解决方法

第一个警告列在 this documentation

! 运算符的操作数不能为空时,分析器会生成此诊断信息。

这是因为您在同一个 ! 运算符的两侧使用了运算符 &&

...
(input!.length < 51 && input!.length > 1)
...

如果满足第一个条件,则第二个条件将对操作数 input 的非空值进行操作,从而产生上述警告。

要关闭它,只需删除右侧的 !

(input!.length < 51 && input.length > 1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。