skip to Main Content

I’m learning Flutter and I’m making an app as a demo, but I couldn’t solve this error. Even though I have given values ​​to the parameter, when I run it, I get an error that it cannot be null.

student.dart code

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

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

main.dart code

List<Student> students = [Student("Engin", "Demiroğ", 75), Student("İsmail", "Güner", 65), Student("Aykut", "Elmas", 88), Student("Cengiz", "Han", 100)];

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo1"),
      ),
      body: buildBody(context),
    );
  }

  Widget buildBody(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
              itemCount: students.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(students[index].firstName);
              }),
        ),

The error I got

enter image description here

6

Answers


  1. Add the question mark with the type of each property to indicate that it is nullable:

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

    Dart is null-safe, so since you’re declaring new properties of a class without the question mark, it will interpret that the value will never be null, but initially their values are all null, thus the error. I suggest to read more on the null safety feature since it’s a pretty important concept for Dart/ Flutter.

    P/s: To use the nullable property (for example String? firstName, use it with ?? for those widgets that don’t take in nullable value. For example:

    Text(student.firstName ?? ‘Empty name’)
    

    Here, the ?? has meaning that, if student.firstName is null, use this Empty name string as value. Since Text requires a non-null value, we need to make sure that in case the firstName is null, we have a default value in place to avoid passing nullable value in.

    Login or Signup to reply.
  2. Dart has recently introduced null-safety. It prevents you from making a lot of mistakes. For more info: https://dart.dev/null-safety/understanding-null-safety

    The best way to solve your problem is to understand what variables can be nullable or non-nullable.

    class Student {
      String? firstName;
      String? lastName; ///nullable
      String status; /// non-nullable
      int? grade;
    
      Student({this.firstName, this.lastName, this.status = 'Geçti', this.grade});
    }
    

    In this case, only the variable status can’t be null, and it’s value is set to "Geçti" by the constructor. All the other variables can be null.

    Login or Signup to reply.
  3. Flutter can be serious concerning null values and initialization. Even if practically you assign values, it does not ‘believe’ you, and throws a build error. See here for example. But for as a quick fix you can mark the members of Student class as late, practically you promise to Flutter, that later you will assign values:

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

    You have many other options, but this one works as a starter, I tried it.

    Login or Signup to reply.
  4. From Dart 2.12 you need to specify if your parameters are nullable or vice versa. Please see below code

    class Student {
      final String firstName;
      final String lastName;
      final String status;
      final int grade;
    
      Student({required this.firstName, required this.lastName, required this.status, required this.grade,});
    }
    
    Login or Signup to reply.
  5. If you enable null safety, then you must initialize the values of non-nullable variables before you use them. Source: documentation for more info.

    Null safety is enabled by default. As stated there, you need to assign a default value for those variables.

    Your class can be rewritten using dart syntax sugar for initializing variables (documentation)

    class Student {
      String firstName = "";
      String lastName = "";
      String status = "";
      int grade = 0;
        
      Student(this.firstName, this.lastName, this.grade);
    }
    

    Using that syntax for initializing variables we don’t need to specify a default value for them, so removing the unnecesary default values:

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

    It’s also common to declare variables initialized in the constructor as final (can only be initialized once)

    class Student {
      final String firstName;
      final String lastName;
      final int grade;
      String status = "";
        
      Student(this.firstName, this.lastName, this.grade);
    }
    

    I recommend taking a look at the Dart language tour

    Login or Signup to reply.
  6. This happens because the type of your variables are not nullable but you didn’t initialize them with a value. To fix this use the keyword late.

    class Student {
      late String firstName;
      late String lastName;
      late String status;
      late int grade;
    
      Student(this.firstName, this.lastName, this.grade) {
        this.status = "Geçti";
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search