Dart mirrors issue. getField

Issue

I’m trying use mirrors, but I have error in some simple code.

import 'dart:mirrors';
// -----------------
class TestUser extends Object{
  String name = 'aaa';
  String status = 'bbb';
  String position = 'ccc';
  int age = 20;
}

var mapVal = new TestUser();
InstanceMirror mirror = reflect(mapVal);

var futureValue = mirror.getField('age');
futureValue.then((imValue) => print("Field: age = ${imValue.reflectee}"));

Result:

Unhandled exception:
Class 'String' has no instance getter '_name@0x1aab143'.

NoSuchMethodError : method not found: '_name@0x1aab143'
Receiver: "age"
Arguments: []
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      Symbol.getName (dart:_collection-dev/symbol.dart:64)
#2      _n (dart:mirrors-patch/mirrors_impl.dart:59)
#3      _LocalObjectMirror.getField (dart:mirrors-patch/mirrors_impl.dart:254)
#4      main (file:///C:/Users/Less/IdeaProjects/testDart/console/template.dart:67:36)
#5      _startIsolate.isolateStartHandler (dart:isolate-patch/isolate_patch.dart:216)
#6      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:115)

What it means? I have no idea. Why it takes ‘_name@0x1aab143’ from String? Black magic…

Solution

var mapVal = new TestUser();
InstanceMirror mirror = reflect(mapVal);
// getField() expects an instance of Symbol, not String
var futureValue = mirror.getField(new Symbol("age"));
// getField() returns an InstanceMirror, not a Future<InstanceMirror>
print("Field: age = ${futureValue.reflectee}");

Could it be that you updated your SDK, but not your Editor? The current Editor with the current SDK shows all of that as a warning, making troubleshooting this code rather trivial.

Answered By – MarioP

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.