-
Notifications
You must be signed in to change notification settings - Fork 1.7k
possibly warn when a class extends ListBase in null safe code, and doesn't implement add? #46646
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
type 'Null' is not a subtype of type 'Object' in type cast
is thrown on List.length
setter
That's expected behavior for null safety. You can only increase the length of a list by setting You can reduce the length safely, so it's hard to make it a compile-time error. The error could be more informative, but that also risks adding an overhead on the valid operations. |
Thanks @lrhn for the explanation, it confirms what I suspected. During my tries to make it work I saw errors on non-growable lists that are much more explanatory - would it be possible to make it similar, for example , give an error that mentions that I am trying to grow a list by adding a null element to a list of non-nullable objects? Some context - the original example was a ListBase implementation that was overriding its methods and forwarding them to an internal list of non-nullable objects. Calling add(7) on that list implementation was implicitly calling the length setter and throwing, making the error harder to understand. |
Yes, the (Could we have the analyzer warn when a class extends |
So it's not possible to |
@cedvdb Not sure what you are asking. The The |
Sorry, I'm also having an hard time parsing what's being said here. I meant that the following snippet won't work without overriding the import 'dart:collection';
void main() {
final list = GrowingList();
list.add(1);
}
class A {}
class GrowingList extends ListBase<int> {
final List<int> _innerList = [];
GrowingList();
@override
set length(int newLength) { _innerList.length = newLength; }
@override
int get length => _innerList.length;
@override
int operator [](int index) => _innerList[index];
@override
void operator []=(int index, int value) { _innerList[index] = value; }
} The only thing that worked for me was to make the inner list nullable. Ence my previous comment, which said if this cannot be done because increasing the length adds a null slot, then I don't think the doc is clear enough there. |
Correct, that class will throw in |
Using
Expected
I suspect that the list cannot grow by adding Null elements due to null safety, so the code should throw, but it would be great to have a better error message. Even better, is it possible to give a compilation error instead?
Actual
Dart SDK version
Dart SDK version: 2.14.0-321.0.dev (dev) (Thu Jul 15 08:55:11 2021 -0700) on "macos_x64"
Platform
VM and web
The text was updated successfully, but these errors were encountered: