Null Safety in Dart

Issue

Recently dart realeased the new feature called null safety. I have a little bit confusion in how to create constructors with named parameters. When I follow the use of curly braces, I get an error.

Here is my code:

void main() {
  
}

class Student {
  String name = '';
  num age = 0;
  List<num> marks = [];
  
  Student({
    this.name,
    this.age,
    this.marks
    });
  
  void printStudentDetails() {
    print('Student Name: ' + this.name);
  }
}

And here is the error that I get:
enter image description here

Solution

Since the properties of your class are not nullable (type is String instead of String? for example), you either need to add required to the properties in the constructor, or provide a default value (which seems to be what you want to do).

  Student({
    this.name = '',
    this.age = 0,
    this.marks = [],
    });

You can now probably also make your properties final:

final String name;
final num age;
final List<num> marks;

Or, with the required keyword:

  Student({
    required this.name,
    required this.age,
    required this.marks,
    });

Answered By – TmKVU

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.