简体   繁体   中英

How can I get data from array?

I need to fetch the list of cat images from the CAT API .

This is a data from API

[
  {
    "breeds": [],
    "id": "bhf",
    "url": "https://cdn2.thecatapi.com/images/bhf.jpg",
    "width": 500,
    "height": 385
  }
]

My code

import 'dart:convert';

import 'package:cats_app_new/constants.dart';

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

class HomeScreen extends StatefulWidget {
  static const routeName = '/home-screen';

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Map data;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getPics(),
      builder: (context, snapshot) {
        Map data = snapshot.data;
        if (snapshot.hasError) {
          print(snapshot.error);
          return Text(
            'Failed to get response',
            style: TextStyle(
              color: Colors.red,
              fontSize: 22.0,
            ),
          );
        } else if (snapshot.hasData) {
          return Center(
            child: ListView.builder(
              // itemCount: data!.length,
              itemBuilder: (context, index) {
                return Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.all(
                        kDefaultPadding / 4,
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {},
                        child: Image.network(
                          '${data['url'][index]}',
                          // '${data['hits'][index]['largeImageURL']}',
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          );
        } else if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}

Future<CatApi> getPics() async {
  String url = 'https://pixabay.com/api/?key=$kApiKey2';
  String url2 = 'https://thecatapi.com/v1/images?api_key=$kApiKey';
  http.Response response = await http.get(url2);
  return CatApi.fromJson(jsonDecode(response.body));
}



class CatApi {
  // List breed;
  String id;
  String url;
  int width;
  int height;

  CatApi(
    this.id,
    this.url,
    this.height,
    this.width,
  );

  factory CatApi.fromJson(dynamic json) {
    return CatApi(
      json['id'] as String,
      json['url'] as String,
      json['width'] as int,
      json['height'] as int,
    );
  }

  @override
  String toString() {
    return '{${this.url}}';
  }
}

In order to display the json object format from json array, I create a separate class CatApi where I describe the parameters of the fields that I intend to display. At the moment I am only using the 'url' field

I can't understand what I'm doing wrong to display a list of photos

The http response you've provided with the question is a List of Map but in the fromJson method in the CatApi class you're treating it as a Map

factory CatApi.fromJson(dynamic json) {
    return CatApi(
      json['id'] as String,
      json['url'] as String,
      json['width'] as int,
      json['height'] as int,
    );
  }

Also, in your getPics() method, the url you're using to fetch the response is not the same as the link you've provided in the question. Do both links return the same response?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM