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();
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 ?? "");
},
),
);
}
}
I'm getting empty string when I trying to get the titles. Please help me.
Here's my source code
Here's my task.dart file
// task.dart
class Task {
int? id;
String? title;
String? note;
int? isCompleted;
String? date;
String? startTime;
String? endTime;
int? color;
int? remind;
String? repeat;
Task({
this.id,
this.title,
this.note,
this.isCompleted,
this.date,
this.startTime,
this.endTime,
this.color,
this.remind,
this.repeat,
});
Task.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
note = json['note'];
isCompleted = json['isCompleted'];
date = json['date'];
startTime = json['startTime'];
endTime = json['endTime'];
color = json['color'];
remind = json['remind'];
repeat = json['repeat'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic> ();
data['id'] = this.id;
data['title'] = this.title;
data['note'] = this.note;
data['isCompleted'] = this.isCompleted;
data['date'] = this.date;
data['startTime'] = this.startTime;
data['endTime'] = this.endTime;
data['color'] = this.color;
data['remind'] = this.remind;
data['repeat'] = this.repeat;
return data;
}
}
Here's my task_controller.dart file
import 'package:calendar_app/db/db_helper.dart';
import 'package:calendar_app/models/task.dart';
import 'package:get/get.dart';
// task_controller.dart
class TaskController extends GetxController {
#override
void onReady() {
getTasks();
super.onReady();
}
var taskList = <Task>[].obs;
Future<int> addTask({Task? task}) async{
return await DBHelper.insert(task);
}
void getTasks() async {
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
}
db_helper.dart
import 'package:calendar_app/models/task.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'dart:developer' as devtools show log;
// db_helper.dart
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName = 'Tasks';
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'tasks.db';
_db = await openDatabase(
_path,
version: _version,
onCreate: (db, version) {
devtools.log('Creating a new one');
return db.execute(
"CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title STRING, note TEXT, date STRING, "
"startTime STRING, endTime STRING, "
"remind INTEGER, repeat STRING, "
"color INTEGER, "
"isCompleted INTEGER)",
);
},
);
} catch (e) {
devtools.log(e.toString());
}
}
static Future<int> insert(Task? task) async {
devtools.log('Insert func called');
return await _db?.insert(_tableName, task!.toJson()) ?? 1;
}
static Future<List<Map<String, dynamic>>> query() async {
devtools.log('Query func called');
return await _db!.query(_tableName);
}
}
When I trying to get a print statement of title it return empty. I have no idea what's happening here. Please help me.
print(_taskController.taskList[index].note.toString());
I'm following dbstech tutorial. If anyone have the source code please let me know.
First in getTask function try to reset taskList by calling this:
void getTasks() async {
taskList = []; // <--- add this
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
Then I think you issue is your table is empty. After run your code try add something to your table then print it and see the result.
I am trying to store the image in SQFLite database as string. While setting up the DBHelper class, I am getting the said error.
Here is the code of model.dart and dbhelper.dart
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<String, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'model.dart';
import 'dart:io' as io;
import 'dart:async';
class DBHelper {
static Database? _db;
static const String ID = 'id';
static const String NAME = 'photoName';
static const String TABLE = 'PhotosTable';
static const String DB_NAME = 'photos.db';
Future<Database?> get db async {
if (null != _db) {
return _db;
}
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, DB_NAME);
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
_onCreate(Database db, int version) async {
await db.execute("CREATE TABLE $TABLE ($ID INTEGER, $NAME TEXT)");
}
Future<Photo> save(Photo photo) async {
var dbClient = await db;
photo.id = await dbClient!.insert(TABLE, photo.toMap());
return photo;
}
Future<List<Photo>> getPhotos() async {
var dbClient = await db;
List<Map> maps = await dbClient!.query(TABLE, columns: [ID, NAME]);
List<Photo> photos = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
photos.add(Photo.fromMap(maps[i])); // ==> Here, at maps[i], it shows the error
}
}
return photos;
}
Future close() async {
var dbClient = await db;
dbClient!.close();
}
}
How can I solve this ?
Change your Photo model to Map<dynamic, dynamic>. The reason for this is that the db is returning a Map<dynamic, dynamic>.
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<dynamic, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<dynamic, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}
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);
the user id is null, the column is primary key and it should not be possible to have it be null
I'm learning Flutter and SQFlite, I'm following the example in the course on Udemey, and I'm typing it to the letter, but it's working for the instructor and it's not working for me
I simplified everything, now it's one file, still, ID is null
main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
void main() async {
// debugPrint("Hello World");
var db = dbhelp();
User user1 = User("User1");
int insertResult = await db.saveUser(user1);
debugPrint("insert result is " + insertResult.toString());
User searchResult = await db.retrieveUser(insertResult);
debugPrint(searchResult.toString());
}
class dbhelp {
static final dbhelp _instance = dbhelp.internal();
dbhelp.internal();
factory dbhelp() => _instance;
static Database _db;
void _onCreate(Database _db, int newVersion) async {
await _db.execute(
"CREATE TABLE MYTABLE(ID INTEGER PRIMARY KEY, userName TEXT NOT NULL)");
}
Future<Database> initDB() async {
Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, "appdb.db");
Database newDB = await openDatabase(path, version: 1, onCreate: _onCreate);
return newDB;
}
Future<Database> get db async {
if (_db != null) {
return _db;
} else {
_db = await initDB();
return _db;
}
}
Future<int> saveUser(User user) async {
var dbClient = await db;
int result;
var userMap = user.toMap();
result = await dbClient.insert("MYTABLE", userMap);
return result;
}
Future<User> retrieveUser(int id) async {
var dbClient = await db;
if (id == null) {
print("The ID is null, cannot find user with Id null");
var nullResult =
await dbClient.rawQuery("SELECT * FROM MYTABLE WHERE ID is null");
return User.fromMap(nullResult.first);
}
String sql = "SELECT * FROM MYTABLE WHERE ID = $id";
var result = await dbClient.rawQuery(sql);
if (result.length != 0) {
return User.fromMap(result.first);
} else {
return null;
}
}
}
class User {
String _userName;
int _id;
String get userName => _userName;
int get id => _id;
User(this._userName, [this._id]);
User.map(dynamic obj) {
this._userName = obj['userName'];
this._id = obj['id'];
}
User.fromMap(Map<String, dynamic> map) {
this._userName = map["userName"];
if (map["id"] != null) {
this._id = map["id"];
} else {
print("in fromMap, Id is null");
}
}
Map<String, dynamic> toMap() {
Map map = Map<String, dynamic>();
map["userName"] = this._userName;
if (_id != null) {
map["id"] = _id;
} else {
print("in toMap, id is null");
}
return map;
}
#override
String toString() {
return "ID is ${this._id} , Username is ${this._userName} }";
}
}
when i print the id it should print a number not null
but it is always null
I was puzzled for a while. A simple print after your select shows the issue:
String sql = "SELECT * FROM MYTABLE WHERE ID = $id";
var result = await dbClient.rawQuery(sql);
print(result);
output:
[{ID: 1, userName: User1}]
Column names are case sensitive.You use sometimes id (in toMap/fromMap) and sometimes ID (in your create table). Make sure to always use the same name everywhere.