How do I get all fields for a class in Dart?

Issue

I looked at the dart:mirrors library, and I found ClassMirror. While I saw getField I didn’t see access to all fields. I did see getters, though.

If I want to get all fields for a class, do I have to go through getters ?

Solution

Zdeslav Vojkovic’s answer is a bit old.

This works for me, for Dart 1.1.3, as of March 2 2014.

import 'dart:mirrors';

class Test {
    int a = 5;

    static int s = 5;

    final int _b = 6;

    int get b => _b;

    int get c => 0;
}

void main() {

    Test t = new Test();
    InstanceMirror instance_mirror = reflect(t);
    var class_mirror = instance_mirror.type;

    for (var v in class_mirror.declarations.values) {

        var name = MirrorSystem.getName(v.simpleName);

        if (v is VariableMirror) {
            print("Variable: $name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}, C: ${v.isConst}");
        } else if (v is MethodMirror) {
            print("Method: $name => S: ${v.isStatic}, P: ${v.isPrivate}, A: ${v.isAbstract}");
        }

    }
}

Would output:

Variable: a => S: false, P: false, F: false, C: false
Variable: s => S: true, P: false, F: false, C: false
Variable: _b => S: false, P: true, F: true, C: false
Method: b => S: false, P: false, A: false
Method: c => S: false, P: false, A: false
Method: Test => S: false, P: false, A: false   

Answered By – corgrath

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *