Dart null safety: the operand cannot be null, so the condition is always true

Viewed 3184

I am trying to double-check if the User object is successfully created, but Null saftey says the operand cannot be null, so the condition is always true

What if in a scenario where the json data contains invalid type, in this case there might be some errors when creating the user object

class User {
  String? name;
  String? age;

  User({name, age}) {
    this.name = name;
    this.age = age;
  }

  factory User.fromJson(dynamic json) {
    return User(name: json['name'], age: json['age']);
  }
}

void main() {
  String data = '{name: "mike",age: "2"}';

  User user = User.fromJson(data);

  if (user != null) { // Warning: "The operand can't be null, so the condition is always true. Remove the condition."

  }
}

Please advise, Thank you! :)

1 Answers

If something wrong is going on creating your User object from a JSON input, it will, in your case, throw an Exception which will crash the program if not catch.

So the variable user cannot be null in your case which is what the warning is telling you.

If you want to have some kind of User.tryFromJson which returns null in case of any problems, you could add something like this to you User class:

  static User? tryFromJson(dynamic json) {
    try {
      return User.fromJson(json);
    } catch (_) {
      return null;
    }
  }

Also, some minor comments. Your User constructor does not make much sense since you could have written the following instead:

User({this.name, this.age});

Also, I would make both arguments required and prevent the nullable types. So something like this (also changed age to int):

class User {
  String name;
  int age;

  User({
    required this.name,
    required this.age,
  });

  factory User.fromJson(dynamic json) => User(
        name: json['name'] as String,
        age: json['age'] as int,
      );

  static User? tryFromJson(dynamic json) {
    try {
      return User.fromJson(json);
    } catch (_) {
      return null;
    }
  }
}

void main() {
  final data = '{name: "mike",age: 2}';
  final user = User.fromJson(data);
}
Related