【问题标题】:dart:js error when calling promiseToFuture - NoSuchMethodError: tried to call a non-function, such as null: 'jsPromise.then'dart:js 调用 promiseToFuture 时出错 - NoSuchMethodError: 试图调用非函数,例如 null: 'jsPromise.then'
【发布时间】:2020-11-06 06:09:45
【问题描述】:

我正在尝试等待自定义全局 JavaScript 函数:

  var promise = js.context.callMethod('performAuthenticationInNewWindow', [uri.toString()]);
  print(promise);
  var qs = await promiseToFuture(promise);

打印以下内容:

[object Promise]
NoSuchMethodError: tried to call a non-function, such as null: 'jsPromise.then'

【问题讨论】:

    标签: flutter flutter-web dart-js-interop


    【解决方案1】:

    我遇到了同样的错误。给定包含函数 promiseToFuture() 的包的名称dart:js_util,我也认为该函数应该与使用dart:js 获得的对象一起使用,但事实并非如此,doc 中的示例实际上非常清除。

    javascript Promise 对象必须使用package:js@JS() 注解获取。 示例:

    @JS()
    library my_lib; //Not avoid the library annotation
    
    import 'dart:js_util';
    import 'package:js/js.dart';
    
    @JS()
    external performAuthenticationInNewWindow(String uri);
    
    performAuth(uri) async {
       var promise = performAuthenticationInNewWindow(uri.toString());
       var qs = await promiseToFuture(promise);
       print(qs);
    }
    
    

    注意避免错误:

    如果与 Javascript 互操作的函数需要使用 dart:js 包获得的对象,则声明的类型通常不是 Object 而是 JsObject 或子类。相反,如果必须使用@JS 注解获取对象,则声明的类型为Object,如果不存在适当的外部声明 (@JS注解获取的对象的runtimeType为NativeJavaScriptObject,但在Dart Sdk中没有暴露对应的类)。

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2019-11-28
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多