2021年4月7日星期三

Dart Null safety, need to use `!` even with with optional constructor parameter set in constructor body

I'm having to use the ! null-check override when accessing a field that has an optional constructor argument. I'm wondering if there's a better way to do this that I've not realized.

This optional, nullable field gets assigned a value in the constructor body if no argument is supplied.

class AuthService {    http.Client? httpClient;        AuthService({this.httpClient}) {      httpClient ??= http.Client();    }  }  

Later when using httpClient I need to provide ! even though it will never be null...

http.Response response = await httpClient!.post(createUri,            body: jsonEncode(requestBodyMap));  

... otherwise the dart analyzer tells me: The method post cannot be unconditionally invoked because the receiver can be null.

When I use the late keyword, Lint checking is telling me the "assign-if-null" will never happen...

class AuthService {    late http.Client httpClient;        AuthService({this.httpClient}) {      httpClient ??= http.Client(); // ← lint says this is useless & will never run    }  }  

... because httpClient can never be null.

Should I just ignore Lint?

Should I be doing something completely different?

https://stackoverflow.com/questions/66995919/dart-null-safety-need-to-use-even-with-with-optional-constructor-parameter April 08, 2021 at 08:46AM

没有评论:

发表评论