【问题标题】:Flutter FetchData from API and save local with sqflite从 API Flutter FetchData 并使用 sqflite 保存本地
【发布时间】: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"
},
]

【问题讨论】:

    标签: api flutter dart sqflite


    【解决方案1】:

    我认为你应该替换:

     String employeeToJson(List<Employee> data) =>
            json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    

    与:

    String employeeToJson(List<Employee> data) => json.encode(data); 
    

    您已经传入要编码的List&lt;Employee&gt;

    你不应该需要List&lt;dynamic&gt;.from 和创建List&lt;dynamic&gt; 的内部函数。根据文档,List&lt;dynamic&gt; 不能直接编码。

    https://api.flutter.dev/flutter/dart-convert/jsonEncode.html

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 2018-11-17
      • 2021-04-24
      • 2020-01-11
      • 2020-12-01
      • 2023-03-29
      • 1970-01-01
      • 2019-07-01
      相关资源
      最近更新 更多