Flutter Validator String Requires Null Aware But Compiler Warns Not Needed

Issue

I have a 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),
    ),
  ),
))),

This gives a warning:

warning: The ‘!’ will have no effect because the receiver can’t be
null. (unnecessary_non_null_assertion at [athelite]
lib\Pages\PlayerEditPageDefaultState.dart:427)

And so I remove the exclamation mark and then it turns into an error:

error: The property ‘length’ can’t be unconditionally accessed because the receiver can be ‘null’. (unchecked_use_of_nullable_value at [athelite] lib\Pages\PlayerEditPageDefaultState.dart:425)

There’s just no pleasing the compiler! What is the correct way to do this with Flutter 2.0?

Solution

The first warning is listed in this documentation

The analyzer produces this diagnostic when the operand of the ! operator can’t be null.

This is because you are using the operator ! in 2 sides of the same && operator:

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

If the first condition is fulfill, the second condition will operate on a non-null value of operand input, which produce the above warning.

To shut it down, simply removing the ! on the right side:

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

Answered By – Bach

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.