Home > front end >  Non-nullable instance field 'httpRequestService' must be initialized
Non-nullable instance field 'httpRequestService' must be initialized

Time:08-07

I have the following code:

class UserService {

  HttpRequestService httpRequestService;

  // I got an error here: Non-nullable instance field 'httpRequestService' must be initialized.
  UserService({HttpRequestService? httpRequestService}) {
    this.httpRequestService = httpRequestService ?? initHttpRequestService();
  }
  
  initHttpRequestService() {
    return HttpRequestService();
  }

}

As you can see, an error occurred in the constructor. But the weird thing is, I've initialized the httpRequestService in the constructor. So why did I get this error?

CodePudding user response:

httpRequestService assigned inside constructor body inside { ...}

One way of avoiding this error is

  UserService({required HttpRequestService httpRequestService})
      : httpRequestService = httpRequestService;

But in your case, one is coming from an instance method. With above pattern late won't suppress the error in this case.

Static method will do the job while it belongs to the class rather than an instance of the class

class UserService {
    HttpRequestService httpRequestService;

  UserService({HttpRequestService? httpRequestService})
      : httpRequestService = httpRequestService ?? initHttpRequestService();

  static initHttpRequestService() {
    return HttpRequestService();
  }
}

Also, we can use late

class UserService {
  late HttpRequestService httpRequestService;

  UserService({HttpRequestService? httpRequestService}) {
    httpRequestService = httpRequestService ?? initHttpRequestService();
  }

  initHttpRequestService() {
    return HttpRequestService();
  }
}

CodePudding user response:

You can add late keyword before httpRequestService declaration

  late HttpRequestService httpRequestService;

or just make your variable nullable like this

 HttpRequestService? httpRequestService;
  • Related