0

Hi I'm trying to create generic API response class in flutter application and I'm getting this error

class ApiResponse<T> {
  Status status;
  T data;
  String message;

  ApiResponse.loading(this.message) : status = Status.LOADING;
  ApiResponse.completed(this.data) : status = Status.COMPLETED;
  ApiResponse.error(this.message) : status = Status.ERROR;

  @override
  String toString() {
    return "Status : $status \n Message : $message \n Data : $data";
  }
}

enum Status { LOADING, COMPLETED, ERROR }

IDE complains about below error

Non-nullable instance field 'data' must be initialized. Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'

Could anyone tell me what is wrong wiht my code?

Ajantha Bandara
  • 1,473
  • 15
  • 36

1 Answers1

3

It is because like the error says, data field has a non-nullable type T. If you want to allow null for the field data, you will need to make its type nullable by putting a ? like so.

T? data;

Similarly, you will also need to make message field nullable.

String? message;

To see other ways you can go about this and to understand null-safety better, I'd suggest reading this.

Jigar Patel
  • 4,953
  • 1
  • 12
  • 20