我一直在尝试使用 Dart 从字符串动态创建方法,但无济于事。字符串示例:“(String str) => return str.length;”。这个想法是允许用户创建自己的函数以应用于给定的字符串。我发现的唯一一件事是 NoSuchMethod ,它似乎不适用于我的情况。我尝试在 JavaScript 中使用 new Function 但是当将函数传递给 Dart 并执行它时,我收到以下错误:Uncaught TypeError: J.$index$asx(...).call$0 is not a function。
代码示例:
镖:
context["UpdateNames"] =
(JsObject pTag)
{
print(pTag["function"]("text"));
};
Run Code Online (Sandbox Code Playgroud)
JS:
function execute ()
{
var func = {"function": new Function("str", "return str.length;")};
UpdateNames(func);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
解决方案:在 JavaScript 中创建一个对象,例如:
this.fun = function (name)
{
var text = "var funs = " + document.getElementById("personalFun").value;
eval(text);
return funs(name);
};
Run Code Online (Sandbox Code Playgroud)
然后在 Dart 中创建对象:
caller = new JsObject(context['Point'], []);
Run Code Online (Sandbox Code Playgroud)
最后调用方法动态创建函数:
caller.callMethod('fun', [text]);
Run Code Online (Sandbox Code Playgroud)
我不确定是否完全了解您想要实现的目标,因此我会尽力提供最佳答案
在这种情况下,这是完全可能的,但是您需要使用一些镜像,因此如果您想将其用于网络,请务必小心
这是一个实现示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
对不起,但这是不可能的。这是一个很大的要求功能,但它不是由 dart 团队计划的,因为它会涉及许多更改和权衡。
也许可以通过创建 dart 文件并使用隔离来运行它来欺骗。
| 归档时间: |
|
| 查看次数: |
1604 次 |
| 最近记录: |