2

I am trying to store the api data in sqflite but getting "Exception has occurred. _CastError (type 'String' is not a subtype of type 'List' in type cast)". Please help me to resolve this.

This is to fetch the api data.(employee_api_provider.dart)

//import 'package:flutter/cupertino.dart';
import 'package:flutter_app/src/models/employee_model.dart';
import 'package:flutter_app/src/providers/db_provider.dart';
import 'package:dio/dio.dart';

class EmployeeApiProvider {
  Future<List<Employee>> getAllEmployees() async {
    var url = "url";
    Response response = await Dio().get(url);
    //debugPrint(response);

    return (response.data as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.createEmployee(Employee.fromJson(employee));
    }).toList();
  }
}

I have created the model class(employee_model.dart)

 import 'dart:convert';

    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;
      int eventId;
      String menuName;
      String menuIcon;
      String deepLinkName;
      int displayStatus;
      int orderId;
      String dateTime;

      Employee({
        this.id,
        this.eventId,
        this.menuName,
        this.menuIcon,
        this.deepLinkName,
        this.displayStatus,
        this.orderId,
        this.dateTime,
      });

      factory Employee.fromJson(Map<String, dynamic> json) => Employee(
            id: json["Id"],
            eventId: json["Event_Id"],
            menuName: json["Menu_Name"],
            menuIcon: json["Menu_Icon"],
            deepLinkName: json["Deep_Link_Name"],
            displayStatus: json["Display_Status"],
            orderId: json["Order_Id"],
            dateTime: json["Date_Time"],
          );

      Map<String, dynamic> toJson() => {
            "Id": id,
            "Event_Id": eventId,
            "Menu_Name": menuName,
            "Menu_Icon": menuIcon,
            "Deep_Link_Name": deepLinkName,
            "Display_Status": displayStatus,
            "Order_Id": orderId,
            "Date_Time": dateTime,
          };
    }

db_provider.dart

import 'dart:io';
import 'package:flutter_app/src/models/employee_model.dart';
import 'package:path/path.dart';

import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DBProvider {
  static Database _database;
  static final DBProvider db = DBProvider._();

  DBProvider._();

  Future<Database> get database async {
    // If database exists, return database
    if (_database != null) return _database;

    // If database don't exists, create one
    _database = await initDB();

    return _database;
  }

  // Create the database and the Employee table
  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    final path = join(documentsDirectory.path, 'menu.db');

    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute('CREATE TABLE Employee('
          'id INTEGER,'
          'eventId INTEGER,'
          'menuName TEXT,'
          'menuIcon TEXT,'
          'deepLinkName TEXT,'
          'displayStatus INTEGER,'
          'orderId INTEGER,'
          'DateTime TEXT'
          ')');
    });
  }

  // Insert employee on database
  createEmployee(Employee newEmployee) async {
    await deleteAllEmployees();
    final db = await database;
    final res = await db.insert('Employee', newEmployee.toJson());

    return res;
  }

  // Delete all employees
  Future<int> deleteAllEmployees() async {
    final db = await database;
    final res = await db.rawDelete('DELETE FROM Employee');

    return res;
  }

  Future<List<Employee>> getAllEmployees() async {
    final db = await database;
    final res = await db.rawQuery("SELECT * FROM EMPLOYEE");

    List<Employee> list =
        res.isNotEmpty ? res.map((c) => Employee.fromJson(c)).toList() : [];

    return list;
  }
}

db_provider.dart

2
  • if possible can you add full stacktrace Commented Dec 21, 2019 at 8:39
  • @VijayaRagavan i have added the full code. please check. i am getting error in employee_api_provider.dart('return (response.data as List).map((employee) {). please check Commented Dec 21, 2019 at 9:14

2 Answers 2

1

Use this in employee_api_provider.dart

return employeeFromJson(response.data).map((employee) {
  print('Inserting $employee');
  DBProvider.db.createEmployee(employee);
}).toList();

instead of

return (response.data as List).map((employee) {
  print('Inserting $employee');
  DBProvider.db.createEmployee(Employee.fromJson(employee));
}).toList();
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your help. I tried but getting error "The argument type 'Response' can't be assigned to the parameter type 'String'.dart(argument_type_not_assignable)"
@arul sorry. I used response instead of response.data. I updated the answer. pls check it again
Still I'm getting this error: <A value of type 'List<Null>' can't be returned from the method 'getAllEmployees' because it has a return type of 'Future<List<employee_model>>>
0

Please use this flutter plugin json_store

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.