rameez khan
rameez khan

Reputation: 359

Flutter getting error while inserting values in sqllite

I am trying to insert my data in sqllite

Here is my code

class Cart {
  int id;
  String title;
  String image;
  String price;
  String color;
  String sizeselect;

  Cart({
    this.id,
    this.title,
    this.image,
    this.price,
    this.color,
    this.sizeselect,

  });



  factory Cart.fromJson(Map<String, dynamic> data) => new Cart(
    id: data["id"],
    title: data["title"],
    image: data["image"],
    price: data["price"],
    color: data["color"],
    sizeselect: data["sizeselect"],

  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "title": title,
    "image": image,
    "price": price,
    "color": color,
    "sizeselect": sizeselect,

  };
}

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';
  
  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute("CREATE TABLE $table ("
    "id INTEGER PRIMARY KEY,"
    "title TEXT,"
    "image TEXT,"
    "color TEXT,"
    "price TEXT,"
    "sizeselect TEXT"
    ")");


  }


  Future<int> insert(cart) async {
    print(cart.id);
    Database db = await instance.database;
    return await db.insert(table, cart);
  }


}

I am trying to pass like this

        onPressed: () async {
          
            var cart = Cart();

            cart.id = widget.product.id;
            cart.title = widget.product.title;
            cart.image = widget.product.image;
            cart.price = widget.product.normalPrice;
            cart.color = selectedColor;
            cart.sizeselect = selectedSize;
            print(cart);


            final dbHelper = DatabaseHelper.instance;

            final id = await dbHelper.insert(cart);
            // Model.createCustomer(map);

          }

Its showing this error while passing data type 'Cart' is not a subtype of type 'Map<String, dynamic>'

Can any one please tell i need to convert it to something or what ? I think i need to change the json to String or something ? i just need to insert data in database but on this error i am stuck :/

Upvotes: 0

Views: 236

Answers (2)

Harsh Bhavsar
Harsh Bhavsar

Reputation: 1671

You need to import below third parties

import 'package:path_provider/path_provider.dart';
// path_provider: ^1.6.0
import 'package:sqflite/sqflite.dart';
// sqflite: ^1.3.0

This is DatabaseHelper Class

const String databaseName = "cart.db";
const int databaseVersion = 1;

  // ------  CART Table Columns  ---------- //

  mixin CartTable {
  static final String colTitle = "title";
  static final String colImage = "image";
  static final String colPrice = "price";
  static final String colColor = "color";
  static final String colSizeSelect = "sizeselect";
}


  class DatabaseHelper {
  static Database database;

  //singleton instance
  static DatabaseHelper sharedInstance = new DatabaseHelper._internal();

  factory DatabaseHelper() {
    return sharedInstance;
  }

  DatabaseHelper._internal();

  Future<Database> get instance async {
    if (database != null) {
      return database;
    }
    database = await initDatabase();
    return database;
  }

  initDatabase() async {
    io.Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, databaseName);
    var db = await openDatabase(path,
        version: databaseVersion, onCreate: _onCreateTables);
    return db;
  }

  _onCreateTables(Database db, int version) async {
    await createCartTable(db);
  }

  Future createCartTable(Database db) async {
    await db.execute(
        "CREATE TABLE ${CartTable.tbCartDetails} ( ${CartTable.colID} INTEGER PRIMARY KEY AUTOINCREMENT, ${CartTable.colTitle} TEXT NOT NULL,"
        " ${CartTable.colImage} TEXT NOT NULL, ${CartTable.colPrice} TEXT NOT NULL, ${CartTable.colColor} TEXT NOT NULL,"
        " ${CartTable.colSizeSelect} TEXT NOT NULL )");
  }

  /// Insert Record
  Future<dynamic> insertRecord(dynamic data, String tableName) async {
    var dbClient = await instance;
    return await dbClient.insert(tableName, data.toJson(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  /// Get records
  Future<List<dynamic>> getRecords(String table,
      {List<String> columns,
      String where,
      List<dynamic> args,
      String groupBy,
      String orderBy,
      int limit,
      int offset}) async {
    var dbClient = await instance;

    return await dbClient.query(table,
        columns: columns,
        where: where,
        whereArgs: args,
        groupBy: groupBy,
        orderBy: orderBy,
        limit: limit,
        offset: offset);
  }

  /// Update records
  Future<dynamic> updateRecord(
      {@required String table,
      @required List<String> whereColumns,
      @required List<dynamic> valuesCondition,
      @required Map updateData}) async {
    var dbClient = await instance;

    String where = '';
    whereColumns.forEach((column) => where += " $column=? and");
    where = where.substring(0, where.length - 3);

    debugPrint(
        "Update => $table -> where :$where values:$valuesCondition Data:$updateData");

    return await dbClient.update(table, updateData,
        where: where, whereArgs: valuesCondition);
  }

  /// Delete records
  Future<dynamic> deleteRecord(
      {@required String table,
      List<String> whereColumns,
      List<dynamic> valuesCondition}) async {
    var dbClient = await instance;
    String where = '';
    whereColumns.forEach((column) => where += " $column=? and");
    where = where.substring(0, where.length - 3);
    return await dbClient.delete(table,
        where: where, whereArgs: valuesCondition);
  }

  Future close() async {
    var dbClient = await instance;
    dbClient.close();
  }
}

Now, If you want to insert Data into cart_details table

     var cart = Cart();

        cart.id = widget.product.id;
        cart.title = widget.product.title;
        cart.image = widget.product.image;
        cart.price = widget.product.normalPrice;
        cart.color = selectedColor;
        cart.sizeselect = selectedSize;

        // This needs only once in main.dart
        await DatabaseHelper.sharedInstance.initDatabase();

        await DatabaseHelper.sharedInstance.insertRecord(cart,CartTable.tbCartDetails);

Upvotes: 0

dm_tr
dm_tr

Reputation: 4763

Edit the line

return await db.insert(table, cart);

With

return await db.insert(table, cart.toJson());

Upvotes: 1

Related Questions