Преобразованный JSON ничего не отображает в ListView

#flutter #dart

#flutter #dart

Вопрос:

Я работаю с Cat API https://api.thecatapi.com/v1/breeds / и я пытаюсь отобразить данные в виде списка. Я пытаюсь преобразовать ответ

 Future<List<CatData>> fetchCats(http.Client client) async {
  final response = await client.get('https://api.thecatapi.com/v1/breeds/');
  return compute(parseCat, response.body);
}

List<CatData> parseCat(responseBody) {
  final parsed = jsonDecode(responseBody) as Map<String, dynamic>;
  return parsed[""].map<CatData>((json) => CatData.fromJson(json)).toList();
}
  

Но список ничего не отображает. Скорее всего, ошибка в return parsed[""] том, что json файл начинается с [] . Как я могу это исправить?

Ответ №1:

Вы можете скопировать вставить запустить полный код ниже
, который вы можете использовать catDataFromJson , см. Полный Код для получения подробной
информации, которую вы можете parseCat непосредственно return catDataFromJson(responseBody);
фрагмент кода

 List<CatData> catDataFromJson(String str) =>
    List<CatData>.from(json.decode(str).map((x) => CatData.fromJson(x)));
    
List<CatData> parseCat(String responseBody) {
  return catDataFromJson(responseBody);
}   
  

рабочая демонстрация

введите описание изображения здесь

полный код

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

import 'dart:convert';

List<CatData> catDataFromJson(String str) =>
    List<CatData>.from(json.decode(str).map((x) => CatData.fromJson(x)));

