如何解析json数据并在Flutter的Listview中显示它? [英] How to parse the json data and display it in Listview in Flutter?

查看:250
本文介绍了如何解析json数据并在Flutter的Listview中显示它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分析以下数据并在列表视图中显示。我已经尝试了很多方法,但是出现了 _InternalLinkedHashMap'错误,没有实例方法'map'具有匹配的参数,像这样。

I want to parse the below data in flutter and show it in listview. i have tried lots of way but got error of _InternalLinkedHashMap' has no instance method 'map' with matching arguments like this.

我该如何做这个?请帮助

How can i do this? Please Help

Json数据

{
    "success": true,
    "data": {
        "categoryList": [{
            "category_id": 4,
            "category_name": "Super Hero",
            "category_type": "Free",
            "order_number": 3,
            "category_img": "https://avatars0.githubusercontent.com/u/1?v=4",
            "thumb_img": "https://avatars0.githubusercontent.com/u/1?v=4",
            "description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit",
            "website_url": "www.superhero.com",
            "created_date": "2018-05-14 12:15:38",
            "number_of_images": "21",
            "categoryImageList": [{
                "category_name": "Super Hero",
                "images_id": 35,
                "category_id": 4,
                "image_large": "https://avatars0.githubusercontent.com/u/2?v=4",
                "thumb_img": "https://avatars0.githubusercontent.com/u/2?v=4",
                "status": "Active",
                "created_date": "2018-05-14 12:50:56"
            }]
        }],
        "ListData": [{
            "wallpaper_id": 30,
            "wallpaper_img": "https://avatars0.githubusercontent.com/u/6?v=4",
            "thumb_img": "https://avatars0.githubusercontent.com/u/6?v=4",
            "website_url": "www.Yahoo.com",
            "created_date": "2018-05-14T12:56:35.000Z"
        }]
    }
}







import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response =     
  await client.get('jsondataurl');

  // Use the compute function to run parsePhotos in a separate isolate
  return compute(parsePhotos, response.body);
}

// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody);

  return parsed.map<Photo>((json) => new Photo.fromJson(json)).toList();
}

class Photo {
  final int albumId;
  final int id;
  final String title;
  final String url;
  final String thumbnailUrl;

  Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  factory Photo.fromJson(Map<String, dynamic> json) {
    return new Photo(
      albumId: json['category_id'] as int,
      id: json['order_number'] as int,
      title: json['category_name'] as String,
      url: json['category_img'] as String,
      thumbnailUrl: json['thumb_img'] as String,
    );
  }
}

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new FutureBuilder<List<Photo>>(
        future: fetchPhotos(new http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? new PhotosList(photos: snapshot.data)
              : new Center(child: new CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new GridView.builder(
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return new Image.network(photos[index].thumbnailUrl);
      },
    );
  }
}


推荐答案

问题出在您的 parsePhotos 函数上。您已经假设接收到的JSON文件只是一张照片列表,但其中还包含其他项。像这样进行更改将解决该问题:

The problem is with your parsePhotos function. You have assumed that the JSON file that you are receiving is only a list of photos, but it also has other items inside it. Changing it like this will fix the issue:

List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody);

  return (parsed["data"]["categoryList"] as List).map<Photo>((json) => 
       new Photo.fromJson(json)).toList();
}

这篇关于如何解析json数据并在Flutter的Listview中显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