【问题标题】:How can I get data from array?如何从数组中获取数据?
【发布时间】:2021-06-05 13:43:28
【问题描述】:

我需要从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”字段

我不明白我在显示照片列表时做错了什么

【问题讨论】:

  • 检查snapshot.connectionStatus,然后决定snapshot.data

标签: arrays json flutter dart asynchronous


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 2022-11-03
    • 2016-12-16
    • 2011-03-10
    • 2017-05-14
    • 2019-08-02
    • 1970-01-01
    相关资源
    最近更新 更多