1

I am trying to execute JS native code in Flutter web. I got the way to call JS function from Dart but could not find any workaround to get the result back from JS to Dart.

Below are the JS code and Dart code which I was trying to achieve in different ways but didn't get any success.

JS Code:

    let fileHandle;
    let finalResult;

    async function fileOpen() {

        [fileHandle] = await window.showOpenFilePicker();
        const file = await fileHandle.getFile();
        console.log('File info ----> ', file);

        if (file != null) {
            const parser = new window.AppInfoParser(file);
            const result = await parser.parse();
            console.log('app info ----> ', result);
            console.log('icon base64 ----> ', result.icon);
            
            finalResult = result;
            
        } else {
            finalResult = 'File not selected';
            console.log('File not selected')
        }

        return finalResult;
        // return Promise.resolve(finalResult)
    }

Dart Code:

Example 1: Simply call JS function without callback.

import 'dart:js' as js;

// Call below on any click event
js.context.callMethod('fileOpen')

Example 2: Getting error before JS code is executed. Uncaught (in promise) TypeError: jsPromise.then is not a function at Object.promiseToFuture (js_util.dart:275:35).

import 'dart:js' as js;
import 'package:js/js_util.dart';

// Call below on any click event
dynamic result = await promiseToFuture<dynamic>(js.context.callMethod('fileOpen'));

Example 3: Getting error after JS code is executed. NoSuchMethodError: tried to call a non-function, such as null: 'obj[$toString]' OR Expected a value of type 'Future<dynamic>', but got one of type 'LegacyJavaScriptObject'.

import 'package:js/js_util.dart';
import 'package:js/js.dart';

@JS('fileOpen')
external dynamic fileOpen;

// Call below on any click event
dynamic result = await promiseToFuture(fileOpen());

Need a way to get the result back to dart.

Patel Pinkal
  • 8,984
  • 4
  • 28
  • 50

1 Answers1

0

The error message NoSuchMethodError points you in the right direction. In your JS code fileOpen is a function, in your dart code it's just a variable.

You're missing the () at the end: fileOpen()

Edit: Just saw you had opened an issue at github which already got resolved: https://github.com/dart-lang/sdk/issues/50530

Syles
  • 135
  • 11