String catDataToJson(List<CatData> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class CatData {
  CatData({
    this.weight,
    this.id,
    this.name,
    this.cfaUrl,
    this.vetstreetUrl,
    this.vcahospitalsUrl,
    this.temperament,
    this.origin,
    this.countryCodes,
    this.countryCode,
    this.description,
    this.lifeSpan,
    this.indoor,
    this.lap,
    this.altNames,
    this.adaptability,
    this.affectionLevel,
    this.childFriendly,
    this.dogFriendly,
    this.energyLevel,
    this.grooming,
    this.healthIssues,
    this.intelligence,
    this.sheddingLevel,
    this.socialNeeds,
    this.strangerFriendly,
    this.vocalisation,
    this.experimental,
    this.hairless,
    this.natural,
    this.rare,
    this.rex,
    this.suppressedTail,
    this.shortLegs,
    this.wikipediaUrl,
    this.hypoallergenic,
    this.catFriendly,
    this.bidability,
  });

  Weight weight;
  String id;
  String name;
  String cfaUrl;
  String vetstreetUrl;
  String vcahospitalsUrl;
  String temperament;
  String origin;
  String countryCodes;
  String countryCode;
  String description;
  String lifeSpan;
  int indoor;
  int lap;
  String altNames;
  int adaptability;
  int affectionLevel;
  int childFriendly;
  int dogFriendly;
  int energyLevel;
  int grooming;
  int healthIssues;
  int intelligence;
  int sheddingLevel;
  int socialNeeds;
  int strangerFriendly;
  int vocalisation;
  int experimental;
  int hairless;
  int natural;
  int rare;
  int rex;
  int suppressedTail;
  int shortLegs;
  String wikipediaUrl;
  int hypoallergenic;
  int catFriendly;
  int bidability;

  factory CatData.fromJson(Map<String, dynamic> json) => CatData(
        weight: Weight.fromJson(json["weight"]),
        id: json["id"],
        name: json["name"],
        cfaUrl: json["cfa_url"] == null ? null : json["cfa_url"],
        vetstreetUrl:
            json["vetstreet_url"] == null ? null : json["vetstreet_url"],
        vcahospitalsUrl:
            json["vcahospitals_url"] == null ? null : json["vcahospitals_url"],
        temperament: json["temperament"],
        origin: json["origin"],
        countryCodes: json["country_codes"],
        countryCode: json["country_code"],
        description: json["description"],
        lifeSpan: json["life_span"],
        indoor: json["indoor"],
        lap: json["lap"] == null ? null : json["lap"],
        altNames: json["alt_names"] == null ? null : json["alt_names"],
        adaptability: json["adaptability"],
        affectionLevel: json["affection_level"],
        childFriendly: json["child_friendly"],
        dogFriendly: json["dog_friendly"],
        energyLevel: json["energy_level"],
        grooming: json["grooming"],
        healthIssues: json["health_issues"],
        intelligence: json["intelligence"],
        sheddingLevel: json["shedding_level"],
        socialNeeds: json["social_needs"],
        strangerFriendly: json["stranger_friendly"],
        vocalisation: json["vocalisation"],
        experimental: json["experimental"],
        hairless: json["hairless"],
        natural: json["natural"],
        rare: json["rare"],
        rex: json["rex"],
        suppressedTail: json["suppressed_tail"],
        shortLegs: json["short_legs"],
        wikipediaUrl:
            json["wikipedia_url"] == null ? null : json["wikipedia_url"],
        hypoallergenic: json["hypoallergenic"],
        catFriendly: json["cat_friendly"] == null ? null : json["cat_friendly"],
        bidability: json["bidability"] == null ? null : json["bidability"],
      );

  Map<String, dynamic> toJson() => {
        "weight": weight.toJson(),
        "id": id,
        "name": name,
        "cfa_url": cfaUrl == null ? null : cfaUrl,
        "vetstreet_url": vetstreetUrl == null ? null : vetstreetUrl,
        "vcahospitals_url": vcahospitalsUrl == null ? null : vcahospitalsUrl,
        "temperament": temperament,
        "origin": origin,
        "country_codes": countryCodes,
        "country_code": countryCode,
        "description": description,
        "life_span": lifeSpan,
        "indoor": indoor,
        "lap": lap == null ? null : lap,
        "alt_names": altNames == null ? null : altNames,
        "adaptability": adaptability,
        "affection_level": affectionLevel,
        "child_friendly": childFriendly,
        "dog_friendly": dogFriendly,
        "energy_level": energyLevel,
        "grooming": grooming,
        "health_issues": healthIssues,
        "intelligence": intelligence,
        "shedding_level": sheddingLevel,
        "social_needs": socialNeeds,
        "stranger_friendly": strangerFriendly,
        "vocalisation": vocalisation,
        "experimental": experimental,
        "hairless": hairless,
        "natural": natural,
        "rare": rare,
        "rex": rex,
        "suppressed_tail": suppressedTail,
        "short_legs": shortLegs,
        "wikipedia_url": wikipediaUrl == null ? null : wikipediaUrl,
        "hypoallergenic": hypoallergenic,
        "cat_friendly": catFriendly == null ? null : catFriendly,
        "bidability": bidability == null ? null : bidability,
      };
}

class Weight {
  Weight({
    this.imperial,
    this.metric,
  });

  String imperial;
  String metric;

  factory Weight.fromJson(Map<String, dynamic> json) => Weight(
        imperial: json["imperial"],
        metric: json["metric"],
      );

  Map<String, dynamic> toJson() => {
        "imperial": imperial,
        "metric": metric,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

List<CatData> parseCat(String responseBody) {
  return catDataFromJson(responseBody);
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List<CatData>> _future;

  Future<List<CatData>> fetchCats(http.Client client) async {
    final response = await client.get('https://api.thecatapi.com/v1/breeds/');
    return compute(parseCat, response.body);
  }

  @override
  void initState() {
    _future = fetchCats(http.Client());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<CatData>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].name.toString()),
                                    Spacer(),
                                    Text(snapshot.data[index].id),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
  

Ответ №2:

Ответ Cat API представляет собой список объектов. Таким образом, вы можете преобразовать проанализированный ответ в виде списка и выполнить над ним преобразование. Также parsed[""] недопустимо.

 List<CatData> parseCat(responseBody) {
  final parsed = jsonDecode(responseBody) as List;
  return parsed.map<CatData>((json) => CatData.fromJson(json)).toList();
}