Как преобразовать карту <String, Object> в карту <Key, Value> в дротике? - PullRequest
0 голосов
/ 17 мая 2019

У меня есть эта Карта Строки, Объект. Я хочу, чтобы она была сплющена, чтобы в результате была Карта Ключа, Значение

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);

}

Токовый выход:

{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.}}

Ожидаемый вывод, который я хочу:

{"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."};

Это как выравнивание карты. Пожалуйста, помогите мне выбраться из этого?

1 Ответ

1 голос
/ 17 мая 2019

Просто закодируйте как 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));
}


Выход:

{"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"}
...