0

我正在尝试使用镜子,但我在一些简单的代码中有错误。

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)

这是什么意思?我不知道。为什么它从字符串中获取'_name@0x1aab143'?黑魔法...

4

2 回答 2

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
于 2014-02-21T09:44:10.823 回答
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 的当前编辑器将所有这些都显示为警告,使此代码的故障排除变得相当简单。

于 2014-02-21T09:45:33.783 回答