Skip to content

List runtime subtyping error #1581

Open
@davidmartos96

Description

@davidmartos96

Hello!
I've been migrated some code to null safety, in particular code that generates raw SQLite queries. One of these methods combines 2 arguments lists into one for the final query.
The migration I did involves generalizing the list of arguments to List<Object?>, but the problem I faced was a runtime exception when concatenating the two List<Object?>. The issue was that one of them was a variable of type List<Object?> but in reality it was created as List<Object>. Passing the non-nullable version as an argument to a function works fine but it can produce hard to catch bugs.

Example of the issue I had: https://dartpad.dev/2a154028230eeb58bb03856c020d7b8f?null_safety=true

The first print works fine whereas the second print gives a runtime exception that is hard to catch in a big codebase.
I was wondering if there is any option in the analyzer or lint that makes this issue more obvious to catch.

The solution I found is to do a .cast<Object?> but I wish there is a better solution.

void main() {
  final List<Object?> a = <Object?>[1, 2, 3, null];
  final List<Object> b = [4, 5];

  printSum(a, b);
  printSum(b, a);
}

void printSum(List<Object?> a, List<Object?> b) {
  print(a + b);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions