3

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.

Saeid Raei
  • 128
  • 2
  • 12

2 Answers2

9

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.

Mertus
  • 1,145
  • 11
  • 17
  • I am using https://pub.dartlang.org/packages/reflectable and used other features of it. only thing I want is how to do it with the mirrors itself just assume we are not using the flutter and I don't really care about package size – Saeid Raei Feb 11 '19 at 15:57
  • @SaeidRaei isn't this the answer you seek? – Mertus Feb 13 '19 at 06:40
  • yes but still there is a issue. I can not reflect the class Icons because I can not add the @reflector annotation to Icons class . I was thinking about extending the Icons class and using my extended class to get values but couldn't do it . Is it impossible to extend this class? – Saeid Raei Feb 14 '19 at 14:01
  • @Mertus I originally downvoted because your original answer was not an answer – Rémi Rousselet Feb 17 '19 at 00:54
  • @SaeidRaei I was trying to do the same, but the Icons class cannot be extended: // This class is not meant to be instantiated or extended; this constructor // prevents instantiation and extension. Icons._(); – isaacfi Nov 03 '21 at 17:16
-2

As far as I know this is not possible unless using a mirror library.

See: Get access to an object's property using bracket notation in dart

mbw
  • 17
  • 3