Search code examples
flutterdartinstancestatic-methodsruntime-type

In a Dart (Flutter) class extending an abstract, how can an instance reference a static method (e.g. tableName)?


This is not quite the same as this question, which itself is unanswered.

I want to call get the tableName from inside an instance when the instance is an interface. Currently, I have it as an instance method and it's fine, really. If I could put it as a static method, I would be happier because it never changes per instance and my anthropomorphic belief that static methods "cost less"

The issue might come down to how to reference a static method without using the name of the class

If I use var foo = anInstance.runtimeType;, should I be able to foo.staticMethod() ?

Cheers


Solution

  • In general, "static" typically means that something is known at compile-time. It is the opposite of "dynamic".

    In Dart, a static method is always referenced via the name of the class that it's declared in. static methods are not inherited, cannot be overridden, and cannot be referenced via instances. A static method is equivalent to a global function with a different scope.

    my anthropomorphic belief that static methods "cost less"

    Yes, static method calls (and global function calls) are cheaper because the compiler already knows which function to call. In contrast, invoking an instance method requires consulting a vtable at runtime to find the appropriate override to invoke for polymorphic behavior.

    The issue might come down to how to reference a static method without using the name of the class

    This is not possible. It's not clear what you hope to achieve by omitting the class name. If you want to save some typing, you could use a global function instead of a static method.

    If I use var foo = anInstance.runtimeType;, should I be able to foo.staticMethod() ?

    No, that is not possible. runtimeType returns a Type object, and there's almost nothing you can do with those except to compare whether they are identical to other Type objects. static methods must be invoked on a statically-known (known at compile-time) type. Dart does not provide any automatic way to invoke static methods dynamically.

    Also see: https://stackoverflow.com/a/70468829/