Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 892
sroes Avatar asked Jul 16 '20 14:07

sroes


1 Answers

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).

like image 130
Mabsten Avatar answered Nov 01 '22 19:11

Mabsten