Home > other >  Why is manual null check required when ? operator is there in Flutter?
Why is manual null check required when ? operator is there in Flutter?

Time:03-04

String playerName(String? name) {
  if (name != null) {
    return name;
  } else {
    return 'Guest';
  }
}

? checks whether name is null or not, then why is special if (name != null) { condition required?

CodePudding user response:

The String? name means that the parameter name is nullable as you can see lower in the code the if statement then checks if your parameter is not null.

Dart docs definition:

If you enable null safety, variables can’t contain null unless you say they can. You can make a variable nullable by putting a question mark (?) at the end of its type. For example, a variable of type int? might be an integer, or it might be null. If you know that an expression never evaluates to null but Dart disagrees, you can add ! to assert that it isn’t null (and to throw an exception if it is). An example: int x = nullableButNotNullInt!

Link to docs

  • Related