How to convert JavaScript object to Dart Map?

后端 未结 5 616
梦毁少年i
梦毁少年i 2021-01-04 02:24

I am looking for some reverse of new JsObject.jsify. Something, that would convert javascript Object back to Dart Map Is there somethi

5条回答
  •  执念已碎
    2021-01-04 02:56

    Here's an adapter to handle a JsObject like a Map :

    import 'dart:collection' show Maps;
    import 'dart:js';
    
    class JsMap implements Map {
      final JsObject _jsObject;
      JsMap.fromJsObject(this._jsObject);
    
      operator [](String key) => _jsObject[key];
      void operator []=(String key, value) {
        _jsObject[key] = value;
      }
      remove(String key) {
        final value = this[key];
        _jsObject.deleteProperty(key);
        return value;
      }
      Iterable get keys => context['Object'].callMethod('keys', [_jsObject]);
    
      // use Maps to implement functions
      bool containsValue(value) => Maps.containsValue(this, value);
      bool containsKey(String key) => keys.contains(key);
      putIfAbsent(String key, ifAbsent()) => Maps.putIfAbsent(this, key, ifAbsent);
      void addAll(Map other) {
        if (other != null) {
          other.forEach((k,v) => this[k] = v);
        }
      }
      void clear() => Maps.clear(this);
      void forEach(void f(String key, value)) => Maps.forEach(this, f);
      Iterable get values => Maps.getValues(this);
      int get length => Maps.length(this);
      bool get isEmpty => Maps.isEmpty(this);
      bool get isNotEmpty => Maps.isNotEmpty(this);
    }
    

提交回复
热议问题