我正在尝试使用镜像,但我在一些简单的代码中有错误。
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}"));
结果:
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)
这意味着什么?我不知道。为什么需要来自String的'_name @ 0x1aab143'?黑魔法......
答案 0 :(得分:1)
并非Dart中的所有内容都是异步的; - )
// mirror.getField('age');
InstanceMirror im = mirror.getField(#age); // needs a symbol
// futureValue.then((imVa
print("Field: age = ${im.reflectee}")); // getField doesn't return a future
答案 1 :(得分:1)
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}");
可能是您更新了SDK,而不是您的编辑器?使用当前SDK的当前编辑器将所有这些显示为警告,使对此代码进行故障排除相当简单。