简体   繁体   English

Flutter '未处理的异常:类型'列表<dynamic> ' 不是类型 'List 的子类型<class> '</class></dynamic>

[英]Flutter 'Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<class>'

I'm getting data from an API and i'm trying to push that data into two variables.我正在从 API 获取数据,并且正在尝试将这些数据推送到两个变量中。 I can access part of the data being returned but not all of it, I can print all of the data but when I try to access a specific part of it, it doesn't work.我可以访问返回的部分数据,但不是全部,我可以打印所有数据,但是当我尝试访问其中的特定部分时,它不起作用。

EG: res = response from API EG: res = 来自 API 的响应

print(res.data); // This works
print(res.feeds); // This doesn't work
print(res.feeds.id); // This doesn't work

The error I am getting is:我得到的错误是:

'Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<FeedItem>'

This is how i'm converting and reading the data:这就是我转换和读取数据的方式:

class FeedData {
  String data;
  List<FeedItem> feeds;

  FeedData({this.data, this.feeds});

  factory FeedData.fromJson(Map<String, dynamic> json) {
    return FeedData(
      data: json['data'],
      feeds: json['feeds'],
    );
  }
}

I can read and access the 'data' but not the 'feeds' which is my problem, I need to be able to access the data in the 'feeds' The 'FeedItem' class is built in the same way as the 'FeedData' class so I'm sure that it is built properly我可以读取和访问“数据”但不能访问“提要”,这是我的问题,我需要能够访问“提要”中的数据“FeedItem”class 的构建方式与“FeedData”相同class 所以我确定它是正确构建的

This is how I'm calling the data:这就是我调用数据的方式:

getUserFeed() async {
    FeedData res = FeedData.fromJson(
        await requests.get(url: 'feeds/u?u=jxchumber&PageNumber=1'));
    print(res.data);
    // res.data works
    print(res.feeds);
    // res.feeds doesn't work
  }

This is the data being returned from the API:这是从 API 返回的数据:

{
    "data": "default",
    "feeds": [
        {
            "id": 2,
            "photoUrl": "https://cartalkio-image-storage-dev.s3.eu-west-2.amazonaws.com/o85DvOaTXXE.jpg",
            "description": "Magna duis consectetur sit ut commodo non eiusmod.",
            "dateAdded": "0001-01-01T00:00:00",
            "isMain": false,
            "publicId": null,
            "isImage": true,
            "mainImage": "https://randomuser.me/api/portraits/men/76.jpg",
            "userId": 9,
            "likers": null,
            "username": "Larsen",
            "thumbnail": null,
            "likes": 0
        },
        {
            "id": 4,
            "photoUrl": "https://cartalkio-image-storage-dev.s3.eu-west-2.amazonaws.com/lXR833PRh3g.jpg",
            "description": "Magna duis consectetur sit ut commodo non eiusmod.",
            "dateAdded": "0001-01-01T00:00:00",
            "isMain": false,
            "publicId": null,
            "isImage": true,
            "mainImage": "https://randomuser.me/api/portraits/men/4.jpg",
            "userId": 8,
            "likers": null,
            "username": "Lloyd",
            "thumbnail": null,
            "likes": 0
        },
}

When you are doing feeds: json['feeds'] , You are basically trying to assign a Map<String,dynamic> to a class FeedItem , Moreover you want to assign a complete list as List<Map<String,dynamic>> to List<FeedItem , The problem is that flutter just can't parse the data automatically and assign like this, You need to go deep level by level and assign Map<String,dynamic> to FeedItem and then finally convert it to a List当您进行feeds: json['feeds'] ,您基本上是在尝试将Map<String,dynamic>分配给 class FeedItem ,此外,您希望将完整列表分配为List<Map<String,dynamic>>List<FeedItem ,问题是 flutter 无法自动解析数据并像这样分配,您需要逐级深入 go 并将Map<String,dynamic>分配给FeedItem最后将其转换为 List

I will share a piece of code based on my knowledge, how I tackle this type of problem and I believe that will give you better insight about your problem ( if not solve it )我将根据我的知识分享一段代码,我如何解决这类问题,我相信这会让你更好地了解你的问题(如果没有解决它)

Future<void> getData() async {
http.Response response =
    await http.get('Example address');
if (response.statusCode == HttpStatus.ok) {
//if the status code is 200 or 'OK' parse the data and convert Outer layer as List
//after that , Map each element as a FeedItem and finally convert the result to List
  feeds = (json.decode(response.body) as List)
      .map<FeedItem>(
          (_feed) => FeedItem.fromJSON(_feed))
      .toList();
} else {
  throw response;
}

} }

