Search code examples
flutterdartdart-null-safety

Non-nullable instance field 'httpRequestService' must be initialized


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?


Solution

  • 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();
      }
    }