Dynamically convert a Dart 2 Map to a Javascript object


I’m writing a custom dart to js interop around chrome.storage.local.set using new js package and dart 2 SDK.

A Map in Dart is not the same thing as an object in JavaScript, but forcing developers to write abstract classes every-time they want to use a public facing API is not the right thing either.

So, I’m looking for a way to convert dart Map to a JavaScript object that won’t require writing abstract class.

Using dart:js it was easy to convert a dart Map to JS object but with new js package I have not seen any example that dynamically converts dart Map to js object.


I was able to solve this problem by writing this function that converts a Map to js object.

import 'package:js/js_util.dart' as js;
Object mapToJSObj(Map<dynamic,dynamic> a){
  var object = js.newObject();
  a.forEach((k, v) {
    var key = k;
    var value = v;
    js.setProperty(object, key, value);
  return object;

Answered By – user10099968

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.