Android 类型列表<;动态>;不是Map的子类型<;字符串,动态>;

Android 类型列表<;动态>;不是Map的子类型<;字符串,动态>;,android,flutter,dart,mobile-development,Android,Flutter,Dart,Mobile Development,我已经能够学习一些关于基本UI设计的颤振教程,并且对API调用还不熟悉。我认为在进行API调用后需要转换类型,但我不知道如何转换 注意:我知道在一个文件中有很多代码,但我会将API调用文件和自定义类文件与主文件分开 import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:

我已经能够学习一些关于基本UI设计的颤振教程,并且对API调用还不熟悉。我认为在进行API调用后需要转换类型,但我不知道如何转换

注意:我知道在一个文件中有很多代码,但我会将API调用文件和自定义类文件与主文件分开

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

Future<Country> fetchAlbum() async {
  final response = await http.get('https://restcountries.eu/rest/v2/all');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Country.fromJson(json.decode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Country {
  final String name;
  final List<String> topLevelDomain;
  final String alpha2Code;
  final String alpha3Code;
  final String callingCodes;
  final String capital;
  final String region;
  final String subregion;
  final int population;
  final List<int> latlng;
  final String demonym;
  final int area;
  final int gini;
  final List<String> timezones;
  final List<String> borders;
  final String nativeName;
  final int numericCode;
  final List<String> currencies;
  final List<String> translations;
  final String flag;
  final String cioc;

  Country({
    @required this.name,
    @required this.topLevelDomain,
    @required this.alpha2Code,
    @required this.alpha3Code,
    @required this.callingCodes,
    @required this.capital,
    @required this.region,
    @required this.subregion,
    @required this.population,
    @required this.latlng,
    @required this.demonym,
    @required this.area,
    @required this.gini,
    @required this.timezones,
    @required this.borders,
    @required this.nativeName,
    @required this.numericCode,
    @required this.currencies,
    @required this.translations,
    @required this.flag,
    @required this.cioc,
  });

  factory Country.fromJson(Map<String, dynamic> json) {
    return Country(
      name: json['name'],
      topLevelDomain: json['topLevelDomain'],
      alpha2Code: json['alpha2Code'],
      alpha3Code: json['alpha3Code'],
      callingCodes: json['callingCodes'],
      capital: json['capital'],
      region: json['region'],
      subregion: json['subregion'],
      population: json['population'],
      latlng: json['latlng'],
      demonym: json['demonym'],
      area: json['area'],
      gini: json['gini'],
      timezones: json['timezones'],
      borders: json['borders'],
      nativeName: json['nativeName'],
      numericCode: json['numericCode'],
      currencies: json['currencies'],
      translations: json['translations'],
      flag: json['flag'],
      cioc: json['cioc'],
    );
  }
}

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  Future<Country> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Country>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.name);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
导入'dart:async';
导入“dart:convert”;
进口“包装:颤振/基础.dart”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
Future fetchAlbum()异步{
最终响应=等待http.get('https://restcountries.eu/rest/v2/all');
如果(response.statusCode==200){
//如果服务器确实返回了200 OK响应,
//然后解析JSON。
return Country.fromJson(json.decode(response.body));
}否则{
//如果服务器没有返回200 OK响应,
//然后抛出一个异常。
抛出异常(“加载相册失败”);
}
}
阶级国家{
最后的字符串名;
最终列表topLevelDomain;
最后的字符串字母代码;
最后的字符串字母代码;
最终字符串调用代码;
最终的字符串资本;
最终字符串区域;
最后一串子区域;
最终整数总体;
最终清单;
最后的字符串名称;
最终国际区;
最终国际基尼;
最后列出时区;
最后的边界清单;
最终字符串nativeName;
最终整数编码;
最后清单货币;
最终翻译清单;
最终字符串标志;
最终字符串cioc;
国家({
@需要此名称,
@需要此.topLevelDomain,
@需要此字母2代码,
@需要此.alpha3Code,
@需要此。调用代码,
@需要这个资本,
@需要这个区域,
@需要这个分区域,
@需要这个。人口,
@需要这个,
@必须使用此.demonym,
@需要这个区域,
@需要这个,基尼,
@需要此选项。时区,
@需要这个。边界,
@需要此.nativeName,
@需要此.numericCode,
@需要这个。货币,
@需要这个翻译,
@需要这个.flag,
@需要这个.cioc,
});
factory Country.fromJson(映射json){
返回国(
名称:json['name'],
topLevelDomain:json['topLevelDomain'],
alpha2Code:json['alpha2Code'],
alpha3Code:json['alpha3Code'],
callingCodes:json['callingCodes'],
大写:json[“大写”],
region:json['region'],
subsection:json['subsection'],
人口:json['population'],
latlng:json['latlng'],
demonym:json['demonym'],
area:json['area'],
gini:json['gini'],
时区:json['timezones'],
borders:json['borders'],
nativeName:json['nativeName'],
numericCode:json['numericCode'],
货币:json[“货币”],
翻译:json['translations'],
flag:json['flag'],
cioc:json['cioc'],
);
}
}
void main()=>runApp(MyApp());
类MyApp扩展了StatefulWidget{
MyApp({Key}):超级(Key:Key);
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
未来专辑;
@凌驾
void initState(){
super.initState();
futureAlbum=fetchAlbum();
}
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“获取数据示例”,
主题:主题数据(
主样本:颜色。蓝色,
),
家:脚手架(
appBar:appBar(
标题:文本(“获取数据示例”),
),
正文:中(
孩子:未来建设者(
未来:未来专辑,
生成器:(上下文,快照){
if(snapshot.hasData){
返回文本(snapshot.data.name);
}else if(snapshot.hasrerror){
返回文本(“${snapshot.error}”);
}
//默认情况下,显示加载微调器。
返回循环ProgressIndicator();
},
),
),
),
);
}
}

