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 :/
Edit the line
return await db.insert(table, cart);
With
return await db.insert(table, cart.toJson());
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);
Related
How to get data from api and save the data to locally database sqlite?
this is my code, but still got error in dio
can you guys help me
error dio
import 'package:bloggggg/employee_model.dart';
import 'package:bloggggg/db_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';
class EmployeeApiProvider {
Future<List<Employee?>> getAllEmployees() async {
final url = "http://demo8161595.mockable.io/employee";
Response response = await Dio().get(url);
if(response.statusCode == 200){
return (response.data as List).map((employee) {
print('Inserting $employee');
DBProvider.db.createEmployee(Employee.fromJson(employee));
}).toList();
}else{
return response.data;
}
}
}
Save Api Data Function
save() async {
final dbHelper = DatabaseHelper.instance;
const url = "http://demo8161595.mockable.io/employee";
final result = await get(Uri.parse(url));
final response = jsonDecode(result.body);
Map<String, dynamic> row = DatabaseInsetItemModel(
name: response["name"] ?? "",
lName: response["lName"] ?? "",
mobile: response["mobile"] ?? "",
email: response["email"] ?? "",
cat: response["cat"] ?? "",
profile: response["profile"] ?? "")
.toJson();
print('insert stRT');
final id = await dbHelper.insertContact(row);
if (kDebugMode) {
print('inserted row id: $id');
}
}
DataBase Helper
class DatabaseHelper {
static final _databaseName = "MyDatabase.db";
static final _databaseVersion = 1;
static final table = 'category';
static final tableContact = 'contact';
static final columnId = '_id';
static final columnName = 'name';
static final columnLName = 'lname';
static final columnMobile = 'mobile';
static final columnEmail = 'email';
static final columnCategory = 'cat';
static final columnProfile = 'profile';
// 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 => _database ??= await _initDatabase();
Future<Database?> get database1 async {
if (_database == null) {
_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 (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT NOT NULL
)
''');
await db.execute('''
CREATE TABLE $tableContact (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT NOT NULL,
$columnLName TEXT NOT NULL,
$columnMobile TEXT NOT NULL,
$columnEmail TEXT NOT NULL,
$columnCategory TEXT NOT NULL,
$columnProfile TEXT NOT NULL
)
''');
}
// Helper methods
// Inserts a row in the database where each key in the Map is a column name
// and the value is the column value. The return value is the id of the
// inserted row.
Future<int> insert(Map<String, dynamic> row) async {
Database? db = await instance.database;
return await db.insert(table, row);
}
Future<int> insertContact(Map<String, dynamic> row) async {
Database? db = await instance.database;
return await db.insert(tableContact, row);
}
// All of the rows are returned as a list of maps, where each map is
// a key-value list of columns.
Future<List<Map<String, dynamic>>> queryAllRows() async {
Database db = await instance.database;
return await db.query(table);
}
Future<List<Map<String, dynamic>>> queryAllRowsofContact() async {
Database db = await instance.database;
return await db.query(tableContact);
}
// All of the methods (insert, query, update, delete) can also be done using
// raw SQL commands. This method uses a raw query to give the row count.
Future<int> queryRowCount() async {
Database db = await instance.database;
return Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM $table')) ??
0;
}
// We are assuming here that the id column in the map is set. The other
// column values will be used to update the row.
Future<int> update(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row[columnId];
return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
}
// Deletes the row specified by the id. The number of affected rows is
// returned. This should be 1 as long as the row exists.
Future<int> delete(int id) async {
Database db = await instance.database;
return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
}
Future<int> deleteContact(int id) async {
Database db = await instance.database;
return await db.delete(tableContact, where: '$columnId = ?', whereArgs: [id]);
}
}
DataBase Item Model
class DatabaseInsetItemModel{
String? name;
String? lName;
String? mobile;
String? email;
String? cat;
String? profile;
DatabaseInsetItemModel(
{required this.name, required this.lName, required this.mobile, required this.email, required this.cat, required this.profile});
DatabaseInsetItemModel.fromJson(Map<String, dynamic> json) {
name = json['postId'];
lName = json['id'];
mobile = json['name'];
email = json['email'];
cat = json['body'];
profile = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data[DatabaseHelper.columnName] = name;
data[DatabaseHelper.columnLName] = lName;
data[DatabaseHelper.columnMobile] = mobile;
data[DatabaseHelper.columnEmail] = email;
data[DatabaseHelper.columnCategory] = cat;
return data;
}
}
Show Data on screen
class ShowPostScreen extends StatefulWidget {
ShowPostScreen({Key? key}) : super(key: key);
#override
State<ShowPostScreen> createState() => _ShowPostScreenState();
}
class _ShowPostScreenState extends State<ShowPostScreen> {
final dbHelper = DatabaseHelper.instance;
List<DatabaseInsetItemModel> data = [];
#override
void initState() {
// TODO: implement initState
dbHelper.queryAllRows().then((value) {
setState(() {
data = value.map((e) => DatabaseInsetItemModel.fromJson(e)).toList();
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Text(data[index].name ?? "");
},
),
);
}
}
// THis is model>>
class CompanyProfile {
// to create name tag for database
static const String columnId = '_id';
static const String comapnyNametag = 'CompanyName';
static const String phoneNumbertag = 'PhoneNumber';
static const String addressLine1tag = 'AddressLine1';
static const String addressLine2tag = 'AddressLine2';
static const String emailaddresstag = 'EmailAddress';
static const String invPrefixtag = 'InvoicePrefix';
static const String footerTexttag = 'FooterText';
// to create new Profile or Update profile
int? id;
String? companyName;
String? addressLine1;
String? addressLine2;
String? emailAddress;
String? phoneNumber;
String? invPrefix;
String? footerText;
CompanyProfile({
this.id,
this.companyName,
this.addressLine1,
this.addressLine2,
this.emailAddress,
this.phoneNumber,
this.invPrefix,
this.footerText,
});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
comapnyNametag: companyName,
phoneNumbertag: phoneNumber,
addressLine1tag: addressLine1,
addressLine2tag: addressLine2,
emailaddresstag: emailAddress,
invPrefixtag: invPrefix,
footerTexttag: footerText,
};
if (id != null) {
map[columnId] = id;
}
return map;
}
CompanyProfile.fromMap(Map<String, dynamic> map) {
id = map[columnId];
companyName = map[comapnyNametag];
phoneNumber = map[phoneNumbertag];
addressLine1 = map[addressLine1tag];
addressLine2 = map[addressLine2tag];
emailAddress = map[emailaddresstag];
invPrefix = map[invPrefixtag];
footerText = map[footerTexttag];
}
}
//this is databasae helper to create database
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../models/company_profile.dart';
class ProfileProvider {
static const _dbName = 'profile.db';
static const _dbVersion = 1;
static Database? _db;
String tableName = 'profile';
String columnId = '_id';
String comapnyNametag = 'CompanyName';
String phoneNumbertag = 'PhoneNumber';
String addressLine1tag = 'AddressLine1';
String addressLine2tag = 'AddressLine2';
String emailaddresstag = 'EmailAddress';
String invPrefixtag = 'InvoicePrefix';
String footerTexttag = 'FooterText';
ProfileProvider._privateConstructor();
static final ProfileProvider instance = ProfileProvider._privateConstructor();
Future<Database?> get database async {
if (_db != null) return _db;
_db = await _createDB();
return _db;
}
_createDB() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = join(dir.path, _dbName);
return await openDatabase(
path,
version: _dbVersion,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
create table $tableName (
$columnId integer primary key autoincrement,
$comapnyNametag text not null,
$phoneNumbertag text not null,
$addressLine1tag text not null,
$addressLine2tag text not null,
$emailaddresstag text not null,
$invPrefixtag text not null,
$footerTexttag text not null
)
''');
}
Future<CompanyProfile> insert(CompanyProfile profile) async {
final db = await database;
profile.id = await db!.insert(tableName, profile.toMap());
return profile;
}
// Future<CompanyProfile> getProfile(int id) async {
// final db = await database;
// final maps = await db.query(
// tableName,
// columns:
// )
// }
// Future<int> insert(Map<String, dynamic> row) async {
// final db = await database;
// return await db!.insert(tableName, row);
// }
Future<List<Map<String, dynamic>>> queryAllRows() async {
final db = await database;
return await db!.query(tableName);
}
// Future<List<CompanyProfile>> profiledetails() async {
// final db = await database;
// final List<Map<String, dynamic>> maps =
// db!.query(tableName) as List<Map<String, dynamic>>;
// return List.generate(maps.length, (i) {
// return CompanyProfile(
// id: maps[i][columnId],
// companyName: maps[i][comapnyNametag],
// phoneNumber: maps[i][phoneNumbertag],
// addressLine1: maps[i][addressLine1tag],
// addressLine2: maps[i][addressLine2tag],
// emailAddress: maps[i][emailaddresstag],
// invPrefix: maps[i][invPrefixtag],
// footerText: maps[i][footerTexttag],
// );
// });
// }
Future<Iterable<CompanyProfile>> getProfile() async {
final db = await database;
final List<Map<String, Object?>> queryResult = await db!.query(tableName);
return queryResult.map((e) => CompanyProfile.fromMap(e));
}
Future<int> update(Map<String, dynamic> row) async {
final db = await database;
int id = row[columnId];
return await db!
.update(tableName, row, where: '$columnId = ?', whereArgs: [id]);
}
Future<int> delete(int id) async {
final db = await database;
return await db!.delete(tableName, where: '$columnId = ?', whereArgs: [id]);
}
}
// this is database helper
Using this model I was able to save data in the database.
//From debug Console.
{_id: 1, CompanyName: a, PhoneNumber: a, AddressLine1: a, AddressLine2: a, EmailAddress: a, InvoicePrefix: a, FooterText: a}
Now I Want to get the values and show in a profile screen like this:
Company Name: a
Address: addressline1 and address line 2
Phone: a
Email: a
Invoice Prefix: a
Footer Text: a
Later I will make a pdf file using this data as well.
Therefore, I need to get the values individually.
Anybody can help me about this?
I am searching in google and youtube but nothing works. some methods doesn't work becasue very old, and most of the methods shows how to create a list graving values from database. I don't want to create any list. I will have only one data in the whole database and i want use this everywhere in the app.
Lots of talking :p
here you just get one record back as your data model
Future<CompanyProfile> getProfile(int id) async {
final db = await database;
final maps = await db.query(tableName, where: '_id = ?', whereArgs: [id]);
return CompanyProfile.fromMap(maps[0]);
}
I have an error on the flutter run. Probably, some problem is on
//podesavanje singltona 2/3
DbHelper()._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
in dbhelper.dart file. Any idea how to solve that?
dbhelper.dart
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:todo_app/model/todo.dart';
class DbHelper {
//podesavanje singltona 1/3
static final DbHelper _dbHelper = DbHelper()._internal();
//table name
String tblName = "todo";
//columns
String colId = "id";
String colTitle = "title";
String colDescription = "description";
String colPriority = "priority";
String colDate = "date";
//podesavanje singltona 2/3
DbHelper()._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
static Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
//za ovo koristimo 'dart:io';
Future<Database> initializeDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + "todos.db";
var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
return dbTodos;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)"
);
}
Future<int> insertTodo(Todo todo) async{
Database db = await this.db;
var result = await db.insert(tblName, todo.toMap());
return result;
}
Future<List> getTodos() async {
Database db = await this.db;
var result = await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
return result;
}
Future<int> getCount() async {
Database db = await this.db;
var result = Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT(*) FROM $tblName")
);
return result;
}
Future<int> updateTodo(Todo todo) async{
Database db = await this.db;
var result = await db.update(tblName, todo.toMap(), where: "$colId = ?", whereArgs: [todo.id]);
return result;
}
Future<int> deleteTodo(int id) async{
Database db = await this.db;
var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId = $id");
return result;
}
}
todo.dart
import 'package:flutter/scheduler.dart';
class Todo {
//_ se stavlja zato da budu privatni
int _id;
String _title;
String _description;
String _date;
int _priority;
//postavljanje konstruktora, ne moze isti vise puta, opcioni ide u []
Todo(this._title, this._priority, this._date, [this._description]);
Todo.withId(this._id, this._title, this._priority, this._date,
[this._description]);
//geteri
int get id => _id;
String get title => _title;
String get description => _description;
String get date => _date;
int get priority => _priority;
//seteri
set title(String newTitle) {
if (newTitle.length < 255) {
_title = newTitle;
}
}
set description(String newDescription) {
if (newDescription.length < 255) {
_description = newDescription;
}
}
set priority(int newPriority) {
if (newPriority > 0 && newPriority <= 3) {
_priority = newPriority;
}
}
set date(String newDate) {
_date = newDate;
}
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
map["title"] = _title;
map["description"] = _description;
map["priority"] = _priority;
map["date"] = _date;
if (_id != null) {
map["id"] = _id;
}
return map;
}
Todo.fromObject(dynamic o) {
this._id = o["id"];
this._title = o["title"];
this._description = o["description"];
this._date = o["date"];
this._priority = o["priority"];
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:todo_app/util/dbhelper.dart';
import 'package:todo_app/model/todo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
List<Todo> todos = List<Todo>();
DbHelper helper = DbHelper();
helper
.initializeDb()
.then((result) => helper.getTodos().then((result) => todos = result));
DateTime today = DateTime.now();
Todo todo = Todo("naslov", 1, today.toString(), "opcioni diskripsn");
helper.insertTodo(todo);
}
}
flutter run
Launching lib/main.dart on iPhone 8 Plus in debug mode...
Running Xcode build...
Xcode build done. 10.4s
Failed to build iOS app
Error output from Xcode build:
↳
** BUILD FAILED **
Xcode's output:
↳
lib/util/dbhelper.dart:19:13: Error: Expected '{' before this.
DbHelper()._internal();
^
lib/util/dbhelper.dart:19:13: Error: Expected a class member, but got '.'.
DbHelper()._internal();
^
lib/util/dbhelper.dart:21:11: Error: 'DbHelper' is already declared in this scope.
factory DbHelper() {
^^^^^^^^
lib/util/dbhelper.dart:19:3: Context: Previous declaration of 'DbHelper'.
DbHelper()._internal();
^^^^^^^^
lib/util/dbhelper.dart:7:7: Error: The non-abstract class 'DbHelper' is missing implementations for these members:
- DbHelper._internal
Try to either
- provide an implementation,
- inherit an implementation from a superclass or mixin,
- mark the class as abstract, or
- provide a 'noSuchMethod' implementation.
class DbHelper {
^^^^^^^^
lib/util/dbhelper.dart:19:14: Context: 'DbHelper._internal' is defined here.
DbHelper()._internal();
^^^^^^^^^
lib/main.dart:14:23: Error: Can't use 'DbHelper' because it is declared more than once.
DbHelper helper = DbHelper();
^
lib/util/dbhelper.dart:9:37: Error: Can't use 'DbHelper' because it is declared more than once.
static final DbHelper _dbHelper = DbHelper()._internal();
^
Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build systemnote: Planning buildnote: Constructing build description
This is what you are trying to do
class DbHelper {
//podesavanje singltona 1/3
static final DbHelper _dbHelper = DbHelper._internal();
//table name
String tblName = "todo";
//columns
String colId = "id";
String colTitle = "title";
String colDescription = "description";
String colPriority = "priority";
String colDate = "date";
//podesavanje singltona 2/3
DbHelper._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
static Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
//za ovo koristimo 'dart:io';
Future<Database> initializeDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + "todos.db";
var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
return dbTodos;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)");
}
Future<int> insertTodo(Todo todo) async {
Database db = await this.db;
var result = await db.insert(tblName, todo.toMap());
return result;
}
Future<List> getTodos() async {
Database db = await this.db;
var result =
await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
return result;
}
Future<int> getCount() async {
Database db = await this.db;
var result = Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT(*) FROM $tblName"));
return result;
}
Future<int> updateTodo(Todo todo) async {
Database db = await this.db;
var result = await db.update(tblName, todo.toMap(),
where: "$colId = ?", whereArgs: [todo.id]);
return result;
}
Future<int> deleteTodo(int id) async {
Database db = await this.db;
var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId = $id");
return result;
}
}
Remove () from DbHelper()._internal()
DbHelper()._internal(); => DbHelper._internal();
Good day everyone,
I am developing an App usaing Flutter.
To save some data localy I am using the SQFlite plugin.
I have a database helper class.
I am using Provider to call my database methods.
When I call the method to write an account in the database I receive an autoincremented ID as response the the sucess of the insertion of the account.
The problem is when I call the method to read these accounts from the database I receiceive nothing. The response Map is null like I have nothing in the database.
If when I insert an account to my database I receive an ID as response, why when I try to read these account I receive nothing.
Please help, me. I am going insane with this code.
class DBProvider {
static const String TABLE_ACCOUNTS = 'Accounts';
static const String COLUMN_ID = 'accountID';
static const String COLUMN_LOCAL_ID = 'id';
static const String COLUMN_CUSTOMER_PICTURE = 'customerPictureBase64';
static const String COLUMN_DOC_FRONT = 'docFrontPictureBase64';
static const String COLUMN_DOC_BACK = 'docBackPictureBase64';
static const String COLUMN_SIGNATURE = 'signatureBase64';
static const String COLUMN_GENDER = 'gender';
static const String COLUMN_FIRST_NAME = 'firstName';
static const String COLUMN_LAST_NAME = 'lastName';
static const String COLUMN_DOC_TYPE = 'docType';
DBProvider._();
static final DBProvider db = DBProvider._();
Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
_database = await createDatabase();
return _database;
}
Future<Database> createDatabase() async {
String dbPath = await getDatabasesPath();
return await openDatabase(
join(dbPath, 'paperless.db'),
version: 1,
onCreate: (Database database, int version) async {
await database.execute(
'CREATE TABLE $TABLE_ACCOUNTS ($COLUMN_LOCAL_ID INTEGER PRIMARY KEY, $COLUMN_ID TEXT, '
'$COLUMN_CUSTOMER_PICTURE TEXT, $COLUMN_DOC_FRONT TEXT, '
'$COLUMN_DOC_BACK TEXT, $COLUMN_SIGNATURE TEXT, '
'$COLUMN_GENDER INTEGER, $COLUMN_FIRST_NAME TEXT, '
'$COLUMN_LAST_NAME TEXT, $COLUMN_DOC_TYPE TEXT)',
);
},
);
}
Future<List<LowKYCAccount>> getLocalLowKYCAccount() async {
final db = await database;
var accounts = await db.rawQuery('SELECT * FROM $TABLE_ACCOUNTS');
var accountsList = List<LowKYCAccount>();
accounts.forEach((account) {
LowKYCAccount kycAccount = LowKYCAccount.fromMap(account);
accountsList.add(kycAccount);
});
return accountsList;
}
Future<LowKYCAccount> saveAccountLocaly(LowKYCAccount account) async {
final db = await database;
account.localId = await db.insert(TABLE_ACCOUNTS, account.toMap());
return account;
}
}
I am calling this methods from my UI sing provider
class LowKYCProvider with ChangeNotifier {
LowKYCAccount _selectedAccount;
List<LowKYCAccount> _lowKycAccounts = [];
List<LowKYCAccount> _localLowKycAccounts = [];
LowKYCAccount get selectedAccount {
return _selectedAccount;
}
List<LowKYCAccount> get lowKycAccounts {
return [..._lowKycAccounts];
}
List<LowKYCAccount> get localLowKycAccounts {
return [..._localLowKycAccounts];
}
Future<void> submitNewAccount(LowKYCAccount account) async {}
Future<void> fetchLowKycAccounts() async {
if (_lowKycAccounts.isEmpty) {
notifyListeners();
}
}
Future<void> fetchLocalLowKycAccounts() async {
print('vamos fetchar os locais');
await DBProvider.db.getLocalLowKYCAccount().then((accounts) {
_localLowKycAccounts = accounts;
//notifyListeners();
});
print('Já terminamos');
}
Future<void> saveAccountLocaly(LowKYCAccount account) async {
await DBProvider.db
.saveAccountLocaly(account)
.then((account) => _localLowKycAccounts.add(account));
notifyListeners();
}
Future<void> updateLowKycAccount(LowKYCAccount account) async {}
Future<void> setSelectedAccount(int index) async {
_selectedAccount = _lowKycAccounts[index];
notifyListeners();
}
}
this is the model class
class LowKYCAccount {
String id;
int localId;
String customerPictureBase64;
String docFrontPictureBase64;
String docBackPictureBase64;
int gender;
String firstName;
String lastName;
String docType;
File signatureFile;
String signatureUrl;
LowKYCAccount({
this.id,
this.localId,
this.customerPictureBase64,
this.docFrontPictureBase64,
this.docBackPictureBase64,
this.gender,
this.firstName,
this.lastName,
this.docType,
this.signatureUrl,
this.signatureFile,
});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
DBProvider.COLUMN_ID: id,
DBProvider.COLUMN_CUSTOMER_PICTURE: customerPictureBase64,
DBProvider.COLUMN_DOC_FRONT: docFrontPictureBase64,
DBProvider.COLUMN_DOC_BACK: docBackPictureBase64,
DBProvider.COLUMN_GENDER: gender,
DBProvider.COLUMN_FIRST_NAME: firstName,
DBProvider.COLUMN_LAST_NAME: lastName,
DBProvider.COLUMN_DOC_TYPE: docType,
};
if (localId != null) {
map[DBProvider.COLUMN_LOCAL_ID] = localId;
}
return map;
}
LowKYCAccount.fromMap(Map<String, dynamic> account) {
id = account[DBProvider.COLUMN_ID];
localId = account[DBProvider.COLUMN_LOCAL_ID];
customerPictureBase64 = account[DBProvider.COLUMN_CUSTOMER_PICTURE];
docFrontPictureBase64 = account[DBProvider.COLUMN_DOC_FRONT];
docBackPictureBase64 = account[DBProvider.COLUMN_DOC_BACK];
gender = account[DBProvider.COLUMN_GENDER];
firstName = account[DBProvider.COLUMN_FIRST_NAME];
lastName = account[DBProvider.COLUMN_LAST_NAME];
docType = account[DBProvider.COLUMN_DOC_TYPE];
}
}
No experience with this type of plugin or this database, but you should probably use transactions! Otherwise your data will probably not be committed:
await database.transaction((txn) async {
var batch = txn.batch();
// ... insert your data here!
// commit but the actual commit will happen when the transaction is committed
// however the data is available in this transaction
await batch.commit();
// ...
});
and the insert example:
// Insert some records in a transaction
await database.transaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
print('inserted1: $id1');
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
print('inserted2: $id2');
});
See https://pub.dev/packages/sqflite for more info on transactions
That's my data stored in database
[{count: 3, minced: 0, category_id: 3, size_id: 63, chops_id: null, cookie_id: null, choole: null, notes: }, {count: 4, minced: 0, category_id: 3, size_id: 62, chops_id: null, cookie_id: null, choole: null, notes: }, {count: 2, minced: 2, category_id: 2, size_id: 49, chops_id: 8, cookie_id: 8, choole: 2, notes: bzbznzjz}]
and that what I need to send to API
[{"size_id":59,"count":2 ,"category_id" :2,"chops_id":null,"cookie_id":null,"choole":null,"notes":"jgg ","minced": 0},{"size_id":63,"count":3 ,"category_id" :2,"chops_id":4,"cookie_id":8,"choole":2,"notes":"tvv","minced": 1}]
I need to add this "" to my keys how can I do this?
and that's my code
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'Models/product.dart';
class DatabaseHelper {
Product _product;
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
await db.execute(
"CREATE TABLE Product(id INTEGER PRIMARY KEY, count INTEGER, minced INTEGER, rate DOUBLE, category_id INTEGER, size_id INTEGER, chops_id INTEGER, cookie_id INTEGER, choole INTEGER, notes TEXT, name TEXT, image TEXT, size_name TEXT, category_name TEXT)"); }
Future<int> saveProduct(Product product) async {
var dbProduct = await db;
int res = await dbProduct.insert("Product", product.toMap());
print(product.toMap());
return res;
}
Future<List> getAllProduct() async {
var dbProduct = await db;
var result = await dbProduct.rawQuery("SELECT * FROM Product");
return result.toList();
}
Future<List> getCartProduct() async {
var dbProduct = await db;
var result = await dbProduct.rawQuery("SELECT count, minced, category_id, size_id, chops_id, cookie_id, choole, notes FROM Product");
return result;
}
Future<int> getCount() async {
var dbProduct = await db;
return Sqflite.firstIntValue(
await dbProduct.rawQuery("SELECT COUNT(*) FROM Product"));
}
Future<Product> getProduct(int id) async {
var dbProduct = await db;
var result = await dbProduct.rawQuery("SELECT * FROM Product WHERE id = $id");
if (result.length == 0) return null;
return new Product.fromMap(result.first);
}
Future<int> deleteProducts(Product product) async {
var dbProduct = await db;
int res = await dbProduct
.rawDelete('DELETE FROM Product WHERE id = ?', [product.id]);
return res;
}
update(Product product) async {
var dbProduct = await db;
int res = await dbProduct.update("Product", product.toMap(),
where: "id = ?", whereArgs: <int>[product.id]);
return res > 0 ? true : false;
}
}
Brother as per my Knowledge the Data Stored in DB is not in Json String so First of all what you need to do is
Save the Data in Correct format use Model class to Save data as String by using "jsonEncode(Your Products List)"
Consider User as Model class
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};
}
whenever you save data to DB you should use
String json = jsonEncode(user);
String json = jsonEncode(List<user>);
by this you will get the " in your DB.
to retrive the Data back in to json just pass the Stored String here
List<Users> MyList = (StringFromDB as List)
.map((data) => User.fromJson(data))
.toList();
this will solve your Problem
Just add a toMap method in your data classes. For example:
class DataClass {
int id;
String message;
Map<String, dynamic> toMap() {
return {
'id': id,
'message': message
}
}
}
By API, I guess you mean a Web API. If it is expecting json (if that is what you mean by ""), you should jsonEncode your data (list or map)
From what I see you just need to make json out of your object. Add toJson in your Product class then just call it.
int res = await dbProduct.insert("Product", product.toMap());
So like this:
int res = await dbProduct.insert("Product", product.toJson());
This is the serialization doc is always helpful in such a case.