dart:js error when calling promiseToFuture - NoSuchMethodError: tried to call a non-function, such as null: 'jsPromise.then'
Asked Answered
B

1

7

I'm trying to await a custom global JavaScript function:

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

Which prints the following:

[object Promise]
NoSuchMethodError: tried to call a non-function, such as null: 'jsPromise.then'
Bishopric answered 16/7, 2020 at 14:28 Comment(0)
R
8

I came across the same mistake. Given the name dart:js_util of the package which contains the function promiseToFuture(), I too thought the function should be used with a object obtained with dart:js, but is not so, and the sample in the doc is actually very clear.

The javascript Promise object must be obtained using the @JS() annotation of package:js. Example:

@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);
}

Note to avoid mistake:

if a function for the interop with Javascript require an object obtained with the dart:js package, the declared type is usally not Object but JsObject or subclasses. Instead, if the object must be obtained using the @JS annotation, the declared type is Object, if it doesn't exists an appropriate external declaration (the runtimeType of the objects obtained with the @JS annotation is NativeJavaScriptObject, but there is no corresponding class exposed in the Dart Sdk).

Rina answered 10/8, 2020 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.