javascriptflutterflutter-js

How to pass object as parameter to javascript using flutter_js?


I need to run javascript code in my Flutter project. I use flutter_js for this.

I can pass int (or String) value as parameter to javascript, for example:

String blocJs = await rootBundle.loadString("assets/js/bloc.js");
final jsResult = jsRuntime.evaluate(blocJs + """add($firstNumber, $secondNumber)""");

But I need to pass object as parameter to javascript code. Is it possible?


Solution

  • You can define an object in Dart and pass it to the JavaScript function as a string. Then, you can parse the string in JavaScript and use the object.

    Here is an example:

    import 'dart:convert';
    
    class Person {
      final String name;
      final int age;
    
      Person(this.name, this.age);
    
      Map<String, dynamic> toMap() {
        return {
          'name': name,
          'age': age,
        };
      }
    
      String toJson() => json.encode(toMap());
    }
    
    final person = Person('John', 30);
    final jsObject = 'JSON.parse(\'${person.toJson()}\')';
    
    final jsResult = jsRuntime.evaluate(blocJs + """add($firstNumber, $secondNumber, $jsObject)""");
    

    In this example, we define a Person class with a name and an age field. We then create an instance of this class and convert it to a JSON string using the json.encode method. We then pass this JSON string to the JavaScript function as a parameter.

    In the JavaScript function, you can parse the JSON string using the JSON.parse method and use the resulting object.