skip to Main Content

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 Javsdcript promise as a Dart Future?

2

Answers


  1. you could use dart:js library to convert the JavaScript Promise to a 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;
    }
    

    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.

    Login or Signup to reply.
  2. 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) => {
                    setTimeout(() => {
                        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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search