【发布时间】:2020-04-29 07:16:27
【问题描述】:
我有问题,我从 API 获取数据并保存到本地数据库。 所以作为 Flutter 的新手,我想找到一种方法将数据保存在数据库中以供离线支持。
这是问题错误
Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>' in type cast
我的模型数据是这样的
List<Employee> employeeFromJson(String str) =>
List<Employee>.from(json.decode(str).map((x) => Employee.fromJson(x)));
String employeeToJson(List<Employee> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Employee {
int id;
String id_surat;
String nama;
String nomor;
String arti;
Employee({
this.id,
this.id_surat,
this.nama,
this.nomor,
this.arti,
});
factory Employee.fromJson(Map<String, dynamic> json) => Employee(
id_surat: json["id_surat"],
nama: json["nama"],
nomor: json["nomor"],
arti: json["arti"],
);
Map<String, dynamic> toJson() => {
"id_surat": id_surat,
"nama": nama,
"nomor": nomor,
"arti": arti,
};
}
下面是从网络查询的JSON解析方法:
class EmployeeApiProvider {
Future<List<Employee>> getAllEmployees() async {
var url = "EXAMPLE";
Response response = await Dio().get(url);
print(response.data);
return (response.data as List).map((employee) {
print('Inserting $employee');
DBProvider.db.createEmployee(Employee.fromJson(employee));
}).toList();
}
}
和来自 API 服务器的响应,像这样。
[
{
id_surat: "1",
nama: "Al Fatihah",
nomor: "1",
arti: "Pembukaan"
},
{
id_surat: "2",
nama: "Al Baqarah",
nomor: "2",
arti: "Sapi Betina"
},
{
id_surat: "3",
nama: "Ali Imran",
nomor: "3",
arti: "Keluarga Imran"
},
{
id_surat: "4",
nama: "An Nisaa",
nomor: "4",
arti: "Wanita"
},
]
【问题讨论】: