Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 转换后的JSON在listView中不显示任何内容_Flutter_Dart - Fatal编程技术网

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

Flutter 转换后的JSON在listView中不显示任何内容,flutter,dart,Flutter,Dart,我正在使用Cat API,并试图在列表中显示数据。 我试图转换反应 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> p

我正在使用Cat API,并试图在列表中显示数据。 我试图转换反应

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();
}
Future fetchCats(http.Client)异步{
最终响应=等待客户端。获取('https://api.thecatapi.com/v1/breeds/');
返回compute(parseCat,response.body);
}
列表parseCat(响应库){
最终解析=jsonDecode(responseBody)作为映射;
返回已解析的[“”].map((json)=>CatData.fromJson(json)).toList();
}

但列表并没有显示任何内容。由于
json
文件以[]开头,因此
return parsed[“”]
中很可能出现错误。如何修复此问题?

Cat API的响应是对象列表。因此,您可以将解析后的响应转换为列表,并对其进行转换。另外,
解析的[“”]
也无效

List parseCat(responseBody){
最终解析=jsonDecode(responseBody)作为列表;
返回parsed.map((json)=>CatData.fromJson(json)).toList();
}

您可以复制粘贴运行下面的完整代码
您可以使用
catDataFromJson
,有关详细信息,请参阅完整代码
您可以在
parseCat
中直接
返回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);
}   
List catDataFromJson(String str)=>
List.from(json.decode(str.map)(x)=>CatData.fromJson(x));
列表parseCat(字符串响应库){
返回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),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
导入“包:flift/foundation.dart”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
导入“dart:convert”;
列表catDataFromJson(字符串str)=>
List.from(json.decode(str.map)(x)=>CatData.fromJson(x));
字符串catDataToJson(列表数据)=>
encode(List.from(data.map((x)=>x.toJson());
类别CatData{
CatData({
这个重量,
这个身份证,
这个名字,
这个.cfaUrl,
这个.vetstreetUrl,
此.vcahospitalURL,
这个气质,,
这个,起源,,
这是国家代码,
这个国家代码,
这个.说明,,
这个,寿命,
这是室内的,
这一圈,
这是我的名字,
这就是适应性,
这个层次,,
这是对孩子友好的,
这只狗很友好,
这是energyLevel,
这个,打扮,
这是一个健康问题,
这就是我的智慧,
这是谢丁格勒维尔,
这是社会需要,,
这个,奇怪的友好,
这个,发声,
这是实验性的,
这个,无毛,
这是自然的,
这是罕见的,
这是雷克斯先生,
这个.抑制的尾巴,
这个,短腿,
这个.wikipediaUrl,
这是低致敏性,
这是友好的,
这就是可投标性,
});
重量;
字符串id;
字符串名;
字符串cfaUrl;
字符串vetstreetUrl;
字符串vcahospitalsUrl;
弦乐气质;
弦源;
字符串国家代码;
字符串国家代码;
字符串描述;
线寿命;
室内;
内圈;
字符串名称;
内在适应性;
智力水平;
int儿童友好型;
对狗友好;
国际能源水平;
整容;
国际卫生问题;
智力;
内舍丁格勒维尔;
国际社会需要;
奇怪的友好;
内发声;
int实验;
无毛;
int-natural;
int罕见;
int-rex;
int-suppressedTail;
短腿;
字符串wikipediaUrl;
低过敏性;
友好的;
不可投标性;
工厂CatData.fromJson(映射json)=>CatData(
weight:weight.fromJson(json[“weight”]),
id:json[“id”],
名称:json[“名称”],
cfaUrl:json[“cfa_url”]==null?null:json[“cfa_url”],
vetstreetUrl:
json[“vetstreet_url”]==null?null:json[“vetstreet_url”],
vCAhospitalURL:
json[“vcahospitals_url”]==null?null:json[“vcahospitals_url”],
气质:json[“气质”],
来源:json[“来源”],
countryCodes:json[“国家代码”],
countryCode:json[“国家代码”],
description:json[“description”],
寿命:json[“寿命”],
室内:json[“室内”],
lap:json[“lap”]==null?null:json[“lap”],
altNames:json[“alt_names”]==null?null:json[“alt_names”],
适应性:json[“适应性”],
情感等级:json[“情感等级”],
儿童友好型:json[“儿童友好型”],
dogFriendly:json[“dog_-friendly”],
energyLevel:json[“能量级别”],
修饰:json[“修饰”],
healthIssues:json[“健康问题”],
智能:json[“智能”],
sheddingLevel:json[“脱落水平”],
社交需求:json[“社交需求”],
陌生友好:json[“陌生友好”],
发声:json[“发声”],
实验性:json[“实验性”],
无毛:json[“无毛”],
natural:json[“natural”],
稀有:json[“稀有”],
rex:json[“rex”],
suppressedTail:json[“suppressed_tail”],
短腿:json[“短腿”],
维基百科网址:
json[“维基百科url”]==null?null:json[“维基百科url”],
低致敏性:json[“低致敏性”],
catFriendly:json[“cat_friendly”]==null?null:json[“cat_friendly”],
可投标性:json[“可投标性”]==null?null:json[“可投标性”],
);
映射到JSON()=>{
“weight”:weight.toJson(),
“id”:id,
“姓名”:姓名,
“cfa_url”:cfaUrl==null?null:cfaUrl,
“vetstreet_url”:vetstreetUrl==null?null:vetstreetUrl,
“vcahospitals_url”:vcahospitalsUrl==null?null:vcahospitalsUrl,
“气质”:气质,
“起源”:起源,
“国家代码”:国家代码,
“国家代码”:国家代码,
“描述”:描述,
“寿命”:寿命,
“室内”:室内,
“lap”:lap==null?null:lap,
“alt_names”:altNames==null?null:altNames,
"适应性":适应性,,
“情感水平”:情感水平,
“儿童友好型”