flutter web调用js带回调函数的3种方法
flutter web调用js带回调函数的3种方法1.直接调用2.转为Promise3.转为Future(推荐)1.直接调用///js funcfunction invoke(index, success, fail){if(index > 1) {success('succes');} else {fail('fail');}}/// dart@JS('invoke')external s
·
flutter web调用js带回调函数的3种方法
1.直接调用
///js func
function invoke(index, success, fail){
if(index > 1) {
success('succes');
} else {
fail('fail');
}
}
/// dart
@JS('invoke')
external static invoke(int index, void Function(String res) success, void Function(String err) fail);
///调用
invoke(2, allowInterop((res){
print(res);
}), allowInterop((err){
print(err);
}));
2.转为Promise
///js func
function invoke(index, success, fail){
if(index > 1) {
success('succes');
} else {
fail('fail');
}
}
function invokePromise(){
return new Promise((resolve, reject)=>{
if(index > 1) {
resolve('succes');
} else {
reject('fail');
}
});
}
/// dart
@JS()
abstract class Promise<T> {}
@JS('invoke')
external static invoke(int index, void Function(String res) success, void Function(String err) fail);
external static Promise invokePromise(int index);
static Future invokeJsPromise() {
final jsPromise = invokePromise();
return promiseToFuture(jsPromise);
}
///调用
try {
final res = await invokeJsPromise(2);
print(res);
} catch(e, stack){
print(e);
print(stack);
}
3.转为Future(推荐)
///js func
function invoke(index, success, fail){
if(index > 1) {
success('succes');
} else {
fail('fail');
}
}
///dart
@JS('invoke')
external static invoke(int index, void Function(String res) success, void Function(String err) fail);
static Future invokeFuture(int index) {
Completer completer = Completer();
invoke(index, allowInterop((res) {
completer.complete(res);
}), allowInterop((err) {
completer.completeError(err);
}));
return completer.future;
}
///调用
try {
final res = await invokeFuture(2);
print(res);
} catch(e, stack){
print(e);
print(stack);
}
更多推荐
已为社区贡献3条内容
所有评论(0)