我一直在尝试使用 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', …Run Code Online (Sandbox Code Playgroud)