Search code examples
flutterdartreflectionmetadata

Reflection in Flutter


I am trying to dynamically build a form according to specific class members and annotations. Because dart:mirrors is not available in Flutter SDK I am trying to access metadata with the reflectable package.

First I created classes for form declaration and annotation

class FormDeclaration {
  @DynamicFieldAttribute(label: 'Name and Surname', order: 1)
  String? name;
  @DynamicFieldAttribute(label: 'Age', order: 2)
  int? age;
  @DynamicFieldAttribute(label: 'Are you married?', order: 3)
  bool? isMarried;
}

class DynamicFieldAttribute {
  final String label;
  final int order;
  const DynamicFieldAttribute({
    required this.order,
    required this.label,
  });
}

I added reflectable package and created Reflector class.

class Reflector extends Reflectable {
  const Reflector() : super(metadataCapability, declarationsCapability, topLevelInvokeCapability, invokingCapability, typeRelationsCapability, typingCapability);
}

const reflector = Reflector();

I'm trying to access FormDeclaration members and their annotations. So I will build the form. Of course, this is only an example of the problem, so it was so simple with three basic and meaningless members.

initializeReflectable();
    ClassMirror classMirror = reflector.reflectType(FormDeclaration) as ClassMirror;
    classMirror.instanceMembers.forEach((key, value) {
      print(value.simpleName);
    });

The code above list the members of FormDecleration class. But I couldn't get the metadata of each member. It will be wonderful if I can query the members with their metadata parameter value (e.g order)

Here is the full source of example


Solution

  • I try to access it like the below code and be able to display its member and annotation. Is that what you want?

    
        classMirror.declarations.forEach((member, mirror) {
    
          var memberMetadata = mirror.metadata.isNotEmpty ? mirror.metadata.first : '';
          
          debugPrint(''' 
            - Member: $member
            - Annotaion: $memberMetadata
            - Owner: ${mirror.owner}
          ''');
    
        });
    
    • Output in the console
    Restarted application in 234ms.
    flutter:         - Member: name
    flutter:         - Annotaion: Instance of 'DynamicFieldAttribute'
    flutter:         - Owner: NonGenericClassMirrorImpl(.FormDeclaration)
    flutter:
    flutter:         - Member: age
    flutter:         - Annotaion: Instance of 'DynamicFieldAttribute'
    flutter:         - Owner: NonGenericClassMirrorImpl(.FormDeclaration)
    flutter:
    flutter:         - Member: isMarried
    flutter:         - Annotaion: Instance of 'DynamicFieldAttribute'
    flutter:         - Owner: NonGenericClassMirrorImpl(.FormDeclaration)