web-dev-qa-db-fra.com

Comment mapper des chaînes JJ Flutter à partir d'une liste?

J'imprime avec succès ma réponse sous forme de chaîne à partir de mon URL JSON YouTube, mais lorsque j'essaie de sérialiser via les "éléments", l'erreur suivante s'affiche: Unhandled exception: type 'List' is not a subtype of type 'Map' of 'json' where List is from Dart:core Map is from Dart:core

Voici mon code ...

class CardInfo {
  //Constructor
  String id;
  String description;
  String role;
  //int score;

  CardInfo.fromJson(Map json) {
    this.id = json['vieoId'];
    this.description = json['description'];
    this.role = json['title'];
    //this.score = json['score'];
  }
}

Future getData() async {
    String url = 'YouTube url';
    var httpClient  = createHttpClient();
    var response = await httpClient.get(url);
    Map data = JSON.decode(response.body);
    //String ip = data['items'];
    var ci = new CardInfo.fromJson(data['items']);

    //print(data['items']);
    print(ci.id);
    //print(ci.description);
    //print(ci.role);

    if (!mounted) return;


    setState(() {});

  }

print(data['items'] est en cours d'impression, mais print(ci.id) ou toute variable Info carte renvoie l'erreur ci-dessus.

**** Journal de print(data);

{kind: youtube#searchListResponse, etag: "VPWTmrH7dFmi4s1RqrK4tLejnRI/P9wyOxsXEuXOCvj7znCun2-EykU", nextPageToken: CAMQAA, regionCode: US, pageInfo: {totalResults: 1000000, resultsPerPage: 3}, items: [{kind: youtube#searchResult, etag: "VPWTmrH7dFmi4s1RqrK4tLejnRI/Csl1kQhnOsbs0j4_336zJAN176k", id: {kind: youtube#video, videoId: e3pUxU_bE6w}, snippet: {publishedAt: 2017-09-14T09:43:17.000Z, channelId: UCbD8EppRX3ZwJSou-TVo90A, title: [PRISTIN - We Like] KPOP TV Show | M COUNTDOWN 170914 EP.541, description: KPOP Chart Show M COUNTDOWN | EP.541 - PRISTIN - We Like ▷Watch more video clips: http://MCOUNTDOWN-KPOP2017 [Kor Ver.] 프리티 ..., thumbnails: {default: {url: https://i.ytimg.com/vi/e3pUxU_bE6w/default.jpg, width: 120, height: 90}, medium: {url: https://i.ytimg.com/vi/e3pUxU_bE6w/mqdefault.jpg, width: 320, height: 180}, high: {url: https://i.ytimg.com/vi/e3pUxU_bE6w/hqdefault.jpg, width: 480, height: 360}}, channelTitle: Mnet K-POP, liveBroadcastContent: none}}, {kind: youtube#searchResult, etag: "VPWTmrH7dFmi4s1RqrK4tLejnRI/1JCCNBPNbFeusCp_9-pl4i8q5OU", id: {kind: youtube#video, videoId: Cc4hO9RLdl4}, snippet: {publishedAt: 2017-09-14T10:37:29.000Z, channelId: UCbD8EppRX3ZwJSou-TVo90A, title: [EXO - Power] KPOP TV Show | M COUNTDOWN 170914 EP.541, description: KPOP Chart Show M COUNTDOWN | EP.541 - EXO - Power ▷Watch more video clips: http://MCOUNTDOWN-KPOP2017 [Kor Ver.] Power Up! '#EXO' 여기 ..., thumbnails: {default: {url: https://i.ytimg.com/vi/Cc4hO9RLdl4/default.jpg, width: 120, height: 90}, medium: {url: https://i.ytimg.com/vi/Cc4hO9RLdl4/mqdefault.jpg, width: 320, height: 180}, high: {url: https://i.ytimg.com/vi/Cc4hO9RLdl4/hqdefault.jpg, width: 480, height: 360}}, channelTitle: Mnet K-POP, liveBroadcastContent: none}}, {kind: youtube#searchResult, etag: "VPWTmrH7dFmi4s1RqrK4tLejnRI/ZnYC4e5evyfldkM67HsDuV8Yh3E", id: {kind: youtube#video, videoId: BBcOM25wrVo}, snippet: {publishedAt: 2017-08-18T15:21:48.000Z, channelId: UCtFtO4By4czgkYGvEXvJu0A, title: Kpop Banned Dance: MV vs LIVE, description: Kpop Banned Dance: MV vs LIVE Koreas biggest broadcasting companies has strict rules and standards on what lyrics and dances moves can be performed., thumbnails: {default: {url: https://i.ytimg.com/vi/BBcOM25wrVo/default.jpg, width: 120, height: 90}, medium: {url: https://i.ytimg.com/vi/BBcOM25wrVo/mqdefault.jpg, width: 320, height: 180}, high: {url: https://i.ytimg.com/vi/BBcOM25wrVo/hqdefault.jpg, width: 480, height: 360}}, channelTitle: Kpop Corn, liveBroadcastContent: none}}]}

*** MISE À JOUR AVEC POUR DÉCLARATION DE BOUCLE

Voici le code de mon for loop qui renvoie une erreur type 'String' is not a subtype of type 'int' of 'index' ...

Map data = JSON.decode(response);
var videos = data['items'];
for (var items in videos['snippet']){
      print(items);
    }

Faire une boucle à travers items in videos me donne 3 entrées distinctes pour les 3 vidéos que je cherche - y compris des extraits. Essayer d'obtenir les extraits individuels est un échec. S'il te plait, oriente moi dans la bonne direction. 

5
Charles Jr

Il semble que data['items'] est une List (c'est-à-dire un tableau JSON), pas une Map.

Vous pouvez utiliser des méthodes de compréhension de liste pour vous aider ici:

final items = (data['items'] as List).map((i) => new CardInfo.fromJson(i));
for (final item in items) {
  print(item.id);
}
13
matanlurey

La ligne suivante vous donne la List de items.

var videos = data['items'];

et vous obtenez l'erreur à cause de cette ligne

for(var items in videos['snippet'])

Dans la ligne précédente, vous pensez que vous parcourez les données à l'intérieur de snippet, alors qu'en fait, vous essayez d'itérer l'index 'extrait' dans la liste des vidéos, ce qui n'a pas de sens car l'itération sur une liste se fait à l'aide de valeurs entières. videos[0] , videos [1], videos [2] .. pendant que vous passez une String'snippet'

Vous devez d’abord itérer sur votre liste videos élément par élément (chaque élément est une carte). Stocke chaque Map dans une variable. alors vous pouvez accéder aux valeurs de snippet par myMap['snippet']

    Map data = JSON.decode(response);
    var videos = data['items']; //returns a List of Maps
    for (var items in videos){ //iterate over the list
    Map myMap = items; //store each map 
    print(myMap['snippet']);
        }

Voyez si cela résout votre problème.

1
aziza