簡體   English   中英

如何解析json數據並在Flutter的Listview中顯示它?

[英]How to parse the json data and display it in Listview in Flutter?

我想在flutter中解析下面的數據並在listview中顯示它。 我已經嘗試了很多方法但是得到了_InternalLinkedHashMap的錯誤'沒有實例方法'map'與這樣的匹配參數

我怎樣才能做到這一點? 請幫忙

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文件只是一張照片列表,但它內部還有其他項目。 像這樣更改它將解決問題:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM