Search code examples
flutterdartdart-null-safety

How to tell Flutter that a variable can be null in the right way (Null Safety)?


I have a question about Flutter and Null Safety.

For example I have this lines of code:

  Future<dynamic> isLoggedIn() async {
    Account account = Account(client);
    Response? result = await account.get();
    if (result == null) {
      print(true);
    }
  }

I've marked result as nullable variable with Response?. So result can be null. Why Visual Studio gives me the warning The operand can't be null, so the condition is always false., if I check if result == null?

Do I misunderstand the concept of Null Safety? :-)


Solution

  • As also suggested by julemand101, the behavior of your ide is due to the fact that, when a variable is set using a method that returns a non-nullable type, the dart analyzer knows with certainty that the variable is not null (despite the type with which you declared the variable would allow null).

    I too was surprised a little by the warning, because if you declare the variable by specifying its type, instead of using var, I would expect the dart analyzer to understand that the intent of the developer is to guard against possible changes. Then, thinking about it, I realized that if the method changed the signature and returned a nullable type, the compiler would force the developer to perform a null check, so in fact there is no reason to execute such a check until it is really needed.

    However, you can make the warning disappear by using the comment // ignore: unnecessary_null_comparison or through the file analysis_options.yaml:

    analyzer:
      errors:
        unnecessary_null_comparison: ignore
    

    Edit:

    the request can return null from server side.

    If your account.get() method could return null, the ide would not report that warning to you. So I guess it's the signature of your method which is incorrect.

    However, as for the question in the title ("the right way to tell Flutter that a variable can be null"), by declaring the variable as nullable you are leaving yourself the option of re-evaluating the variable with null or with a nullable type (and in that case then the null check would make sense).