'List <dynamic>'类型不是'Map <dynamic,dynamic>'类型的子类型

时间:2020-02-03 23:27:12

标签: json list object flutter

当我尝试将.json映射到对象列表时遇到一些问题,首先是.json使用的

0

接下来是模型:

[{
"name": "Peru",
"capital": "Lima",
"region": "Americas",
"subregion": "South America",
"population": 31488700
}]

}

最后对此进行了测试,在这一部分中,我创建了一个模型示例,用于在tojson函数正确的情况下进行资产赋值:

import 'dart:convert';

import 'package:clean_architecture_tdd_course/features/country_info/domain/entities/country_info.dart';
import 'package:meta/meta.dart';

List<CountryInfoModel> countryFromJson(String str) => new 
List<CountryInfoModel>.from(json.decode(str).map((x) => CountryInfoModel.fromJson(x)));
String countryToJson(List<CountryInfoModel> data) => json.encode(new List<dynamic>.from(data.map((x) 
  => x.toJson())));

class CountryInfoModel extends CountryInfo {
  CountryInfoModel({
  @required String name,
  @required String capital,
  @required String region,
  @required String subregion,
  @required int population,

}) : super(name:name, capital:capital, region:region, subregion:subregion, population:population);

factory CountryInfoModel.fromJson(Map<String, dynamic> json) {
  return CountryInfoModel(
    name: json['name'],
    capital: json['capital'],
    region: json['region'],
    subregion: json['subregion'],
    population: (json['population'] as num).toInt()
  );
}

Map<String, dynamic> toJson() {
  return {
    'name': name,
    'capital': capital,
    'region': region,
    'subregion': subregion,
    'population': population
  };
}

运行测试时,它会抛出以下内容:

void main() {
  final tCountryInfoModel = CountryInfoModel(name: 'Peru', capital: 'Lima', region: "Americas",
      subregion: "South Americas", population: 31488700);


group('fromJson', () {
test(
  'should return a valid model',
  () async {
    // arrange
    final Map jsonMap =
        json.decode(fixture('country_info.json'));
    // act
   final result = countryFromJson(jsonMap.toString());
    // assert
    expect(result[0], tCountryInfoModel);
  },
);

1 个答案:

答案 0 :(得分:1)

您在测试中犯了一个简单的错误:

// arrange
final Map jsonMap =
    json.decode(fixture('country_info.json'));
// act
final result = countryFromJson(jsonMap.toString());

像这样更改它:

final result = countryFromJson(fixture('country_info.json'));

由于在countryFromJson内,您再次在解码。