I've been trying to create methods dynamically from strings using Dart to no avail. String example: "(String str) => return str.length;". The idea is to allow users to create their own functions to apply to a given string. The only thing I've found is NoSuchMethod which does not seem to apply to my case. I tried using new Function in JavaScript but when passing the function to Dart and executing it, I get the following error: Uncaught TypeError: J.$index$asx(...).call$0 is not a function.
Code examples:
Dart:
context["UpdateNames"] =
(JsObject pTag)
{
print(pTag["function"]("text"));
};
JS:
function execute ()
{
var func = {"function": new Function("str", "return str.length;")};
UpdateNames(func);
}
EDIT:
Solution: Create an object in JavaScript such as this:
this.fun = function (name)
{
var text = "var funs = " + document.getElementById("personalFun").value;
eval(text);
return funs(name);
};
Then create the object in Dart:
caller = new JsObject(context['Point'], []);
Finally call the method to dynamically create the function:
caller.callMethod('fun', [text]);
I'm not sure to completely understand what you want achieve so i will try to provide the best answers
In this case it's completely possible but you need to use some mirror so be careful if you want to use this for the web
here an implementation example :
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);
}
Sorry but it's not possible. it's a big requested features but it's not planned by the dart team be cause it will involve to many change and trad off.
Maybe it's possible to trick by creating dart file and use isolate to run it.
Solution: Create an object in JavaScript such as this:
var FunctionObject = function() {
this.fun = function (name)
{
var text = "var funs = " + document.getElementById("personalFun").value;
eval(text);
return funs(name);
};
};
Then create the object in Dart:
caller = new JsObject(context['FunctionObject'], []);
Finally call the method to dynamically create the function:
caller.callMethod('fun', [text]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With