In the following code p param is non-nullable but p field is nullable so we can not use initializing formal.
// @dart = 2.9
class A {
A({required String p}) : p = p;
String? p;
}
Sounds like you want an initializing formal with a type annotation, which is fine:
class A {
A({required String this.p});
String? p;
}
However, there's a false positive hint saying 'Don't type annotate initializing formals'.
Thanks! The spurious 'Don't type annotate initializing formals' is not present in a fresh dartanalyzer (commit a3815b659047cfc6b63d41d180aa1ca1b781ee68), so there's no need to follow up on that.
But it's not obvious that you have to type annotate the initializing formal to make it works. Either the message could mention that (or an example in the doc) or we should exclude this case from the lint cases.
Ah, I was thinking about typed initializing formals in general (e.g., they can be used as a kind of union type constraint):
class WrapIntOrString {
final Object _o; // Actual type: `int | String`.
WrapIntOrString.wrappingInt(int this._o);
WrapIntOrString.wrappingString(String this._o);
}
In this case the different types are the point, and anyone who wants this effect would know that a type annotation is needed.
In the case with a String? variable vs. a String initializing formal, I think you'd want the type explicitly anyway: If the constructor argument must be non-null, but the instance variable can be null you'd use this, and if it is OK to pass null as the constructor argument you'd use this:
class A {
A({required this.p});
String? p;
}
Doesn't this set of alternatives eliminate the need to use code which will trigger prefer_initializing_formals?
Yes adding the type will fix the issue. I only have to wait for a fresh analyzer as I face the _Don't type annotate initializing formals_ message. Thanks!
Flutter is on Dart 2.10.0-38.0.dev, which includes the commit https://github.com/dart-lang/sdk/commit/b0d007a931f5d5bd5e04a413899a0aad8bcf4223 referenced above in https://github.com/dart-lang/linter/issues/2192#issuecomment-662336985 and I am still seeing the issue.
The following code produces the lint "Don't type annotate initializing formals. (type_init_formals)":
class A {
A({required String this.p});
String? p;
}
And the following code produces the lint "Use initializing formals when possible. (prefer_initializing_formals)"
class A {
A({required String p}) : p = p;
String? p;
}
My understanding is that in an NNBD world, at least one of these should not produce a lint. Can we reopen the issue until it is resolved? Or is there any other way to solve this?
/fyi @a14n
I also don't see a type_init_formals test case for @goderbauer's first example. https://github.com/dart-lang/linter/blob/master/test/rules/type_init_formals.dart There aren't very many tests.