dartflutterdart-async

How to convert Map<String, Object> to Map<Key, Value> in dart?


I have this Map of String, Object I want it to be flattened so the result is Map of Key, Value

void main(){


    var li = {"qotd_date":"2019-05-18T00:00:00.000+00:00","quote":{"id":61869,"dialogue":false,"private":false,"tags":[],"url":"https://favqs.com/quotes/wael-ghonim/61869-the-power-of--","favorites_count":1,"upvotes_count":0,"downvotes_count":0,"author":" Wael Ghonim ","author_permalink":"wael-ghonim","body":"The power of the people is greater than the people in power."}};


    print(li);

}

Current Output :

{qotd_date: 2019-05-18T00:00:00.000+00:00, quote: {id: 61869, dialogue: false, private: false, tags: [], url: https://favqs.com/quotes/wael-ghonim/61869-the-power-of--, favorites_count: 1, upvotes_count: 0, downvotes_count: 0, author:  Wael Ghonim , author_permalink: wael-ghonim, body: The power of the people is greater than the people in power.}}

Expected Output I want is

{"qotd_date":"2019-05-18T00:00:00.000+00:00","id":61869,"dialogue":false,"private":false,"tags":[],"url":"https://favqs.com/quotes/wael-ghonim/61869-the-power-of--","favorites_count":1,"upvotes_count":0,"downvotes_count":0,"author":" Wael Ghonim ","author_permalink":"wael-ghonim","body":"The power of the people is greater than the people in power."};

It is just like flattening the Map. Please help me get out of this?


Solution

  • Simply, encode as json:

    import 'dart:convert';
    
    void main() {
      Map<String, dynamic> li = {
        "qotd_date": "2019-05-18T00:00:00.000+00:00",
        "quote": {
          "id": 61869,
          "dialogue": false,
          "private": false,
          "tags": [],
          "url": "https://favqs.com/quotes/wael-ghonim/61869-the-power-of--",
          "favorites_count": 1,
          "upvotes_count": 0,
          "downvotes_count": 0,
          "author": " Wael Ghonim ",
          "author_permalink": "wael-ghonim",
          "body": "The power of the people is greater than the people in power."
        }
      };
    
      Map<String, dynamic> flattened = {};
    
      li.removeWhere((key, value) {
        if (value is Map) {
          flattened.addAll(value);
        }
        return value is Map;
      });
    
      flattened.addAll(li);
    
      print(jsonEncode(flattened));
    }
    
    
    

    Output:

    {"id":61869,"dialogue":false,"private":false,"tags":[],"url":"https://favqs.com/quotes/wael-ghonim/61869-the-power-of--","favorites_count":1,"upvotes_count":0,"downvotes_count":0,"author":" Wael Ghonim ","author_permalink":"wael-ghonim","body":"The power of the people is greater than the people in power.","qotd_date":"2019-05-18T00:00:00.000+00:00"}