Ошибка в Dart - "a nullable expression can't be used as condition / an iterator"

Я учусь работать на Dart во фрейме Flutter. Вот простейший код, который по идее вопросов не вызывает, но компилятор ругается на на 22 и 24 строчки (ошибки описала в коде через комментарии).

void main() {
  var bob = user('bob', 40, true, ['footbal', 'skate']);
  bob.info();

  var alex = user('alex', 23, false, ['basketball']);
  alex.info();
}

class user {
  String? name;
  int? age;
  bool? isHappy;
  List<String>? hobbies;

  user([name, age, isHappy, hobbies]) {
    this.name = name;
    this.age = age;
    this.isHappy = isHappy;
    this.hobbies = hobbies;
  }
  void info() {
    var happy = isHappy ? 'happy' : 'not happy';//a nullable expression can't be used as condition
    print('user $name is $age yers old. he is $happy. His hobbies:');
    for (var el in hobbies) {//a nullable expression can't be used as an iterator in a for-in loop
      print(el);
    }
  }
}

Ответы (1 шт):

Автор решения: Grundy

При указании в определении типа ?, переменная может принимать null

bool? isHappy;
List<String>? hobbies;

В данном случае эти два поля могут быть null, поэтому их нельзя использовать там, где null недопустим.

Например в условии. В этом случае можно добавить проверку, например

var happy = isHappy == true ? 'happy' : 'not happy';

Так же можно использовать null-aware оператор, который позволяет указать, какое значение будет использоваться вместо null

for (var el in hobbies ?? [])

В итоге код может выглядеть так:

void info() {
  var happy = isHappy == true ? 'happy' : 'not happy';//a nullable expression can't be used as condition
  print('user $name is $age yers old. he is $happy. His hobbies:');
  for (var el in hobbies ?? []) {//a nullable expression can't be used as an iterator in a for-in loop
    print(el);
  }
}
→ Ссылка