【问题标题】:Flutter Validator String Requires Null Aware But Compiler Warns Not NeededFlutter Validator String 需要 Null Aware 但编译器警告不需要
【发布时间】:2021-06-26 00:30:06
【问题描述】:

我有一个 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)

于是我把感叹号去掉了,然后就变成了错误:

错误:无法无条件访问属性“长度”,因为接收者可以为“空”。 ([athelite] lib\Pages\PlayerEditPageDefaultState.dart:425 处的 unchecked_use_of_nullable_value)

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

【问题讨论】:

    标签: flutter validation dart-null-safety flutter2.0


    【解决方案1】:

    第一个警告列在this documentation

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

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

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

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

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

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

    【讨论】:

    • 呃,这很有道理——我以为我快疯了——非常感谢
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2016-11-03
    • 2017-11-29
    • 1970-01-01
    • 2020-11-29
    相关资源
    最近更新 更多