我一直在尝试使用 Dart 从字符串动态创建方法,但没有成功。字符串示例:“(String str) => return str.length;”。这个想法是允许用户创建自己的函数来应用于给定的字符串。我发现的唯一的东西是 NoSuchMethod ,它似乎不适用于我的情况。我尝试在 JavaScript 中使用 new Function,但是当将该函数传递给 Dart 并执行它时,出现以下错误:未捕获的类型错误:J.$index$asx(...).call$0 不是函数.
代码示例:
Dart:
context["UpdateNames"] =
(JsObject pTag)
{
print(pTag["function"]("text"));
};
JS:
function execute ()
{
var func = {"function": new Function("str", "return str.length;")};
UpdateNames(func);
}
EDIT:
解决方案:在 JavaScript 中创建一个对象,如下所示:
this.fun = function (name)
{
var text = "var funs = " + document.getElementById("personalFun").value;
eval(text);
return funs(name);
};
然后在 Dart 中创建对象:
caller = new JsObject(context['Point'], []);
最后调用动态创建函数的方法:
caller.callMethod('fun', [text]);
我不确定完全理解您想要实现的目标,所以我会尽力提供最佳答案
您想要动态地将方法添加到具有特定字符串标识符的类中
在这种情况下这是完全可能的,但你需要使用一些镜子 so 如果您想将其用于网络,请小心
这里是一个实现示例:
import "dart:mirrors";
class Test {
Map<String, dynamic> _methods = {};
void addMethod(String name, var cb) {
_methods[name] = cb;
}
void noSuchMethod(Invocation inv) {
if (inv.isMethod) {
Function.apply(_methods[MirrorSystem.getName(inv.memberName)], inv.positionalArguments);
}
}
}
void testFunction() {
for (int i = 0; i < 5; i++) {
print('hello ${i + 1}');
}
}
void testFunctionWithParam(var n) {
for (int i = 0; i < 5; i++) {
print('hello ${i + n}');
}
}
void main() {
var t = new Test();
t.addMethod("printHello", testFunction);
t.addMethod("printHelloPlusN", testFunctionWithParam);
t.printHello();
t.printHelloPlusN(42);
}
您想要“执行”字符串中的代码
抱歉,但这是不可能的。这是一个很大的需求功能,但 dart 团队没有计划它,因为它会涉及许多更改和权衡。
也许可以通过创建 dart 文件并使用来欺骗isolate https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:isolate.Isolate运行它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)