You are not converting feedItems to objects您没有将 feedItems 转换为对象

  factory FeedData.fromJson(Map<String, dynamic> json) {
    return FeedData(
      data: json['data'],
      feeds: json['feeds'],  # <- here is the problem
    );

Should be something like this:应该是这样的:

feeds: (json['feeds'] as List)
        ?.map((e) =>
            e == null ? null : FeedItem.fromJson(e as Map<String, dynamic>))
        ?.toList(),

The error is because you are not passing json['feeds'] as a List.该错误是因为您没有将 json['feeds'] 作为列表传递。 Your FeedData class will have to be changed to the following, this is assuming that your FeedItem class also has a fromJson method:您的 FeedData class 必须更改为以下内容,这是假设您的 FeedItem class 也具有 fromJson 方法:

class FeedData {
  String data;
  List<FeedItem> feeds;

  FeedData({this.data, this.feeds});

  factory FeedData.fromJson(Map<String, dynamic> json) {
    return FeedData(
      data: json['data'],
      feeds: List.from(json['feeds']).map((item)=>FeedItem.fromJson(item)).toList(),
    );
  }
}

Please see the working code based on your data.请根据您的数据查看工作代码。 You can also load the following code on DartPad https://dartpad.dev/24694a911ddd0619277f5780573086f1您还可以在DartPad https://dartpad.dev/24694a911ddd0619277f5780573086f1上加载以下代码

void main() {

  Map<String, dynamic> json = {
    "data": "default",
    "feeds": [
        {
            "id": 2,
            "photoUrl": "https://cartalkio-image-storage-dev.s3.eu-west-2.amazonaws.com/o85DvOaTXXE.jpg",
            "description": "Magna duis consectetur sit ut commodo non eiusmod.",
            "dateAdded": "0001-01-01T00:00:00",
            "isMain": false,
            "publicId": null,
            "isImage": true,
            "mainImage": "https://randomuser.me/api/portraits/men/76.jpg",
            "userId": 9,
            "likers": null,
            "username": "Larsen",
            "thumbnail": null,
            "likes": 0
        },
        {
            "id": 4,
            "photoUrl": "https://cartalkio-image-storage-dev.s3.eu-west-2.amazonaws.com/lXR833PRh3g.jpg",
            "description": "Magna duis consectetur sit ut commodo non eiusmod.",
            "dateAdded": "0001-01-01T00:00:00",
            "isMain": false,
            "publicId": null,
            "isImage": true,
            "mainImage": "https://randomuser.me/api/portraits/men/4.jpg",
            "userId": 8,
            "likers": null,
            "username": "Lloyd",
            "thumbnail": null,
            "likes": 0
        },
      ]
};
  
  
  FeedData feedData = FeedData.fromJson(json);
  print(feedData.feeds.length);
}


class FeedData {
  String data;
  List<FeedItem> feeds;

  FeedData({this.data, this.feeds});

  factory FeedData.fromJson(Map<String, dynamic> json) {
    return FeedData(
      data: json['data'],
      feeds: List.from(json['feeds']).map((item)=>FeedItem.fromJson(item)).toList(),
    );
  }
}


class FeedItem {
  int id;
  String photoUrl;
  String description;
  String dateAdded;
  bool isMain;
  Null publicId;
  bool isImage;
  String mainImage;
  int userId;
  Null likers;
  String username;
  Null thumbnail;
  int likes;

  FeedItem(
      {this.id,
      this.photoUrl,
      this.description,
      this.dateAdded,
      this.isMain,
      this.publicId,
      this.isImage,
      this.mainImage,
      this.userId,
      this.likers,
      this.username,
      this.thumbnail,
      this.likes});

  FeedItem.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    photoUrl = json['photoUrl'];
    description = json['description'];
    dateAdded = json['dateAdded'];
    isMain = json['isMain'];
    publicId = json['publicId'];
    isImage = json['isImage'];
    mainImage = json['mainImage'];
    userId = json['userId'];
    likers = json['likers'];
    username = json['username'];
    thumbnail = json['thumbnail'];
    likes = json['likes'];
  }
}

Please change this code请更改此代码

print(res.feeds);    -->  print(res.feeds[0]);
print(res.feeds.id); --> print(res.feeds[0].id);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:未处理的异常:键入“列表”<dynamic> ' 不是类型 'List 的子类型<string> '</string></dynamic> - Flutter:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>' Dart 未处理的异常:键入“列表”<dynamic> ' 不是类型 'Family' 的子类型,- Flutter</dynamic> - Dart Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Family', - Flutter 未处理的异常:键入“列表”<dynamic> ' 不是 'SubJsonModel' 类型的子类型 - flutter</dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'SubJsonModel' - flutter Flutter:未处理的异常:输入“未来” <list<dynamic> &gt;' 不是类型“列表”的子类型<dynamic> ' 在类型转换中</dynamic></list<dynamic> - Flutter: Unhandled Exception: type 'Future<List<dynamic>>' is not a subtype of type 'List<dynamic>' in type cast 未处理的异常:键入“列表”<dynamic> ' 不是类型 'List 的子类型<map<dynamic, dynamic> &gt;' Flutter Firebase </map<dynamic,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>' Flutter Firebase Flutter Hive - 未处理的异常:输入“列表”<dynamic> &#39; 不是 &#39;List 类型的子类型<SourceStations> &#39; 在类型转换中 - Flutter Hive - Unhandled exception: type 'List<dynamic>' is not a subtype of type 'List<SourceStations>' in type cast Flutter:未处理的异常:键入“列表”<dynamic> ' 不是类型 'List 的子类型<double> ' 在类型转换中</double></dynamic> - Flutter : Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<double>' in type cast 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic> ' 在请求中的类型转换 flutter</dynamic></string,> - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast in request flutter 未处理的异常:键入“列表”<dynamic> ' 不是类型 'Map 的子类型<dynamic, dynamic> '</dynamic,></dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>' 未处理的异常:键入“列表”<dynamic> &#39; 不是类型 &#39;Map 的子类型<dynamic, dynamic> - Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM