簡體   English   中英

如何從數組中獲取數據?

[英]How can I get data from array?

我需要從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 object 格式,我創建了一個單獨的 ZA2F2ED4F8EBC2CBB4CBB4C21A29DC40AB1 的字段,其中描述了 Cat21A29DC40AB16 的參數。 目前我只使用“url”字段

我不明白我做錯了什么來顯示照片列表

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,
    );
  }

此外,在您的 getPics() 方法中,您用於獲取響應的 url 與您在問題中提供的鏈接不同。 兩個鏈接是否返回相同的響應?

暫無
暫無

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

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