如何从数组中获取数据?

时间:2021-03-07 13:14:14

标签: arrays json flutter dart asynchronous

我需要从 CAT API 中获取猫图像列表。

这是来自 API 的数据

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

我的代码

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}}';
  }
}

为了从 json 数组中显示 json 对象格式,我创建了一个单独的类 CatApi,我在其中描述了我打算显示的字段的参数。目前我只使用 'url' 字段

我无法理解我在显示照片列表时做错了什么

1 个答案:

答案 0 :(得分:0)

您随问题提供的 http 响应是 Map 列表,但在 CatApi 类的 fromJson 方法中,您将其视为 Map< /p>

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

此外,在您的 getPics() 方法中,您用来获取响应的网址与您在问题中提供的链接不同。两个链接是否返回相同的响应?