0

I just started learning Dart and Flutter but i'm struggling on defining classes with null safety. I found two ways to define classes. First one is this:

class Student {
  String? firstName;
  String? lastName;
  int? grade;
  String? status;

  Student(String? firstName, String? lastName, int? grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
    this.status = "Geçti";
  }
}

But if i define like that i have to use exclamation mark to assing for example firstName to a Text Widget.

Other way i found is this:

class Student {
  late String firstName;
  late String lastName;
  late int grade;
  late String status;

  Student(String firstName, String lastName, int grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
    this.status = "Geçti";
  }
}

I guess this way works fine but i'm not sure if there are any better ways or which one i should use. I would be glad if anyone can help, thank you.

hakanAkdogan
  • 223
  • 2
  • 3
  • 10
  • 1
    See [this](https://stackoverflow.com/questions/66860060/in-flutter-dart-why-do-we-sometimes-add-a-question-mark-to-string-when-decl) answer. – abdev Jul 12 '21 at 21:50
  • 1
    You can avoid using `late` by using [initialization lists](https://stackoverflow.com/a/64548861/). For most of your members, you can use [Dart's syntactic sugar for initializing members from constructor parameters](https://dart.dev/guides/language/language-tour#constructors): `Student(this.firstName, this.lastName, this.grade)`. – jamesdlin Jul 12 '21 at 22:42

0 Answers0