Flutter报错:type 'Book'不是Map<String, dynamic>子类型 求代码修正
错误分析与修正方案
核心问题
你遇到的type 'Book' is not a subtype of type 'Map<String, dynamic>' in type cast错误,主要来自两个方面:
- 代码中存在把Book实例直接当作Map<String, dynamic>类型强制转换的场景(比如在需要传Map的地方直接传入Book对象)
- Book类的
fromJson方法存在类型不匹配的隐患
步骤1:修复Book类自身的类型问题
你的fromJson方法里,id是int?类型,但你用json['id'] ?? ""兜底,空字符串属于String类型,会导致类型不兼容,先修正这个问题:
class Book { final int? id; final String title; final String author; Book({ this.id, required this.title, required this.author, }); factory Book.fromJson(Map<String, dynamic> json) { return Book( // 修正:id是int?类型,用null作为兜底值 id: json['id'] as int?, // title和author为必填String,用空字符串兜底确保类型一致 title: json['title'] as String? ?? "", author: json['author'] as String? ?? "", ); } Map<String, dynamic> toJson() { return { 'id': id, 'title': title, 'author': author, }; } }
步骤2:修正类型转换场景
如果错误是因为把Book实例当作Map使用,需要在对应场景调用toJson()方法将其转为Map:
- 错误示例:
// 错误:直接传递Book对象给需要Map的方法 someMapRequiredFunction(bookInstance); - 正确写法:
// 正确:调用toJson()转为Map后传递 someMapRequiredFunction(bookInstance.toJson());
另外,若你是在调用fromJson时传入了Book实例而非Map,也要修正:
- 错误示例:
// 错误:将Book对象传入fromJson方法 Book.fromJson(existingBook); - 正确写法:
// 正确:传入Map类型数据 Book.fromJson(someValidMapData); // 若要复制已有Book实例,直接构造新对象即可 Book newBook = Book(id: existingBook.id, title: existingBook.title, author: existingBook.author);
内容的提问来源于stack exchange,提问作者Shishir Wagle K
相关产品推荐
相关产品推荐

