简体   繁体   English

如何从数组中获取数据?

[英]How can I get data from array?

I need to fetch the list of cat images from the CAT API .我需要从CAT API中获取猫图像列表。

This is a data from API这是来自 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.为了显示 json 数组中的 json object 格式,我创建了一个单独的 ZA2F2ED4F8EBC2CBB4CBB4C21A29DC40AB1 的字段,其中描述了 Cat21A29DC40AB16 的参数。 At the moment I am only using the 'url' field目前我只使用“url”字段

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 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.此外,在您的 getPics() 方法中,您用于获取响应的 url 与您在问题中提供的链接不同。 Do both links return the same response?两个链接是否返回相同的响应?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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