dart 类型“Book”不是类型转换中类型“Map〈String,dynamic>”的子类型

7nbnzgx9  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(114)
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: json['id'] ?? "",
      title: json['title'] ?? "",
      author: json['author'] ?? "",
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'author': author,
    };
  }
}

我得到这个错误类型'图书'不是类型'Map〈字符串,动态〉'在类型转换的子类型我已经提到了下面的代码,你能帮我纠正错误.

bihw5rsg

bihw5rsg1#

使用此类型的Model类

class UserModel {
 String? name;
 String? firstName;
 String? deviceToken;
 String? email;
 String? image;

UserModel({
  this.name,
  this.firstName,
  this.deviceToken,
  this.email,
  this.image,
   });

UserModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
firstName = json['firstName'];
deviceToken = json['deviceToken'];
email = json['email'];
image = json['image'];
  }

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
void writeNotNull(String key, dynamic value) {
  if (value != null && value.toString().isNotEmpty) {
    data[key] = value;
  }
}
writeNotNull("name", name);
writeNotNull("email", email);
writeNotNull("image", image);
return data;
  }
}

相关问题