下面是我的模拟器屏幕的样子:

第12行“return Country.fromJson(json.decode(response.body));”


我认为'json.decode(response.body)'的类型是一个'List',但这里的参数类型是Map。也许您的响应是一个国家对象列表,但它返回1个国家对象。这就是为什么会出现此错误

您的API返回的是
List
,而不是
Map

您需要将每个元素映射为
国家

Future<List<Country>> fetchAlbum() async {
  final response = await http.get('https://restcountries.eu/rest/v2/all');

  if (response.statusCode == 200) {
     List<Country> countryList = ((json.decode(response.body) as List).map((i) => Country.fromJson(i)).toList();
    return countryList;
  } else {
    throw Exception('Failed to load album');
  }
}
Future fetchAlbum()异步{
最终响应=等待http.get('https://restcountries.eu/rest/v2/all');
如果(response.statusCode==200){
List countryList=(json.decode(response.body)为List.map((i)=>Country.fromJson(i)).toList();
返回国家列表;
}否则{
抛出异常(“加载相册失败”);
}
}

尝试使用
工厂国家/地区。fromJson(Map json)
类型列表不是MapTry使用工厂国家/地区的sybtype。fromJson(dynamic json)可能就是这样;我该如何更改返回类型?这取决于您。该API返回一个列表。因此,您可以首先获取列表,运行循环并转换每个元素(类型是Map)对你的对象做你想做的事我是个新手;你能写出代码并给我解释一下吗?
Future fetchAlbum()async{final response=wait http.get('https://restcountries.eu/rest/v2/all');如果(response.statusCode==200){//如果服务器确实返回了200 OK响应,//则解析JSON.List List=[];JSON.decode(response.body).forEach((e)=>List.add(Country.fromJson(e));返回List;}否则{//如果服务器没有返回200 OK响应,则引发异常。引发异常('无法加载相册')}
如果要使用国家/地区列表,必须更改函数return Future。或者只返回一个要使用的国家/地区。我的仿真程序屏幕上显示“type list不是list的子类型”。下面是代码: