Home > database >  Convert a JSObject to being readable in Dart
Convert a JSObject to being readable in Dart

Time:07-20

This is a repeat of several similar questions, but all of the answers I've seen are 7-10 years old an no longer relevant, as dart has since come out with null safety.

Currently, I am building a Chrome Web Extension in Dart and using some Dart interop libraries like the package:js/js.dart and dart:js. I am trying to retrieve a key-value pair from the Chrome Storage API, and can successfully do that with the following:

var test = context['chrome']['storage']['local'];
test.callMethod('get', [
  ['r'], // Assume that this is already stored in chrome storage via chrome.storage.local.set()
  (Object result) {
    _getCallback(result);
  }
]);

void _getCallback(dynamic stuff) {
  JsObject obj = stuff as JsObject;
  print(obj.toString());
}

The issue is that I am unable to see anything inside of obj, as it just returns a JsObject type. Is there a proper way in modern dart to retrieve what i need from this object? Thanks in advance!

CodePudding user response:

You can convert it to a JSON (JavaScript Object Notation) string

JSON.strigify(object)   // Javascript

save the string in the storage and then retrive it from the storage and parse it from Dart

import 'dart:convert';  // Dart

JSON.decode(string)  

This answer may help for parsing the JSON from dart.

  • Related