Home > Software design >  Non-nullable instance field 'id' must be initialized
Non-nullable instance field 'id' must be initialized

Time:12-27

could anyone help me with how to manage this problem? I am new to Flutter, I am trying to code exactly likes the course's video, but I got this problem: 2. How could I change the 'status' item optional?

class Task {
 int id;
 String title;
 DateTime date;
 String priority;
 int status; // 0 - Incomplete, 1 - Complete

 Task({this.title, this.date, this.priority, this.status});
 Task.withId({this.id, this.title, this.date, this.priority, this.status});

CodePudding user response:

It's a null safety problem

solutions

make int nullable

int? id; // preferred

or

when calling constructor use required keyword

 Task({required this.id})

or

initialize default value to id

int id = 0;

CodePudding user response:

When you have named parameters constructors

Task({...});

and you do not specify required keyword in front of a variable the variable is optional. But, because your code is written in null-safety way, you must give it value or the other way it would be assigned null (which is illegal in this case).

Nullable var
If you want your value to be null-assignable you can write:

int? status;

Then you have to remember to check if the variable is null or not before you use it.

Default value
Another way is to use default value in the constructor:

Task({..., this.status = 0});

Required value
Or you can force developer to give it a value:

Task({..., required this.status});

Dartz
Another way is to use Option variable from Dartz package:

import 'package:dartz/dartz.dart';
...
Option<int> status;
Task({..., required this.status});

then you can pass none() or some(1) as a status.

Task(..., status: none());
Task(..., status: some(0));
  • Related