2

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.