Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, it is possible to pass an object as a parameter to a JavaScript function in Flutter. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading