Flutter FetchData from API and save local with sqflite

813

I think you should replace:

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

with:

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

You already pass in List<Employee> that you want to encode.

You shouldn't need List<dynamic>.from and that inner function which creates List<dynamic>. According to documentation, List<dynamic> is not directly encodable.

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

Share:
813
Zaboy
Author by

Zaboy

Updated on December 17, 2022

Comments

  • Zaboy
    Zaboy over 1 year

    I have problem , went i'm fetch data from API and save to database local . So being a newbie in Flutter, I would like to find a way to save the data in a database for offline support.

    This the problem error

    Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>' in type cast
    

    My Model Data like this

    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,
          };
    }
    

    Here is the JSON parsing method that queries from the network:

    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();
      }
    }
    

    And Response from API Server , like this .

    [
    {
    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"
    },
    ]