Passing Type/class as argument and accessing static properties, constructors etc

Viewed 800

I'm fairly new to dart, so I'm still trying to figure out all of it's nuances. One thing I'm trying to do, just based on circumstances is to pass a class/type as an argument to a function so that I can access some static methods and properties.

Here's an example:

class WithStatic {
  static final test = 'wwww';
}

void main() {
  print(WithStatic.test);
  test(WithStatic);
}


void test(dynamic cls){
  // throws error Class '_Type' has no instance getter 'test'
  print(cls.test);
}
1 Answers

This cannot be done in Dart. Static members can only be accessed directly on the actual class, never on a variable. It doesn't matter whether you use a type variable (<T>) or a variable holding a Type object, neither provides access to a static member.

If you need need to provide delayed access to a static member, you need to pass a function

class WithStatic {
  static final test = 'wwww';
}

void main() {
  print(WithStatic.test);
  test(() => WithStatic.test);
}

void test(dynamic testGetter()){
  print(cls.testGetter());
}
Related