gpt4 book ai didi

flutter - 转换后的JSON在listView中不显示任何内容

转载 作者:行者123 更新时间:2023-12-03 04:35:17 25 4
gpt4 key购买 nike

我正在使用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文件以[]开头。我怎样才能解决这个问题?

最佳答案

您可以在下面复制粘贴运行完整代码
您可以使用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);
}
工作演示
enter image description here
完整的代码
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),
],
),
));
});
}
}
}));
}
}

关于flutter - 转换后的JSON在listView中不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64232629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com