如何从Flutter调用异步JS函数并获取结果?

huangapple go评论115阅读模式
英文:

How to call an async JS function from Flutter and get result?

问题

I need to get the search results from Algolia on Flutter Web from JS?

This is in the index.html:

<script>
   const client = algoliasearch("4HURXXXXX", "xxxxxb8fxxxx");
   async function asyncTest(indexx, text, hitCallback, errorCallback) {
     // Get the 
     const index = client.initIndex(indexx);
      
     const res = await index.search();

     return res;
      
   }
</script>

Flutter:

import 'dart:js' as js;

js.context.callMethod('asyncTest', [
  'stock_items',
  searchValue,
]);

How do I get the JavaScript promise as a Dart Future?

英文:

I need to get the search results from Algolia on Flutter Web from JS?

This is in the index.html:

&lt;script&gt;
   const client = algoliasearch(&quot;4HURXXXXX&quot;, &quot;xxxxxb8fxxxx&quot;);
   async function asyncTest(indexx, text, hitCallback, errorCallback) {
     // Get the 
     const index = client.initIndex(indexx);
      
     const res = await index.search();

     return res;
      
   }
&lt;/script&gt;

Flutter:

import &#39;dart:js&#39; as js;

    js.context.callMethod(&#39;asyncTest&#39;, [
      &#39;stock_items&#39;,
      searchValue,
    ]);

How do I get the Javsdcript promise as a Dart Future?

答案1

得分: 1

你可以使用 dart:js 库将 JavaScript 的 Promise 转换为 Dart 的 Future。

import 'dart:async';
import 'dart:js' as js;

Future<dynamic> searchAlgolia(String index, String text) {
  final completer = Completer<dynamic>();

  js.context.callMethod('asyncTest', [
    index,
    text,
    (result) => completer.complete(result),
    (error) => completer.completeError(error),
  ]);

  return completer.future;
}

在这段代码中,我创建了一个 Completer 来将 JavaScript 的 Promise 转换为 Dart 的 Future。你需要将 index 和 text 参数传递给 JavaScript 中的 asyncTest 函数。你还需要传递两个回调函数来处理成功和错误情况。当 JavaScript 的 Promise 解析完成时,Completer 将使用结果完成。如果 Promise 被拒绝,Completer 将以错误状态完成。最后,返回 Completer 的 future 属性。

英文:

You could use dart:js library to convert the JavaScript Promise to a Dart Future.

import &#39;dart:async&#39;;
import &#39;dart:js&#39; as js;

Future&lt;dynamic&gt; searchAlgolia(String index, String text) {
  final completer = Completer&lt;dynamic&gt;();

  js.context.callMethod(&#39;asyncTest&#39;, [
    index,
    text,
    (result) =&gt; completer.complete(result),
    (error) =&gt; completer.completeError(error),
  ]);

  return completer.future;
}

In this piece of code, I created a Completer to convert the JavaScript Promise to a Dart Future. You need to pass the index and text parameters to the asyncTest function in JavaScript. You also pass two callbacks to handle the success and error cases. When the JavaScript Promise resolves, the completer is completed with the result. If the Promise is rejected, the completer is completed with an error. Lastly return the future property of the completer.

答案2

得分: 1

You are looking for Darts promiseToFuture:

> Converts a JavaScript Promise to a Dart Future.

Here's a minmial example, adapt it to your needs:

script.js

  function timer() {
            return new Promise((resolve, reject) =&gt; {
                setTimeout(() =&gt; {
                    resolve('Promise resolved!');
                }, 2000);
            });
        }

main.js

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

@JS()
// This is the JavaScript function we want to call, use the same name as the JS function.
external dynamic timer();

Future<void> main() async {
  final jsPromise = timer(); // Call the JavaScript function

  // Convert JavaScript Promise to Dart Future
  final futureData = js_util.promiseToFuture(jsPromise);

  try {
    final data = await futureData;
    print(data);
  } catch (e) {
    print('Error: $e');
  }
}

Prints:

Promise resolved!

Helpful resources
英文:

You are looking for Darts promiseToFuture:

> Converts a JavaScript Promise to a Dart Future.

Here's a minmial example, adapt it to your needs:

script.js

  function timer() {
            return new Promise((resolve, reject) =&gt; {
                setTimeout(() =&gt; {
                    resolve(&#39;Promise resolved!&#39;);
                }, 2000);
            });
        }

main.js

import &#39;package:js/js.dart&#39;;
import &#39;dart:js_util&#39; as js_util;

@JS()
// This is the JavaScript function we want to call, use the same name as the JS function.
external dynamic timer();

Future&lt;void&gt; main() async {
  final jsPromise = timer(); // Call the JavaScript function

  // Convert JavaScript Promise to Dart Future
  final futureData = js_util.promiseToFuture(jsPromise);

  try {
    final data = await futureData;
    print(data);
  } catch (e) {
    print(&#39;Error: $e&#39;);
  }
}

Prints:

Promise resolved!
Helpful resources

huangapple
  • 本文由 发表于 2023年8月5日 04:21:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定