reflectiondartflutterdart-mirrors

Getting value of public static field/property of a class by it's name as string in dart via reflectable


Say I have a class:

class Icons {
       static const IconData threesixty = IconData(0xe577, fontFamily: 'MaterialIcons');
 }

now I have a string variable with value of "threesixty":

String fieldName = "threesixty";

how can I get the value of the threesixty in Icons class by the fieldName variable?

I am using the reflectable package and already have used other features of ClassMirrors in flutter but don't know how to do this.


Solution

  • What you want requires use of reflection. In flutter reflection is not supported because of tree shaking. Tree shaking is the process of removing unused code from your app package (apk, ipa) in order to reduce the package size. When reflection is in use all code can be used implicitly so flutter won't be able to know which parts of code to get rid of, so they opted to not support reflection (mirrors in dart context). You should try to solve your problem with inheritance if possible, or depending on your specific problem you can try to utilize static code generation.

    Edit: You can invoke a static getter with reflectable like this;

    import 'package:reflectable/reflectable.dart';
    
    class Reflector extends Reflectable {
      const Reflector() : super(staticInvokeCapability);
    }
    
    const reflector = const Reflector();
    
    @reflector
    class ClassToReflect {
      static double staticPropertyToInvoke = 15;
    }
    

    Main.dart

    import 'package:reflectable/reflectable.dart';
    import 'main.reflectable.dart';
    
    void main() {
      initializeReflectable();
    
      ClassMirror x = reflector.reflectType(ClassToReflect);
      var y = x.invokeGetter('staticPropertyToInvoke');
      debugPrint(y);
    }
    

    P.S. main.reflectable.dart is the file generated by reflectable package.