Skip to content

How to pass empty lists to invokeSetter without knowing the list type? #349

@alessandro-amos

Description

@alessandro-amos

Hello.

I’m having trouble using invokeSetter with typed lists.

Consider the following code:

class Reflector extends Reflectable {
  const Reflector() : super(instanceInvokeCapability);
}

const reflector = Reflector();

@reflector
class Person {
  String? name;
  int? age;
  List<Address>? addresses;
}

@reflector
class Address {
  String street = '';
  String city = '';
}

void main() {
  initializeReflectable();

  Person p = Person();

  final im = reflector.reflect(p);
  im.invokeSetter('addresses', []);
}

The problem is that when I call im.invokeSetter('addresses', []), the value is interpreted as List<dynamic>, but the property actually expects a List<Address>.
If I pass an explicitly typed list (<Address>[]), it works. However, in my case I don’t know the Address type at compile time — it’s only discovered via reflection.

My question is:
Is there a way to:

  1. Retrieve the expected type (List<Address>) from the mirror?
  2. Create or cast an empty list to that expected type, without having to write <Address>[] explicitly?

In other words, I’d like to be able to instantiate the correct empty list with the reflected type, so that invokeSetter doesn’t throw a type error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions