I have one data table named "visits" and its working fine. Now I am trying to create another data table name "bookings". But I can not do it. Is there any one who can help me to create the new data table? This my my DBHelper Class code:
DB Helper Class:
======================
import 'package:mrhandyman_admin/models/visit_list_model.dart';
import 'package:sqflite/sqflite.dart';
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName="visits";
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'visits.db';
_db = await openDatabase(
_path,
version: _version,
onCreate: (db, version) async {
print("Creating a new entry");
return await db.execute(
"CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"customerName STRING, customerPhone STRING,"
"moveFromAddress STRING, moveToAddress STRING,"
"visitDate STRING, visitTime STRING, remind INTEGER,"
"isCompleted INTEGER)",
);
},
);
} catch (e) {
print(e);
}
}
static Future<int> insert(VisitListModel? visitListModel) async {
print("insert function called");
return await _db?.insert(_tableName, visitListModel!.toJson())??1;
}
static Future<List<Map<String, dynamic>>> query() async {
print("query function called");
return await _db!.query(_tableName);
}
static delete(VisitListModel visitListModel) async {
return await _db!.delete(_tableName, where: 'id=?', whereArgs: [visitListModel.id]);
}
static update(int id) async{
return await _db!.rawUpdate('''
UPDATE visits
SET isCompleted = ?
WHERE id =?
''', [1, id]
);
}
}
Visit Controller
import 'package:get/get.dart';
import 'package:mrhandyman_admin/database/db_helper.dart';
import 'package:mrhandyman_admin/models/visit_list_model.dart';
class VisitListController extends GetxController{
#override
void onReady() {
super.onReady();
}
var visitList = <VisitListModel>[].obs;
Future<int> addVisit({VisitListModel? visitListModel}) async {
return await DBHelper.insert(visitListModel);
}
//get all data from table
void getVisits() async {
List<Map<String, dynamic>> visits = await DBHelper.query();
visitList.assignAll(visits.map((data) => new VisitListModel.fromJson(data)).toList());
}
void delete(VisitListModel visitListModel) async {
await DBHelper.delete(visitListModel);
getVisits();
}
void markTaskCompleted(int id) async {
await DBHelper.update(id);
getVisits();
}
}
Hello, I have one data table named "visits" and its working fine. Now I am trying to create another data table name "bookings". But I can not do it. Is there any one who can help me to create the new data table? This my my DBHelper Class code:
Related
I am getting this error:
E/SQLiteLog( 5621): (1) table note has no column named is_synced_with_cloud in "INSERT INTO note (user_id, text, is_synced_with_cloud) VALUES (?, ?, ?)"
This is my code:
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:myprogram/services/crud/crud_exceptions.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
class NotesService {
Database? _db;
List<DatabaseNote> _notes = [];
static final NotesService _shared = NotesService._sharedInstance();
NotesService._sharedInstance() {
_notesStreamController = StreamController<List<DatabaseNote>>.broadcast(
onListen: () {
_notesStreamController.sink.add(_notes);
},
);
}
factory NotesService() => _shared;
late final StreamController<List<DatabaseNote>> _notesStreamController;
Stream<List<DatabaseNote>> get allNotes => _notesStreamController.stream;
Future<DatabaseUser> getOrCreateUser({required String email}) async {
try {
final user = await getUser(email: email);
return user;
} on CouldNotFindUser {
final createdUser = await createUser(email: email);
return createdUser;
} catch (e) {
rethrow;
}
}
Future<void> _cacheNotes() async {
final allNotes = await getAllNotes();
_notes = allNotes.toList();
_notesStreamController.add(_notes);
}
Future<DatabaseNote> updateNote({
required DatabaseNote note,
required String text,
}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
// make sure note exists
await getNote(id: note.id);
// update DB
final updatesCount = await db.update(noteTable, {
textColumn: text,
isSyncedWithCloudColumn: 0,
});
if (updatesCount == 0) {
throw CouldNotUpdateNote();
} else {
final updatedNote = await getNote(id: note.id);
_notes.removeWhere((note) => note.id == updatedNote.id);
_notes.add(updatedNote);
_notesStreamController.add(_notes);
return updatedNote;
}
}
Future<Iterable<DatabaseNote>> getAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(noteTable);
return notes.map((noteRow) => DatabaseNote.fromRow(noteRow));
}
Future<DatabaseNote> getNote({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(
noteTable,
limit: 1,
where: 'id = ?',
whereArgs: [id],
);
if (notes.isEmpty) {
throw CouldNotFindNote();
} else {
final note = DatabaseNote.fromRow(notes.first);
_notes.removeWhere((note) => note.id == id);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
}
Future<int> deleteAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final numberOfDeletions = await db.delete(noteTable);
_notes = [];
_notesStreamController.add(_notes);
return numberOfDeletions;
}
Future<void> deleteNote({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
noteTable,
where: 'id = ?',
whereArgs: [id],
);
if (deletedCount == 0) {
throw CouldNotDeleteNote();
} else {
_notes.removeWhere((note) => note.id == id);
_notesStreamController.add(_notes);
}
}
Future<DatabaseNote> createNote({required DatabaseUser owner}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
// make sure owner exists in the database with the correct id
final dbUser = await getUser(email: owner.email);
if (dbUser != owner) {
throw CouldNotFindUser();
}
const text = '';
// create the note
final noteId = await db.insert(noteTable, {
userIdColumn: owner.id,
textColumn: text,
isSyncedWithCloudColumn: 1,
});
final note = DatabaseNote(
id: noteId,
userId: owner.id,
text: text,
isSyncedWithCloud: true,
);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
Future<DatabaseUser> getUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isEmpty) {
throw CouldNotFindUser();
} else {
return DatabaseUser.fromRow(results.first);
}
}
Future<DatabaseUser> createUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isNotEmpty) {
throw UserAlreadyExists();
}
final userId = await db.insert(userTable, {
emailColumn: email.toLowerCase(),
});
return DatabaseUser(
id: userId,
email: email,
);
}
Future<void> deleteUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
userTable,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (deletedCount != 1) {
throw CouldNotDeleteUser();
}
}
Database _getDatabaseOrThrow() {
final db = _db;
if (db == null) {
throw DatabaseIsNotOpen();
} else {
return db;
}
}
Future<void> close() async {
final db = _db;
if (db == null) {
throw DatabaseIsNotOpen();
} else {
await db.close();
_db = null;
}
}
Future<void> _ensureDbIsOpen() async {
try {
await open();
} on DatabaseAlreadyOpenException {
// empty
}
}
Future<void> open() async {
if (_db != null) {
throw DatabaseAlreadyOpenException();
}
try {
final docsPath = await getApplicationDocumentsDirectory();
final dbPath = join(docsPath.path, dbName);
final db = await openDatabase(dbPath);
_db = db;
// create the user table
await db.execute(createUserTable);
// create note table
await db.execute(createNoteTable);
await _cacheNotes();
} on MissingPlatformDirectoryException {
throw UnableToGetDocumentsDirectory();
}
}
}
#immutable
class DatabaseUser {
final int id;
final String email;
const DatabaseUser({
required this.id,
required this.email,
});
DatabaseUser.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
email = map[emailColumn] as String;
#override
String toString() => 'Person, ID = $id, email = $email';
#override
bool operator ==(covariant DatabaseUser other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
class DatabaseNote {
final int id;
final int userId;
final String text;
final bool isSyncedWithCloud;
DatabaseNote({
required this.id,
required this.userId,
required this.text,
required this.isSyncedWithCloud,
});
DatabaseNote.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
userId = map[userIdColumn] as int,
text = map[textColumn] as String,
isSyncedWithCloud =
(map[isSyncedWithCloudColumn] as int) == 1 ? true : false;
#override
String toString() =>
'Note, ID = $id, userId = $userId, isSyncedWithCloud = $isSyncedWithCloud, text = $text';
#override
bool operator ==(covariant DatabaseNote other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
const dbName = 'notes.db';
const noteTable = 'note';
const userTable = 'user';
const idColumn = 'id';
const emailColumn = 'email';
const userIdColumn = 'user_id';
const textColumn = 'text';
const isSyncedWithCloudColumn = 'is_synced_with_cloud';
const createUserTable = '''CREATE TABLE IF NOT EXISTS "user" (
"id" INTEGER NOT NULL,
"email" TEXT NOT NULL UNIQUE,
PRIMARY KEY("id" AUTOINCREMENT)
);''';
const createNoteTable = '''CREATE TABLE IF NOT EXISTS "note" (
"id" INTEGER NOT NULL,
"user_id" INTEGER NOT NULL,
"text" TEXT,
"is_synced_with_cloud" INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY("user_id") REFERENCES "user"("id"),
PRIMARY KEY("id" AUTOINCREMENT)
);''';
This is a notes app. When you press the plus button it takes you to the new notes view and when any text is typed into the text text space and you go back to the notes view its supposed to automatically save and appear on the notes view but noting appears
I am working on developing an app and am currently in the account creation part. I want users to tap on buttons, and the text would be added to a Firestore database that I have created.
Currently, my problem is that I am not sure how to go about setting that up. I have repositories and blocs created for other components of the account creation, but I am struggling to figure out how to create buttons that will store the text as an array in Firestore. I have attached an image of what my screen will look like, my Firestore screen, as well as the code of my database repository and the chunk of code I have thus far with creating buttons that will store the text. The code for my button does NOT work, so I was hoping that I could get some help :):
Database Repository:
class DatabaseRepository extends BaseDatabaseRepository {
final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
#override
Stream<User> getUser(String userId) {
return _firebaseFirestore
.collection('Users')
.doc(userId)
.snapshots()
.map((snap) => User.fromSnapshot(snap));
}
#override
Stream <List<User>> getUsers(
String userId
) {
return _firebaseFirestore
.collection('Users').snapshots().map((snap) {
return snap.docs.map((doc) => User.fromSnapshot(doc)).toList();
});
}
#override
Future<void> updateUserPictures(User user, String imageName) async{
String downloadURL = await StorageRepository().getDownloadURL(user, imageName);
return _firebaseFirestore
.collection('Users')
.doc(user.id)
.update({
'imageUrls': FieldValue.arrayUnion([downloadURL])});
}
#override
Future<void> UpdateUser(User user) async{
return _firebaseFirestore
.collection('Users')
.doc(user.id)
.update(user.toMap())
.then((value) =>
print('User document updated.'));
}
#override
Future<void> createUser(User user) async{
await _firebaseFirestore
.collection('Users')
.doc(user.id)
.set(user.toMap());
}
}
Button code (thus far):
Widget _button (event) => TextButton(
onPressed: () async {
DocumentReference documentReference = FirebaseFirestore.instance.collection('Users').doc();
DocumentSnapshot doc = await documentReference.get();
List Interests = doc.data('Interests');
if (Interests.contains(event == true) ) {}
},
child: Text(event,
style: GoogleFonts.montserrat()));
Hi I'm working on a flutter project
Here's my DB file
notes_service.dart
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:my_notebook/extensions/list/filter.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
import 'package:my_notebook/services/crud/crud_exceptions.dart';
class NotesService {
Database? _db;
List<DatabaseNotes> _notes = [];
DatabaseUser? _user;
static final NotesService _shared = NotesService._sharedInstance();
NotesService._sharedInstance() {
_notesStreamController = StreamController<List<DatabaseNotes>>.broadcast(
onListen: () {
_notesStreamController.sink.add(_notes);
},
);
}
factory NotesService() => _shared;
late final StreamController<List<DatabaseNotes>> _notesStreamController;
Stream<List<DatabaseNotes>> get allNotes =>
_notesStreamController.stream.filter((note) {
final currentUser = _user;
if (currentUser != null) {
return note.userId == currentUser.id;
} else {
throw UserShouldBeSetBeforeReadingAllNotesException();
}
});
Future<DatabaseUser> getOrCreateUser({
required String email,
bool setAsCurrentUser = true,
}) async {
try {
final user = await getUser(email: email);
if (setAsCurrentUser) {
_user = user;
}
return user;
} on CouldNotFindUserException {
final createdUser = await createUser(email: email);
if (setAsCurrentUser) {
_user = createdUser;
}
return createdUser;
} catch (e) {
rethrow;
}
}
Future<void> _cacheNotes() async {
final allNotes = await getAllNotes();
_notes = allNotes.toList();
_notesStreamController.add(_notes);
}
Future<DatabaseNotes> updateNote({
required DatabaseNotes note,
required String text,
}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
// make sure note exists
await getNotes(id: note.id);
// update db
final updateCount = await db.update(
notesTable,
{
textColumn: text,
isSyncedWithCloudColumn: 0,
},
where: 'id = ?',
whereArgs: [note.id],
);
if (updateCount == 0) {
throw CouldNotUpdateNoteException();
} else {
final updatedNote = await getNotes(id: note.id);
_notes.removeWhere((note) => note.id == updatedNote.id);
_notes.add(updatedNote);
_notesStreamController.add(_notes);
return updatedNote;
}
}
Future<Iterable<DatabaseNotes>> getAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(notesTable);
return notes.map((noteRow) => DatabaseNotes.fromRow(noteRow));
}
Future<DatabaseNotes> getNotes({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final notes = await db.query(
notesTable,
limit: 1,
where: 'id = ?',
whereArgs: [id],
);
if (notes.isEmpty) {
throw CouldNotFindNoteException();
} else {
final note = DatabaseNotes.fromRow(notes.first);
_notes.removeWhere((note) => note.id == id);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
}
Future<int> deleteAllNotes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final numOfDeletions = await db.delete(notesTable);
_notes = [];
_notesStreamController.add(_notes);
return numOfDeletions;
}
Future<void> deleteNote({required int id}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
notesTable,
where: 'id = ?',
whereArgs: [id],
);
if (deletedCount == 0) {
throw CouldNotDeleteNoteException();
} else {
_notes.removeWhere((note) => note.id == id);
_notesStreamController.add(_notes);
}
}
Future<DatabaseNotes> createNote({required DatabaseUser owner}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final dbUser = await getUser(email: owner.email);
// making sure owner exists in db with correct id
if (dbUser != owner) {
throw CouldNotFindUserException();
}
const text = '';
// create note
final noteId = await db.insert(
notesTable,
{
userIdColumn: owner.id,
textColumn: text,
isSyncedWithCloudColumn: 1,
},
);
final note = DatabaseNotes(
id: noteId,
userId: owner.id,
text: text,
isSyncedWithCloud: true,
);
_notes.add(note);
_notesStreamController.add(_notes);
return note;
}
Future<DatabaseUser> getUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isEmpty) {
throw CouldNotFindUserException();
} else {
return DatabaseUser.fromRow(results.first);
}
}
Future<DatabaseUser> createUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
userTable,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isNotEmpty) {
throw UserAlreadyExistsException();
}
final userId = await db.insert(
userTable,
{
emailColumn: email.toLowerCase(),
},
);
return DatabaseUser(
id: userId,
email: email,
);
}
Future<void> deleteUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final deletedCount = await db.delete(
userTable,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (deletedCount != 1) {
throw CouldNotDeleteUserException();
}
}
Database _getDatabaseOrThrow() {
final db = _db;
if (db == null) {
throw DatabaseAlreadyOpenedException();
} else {
return db;
}
}
Future<void> close() async {
final db = _db;
if (db == null) {
throw DatabaseNotOpenedException();
} else {
await db.close();
_db = null;
}
}
Future<void> _ensureDbIsOpen() async {
try {
await open();
} on DatabaseAlreadyOpenedException {}
}
Future<void> open() async {
if (_db != null) {
throw DatabaseAlreadyOpenedException();
}
try {
final docsPath = await getApplicationDocumentsDirectory();
final dbPath = join(docsPath.path, dbName);
final db = await openDatabase(dbPath);
_db = db;
// create user table
await db.execute(createUserTable);
// create note table
await db.execute(createNotesTable);
await _cacheNotes();
} on MissingPlatformDirectoryException {
throw UnableToGetDocumentDirectoryException();
}
}
}
#immutable
class DatabaseUser {
final int id;
final String email;
const DatabaseUser({
required this.id,
required this.email,
});
DatabaseUser.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
email = map[emailColumn] as String;
#override
String toString() => 'Person, ID = $id, email = $email';
#override
bool operator ==(covariant DatabaseUser other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
class DatabaseNotes {
final int id;
final int userId;
final String text;
final bool isSyncedWithCloud;
DatabaseNotes({
required this.id,
required this.userId,
required this.text,
required this.isSyncedWithCloud,
});
DatabaseNotes.fromRow(Map<String, Object?> map)
: id = map[idColumn] as int,
userId = map[userIdColumn] as int,
text = map[textColumn] as String,
isSyncedWithCloud =
(map[isSyncedWithCloudColumn] as int) == 1 ? true : false;
#override
String toString() =>
'Note, ID = $id, userId = $userId, text = $text, isSyncedWithCloud = $isSyncedWithCloud';
#override
bool operator ==(covariant DatabaseNotes other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
const dbName = 'notes.db';
const userTable = 'user';
const notesTable = 'notes';
const idColumn = 'id';
const emailColumn = 'email';
const userIdColumn = 'user_id';
const textColumn = 'text';
const isSyncedWithCloudColumn = 'is_synced_with_cloud';
const createUserTable = '''CREATE TABLE IF NOT EXISTS "user" (
"id" INTEGER NOT NULL,
"email" INTEGER NOT NULL UNIQUE,
PRIMARY KEY("id" AUTOINCREMENT)
);''';
const createNotesTable = ''' CREATE TABLE IF NOT EXISTS "notes" (
"id" INTEGER NOT NULL,
"user_id" INTEGER NOT NULL,
"text" TEXT,
"is_synced_with_cloud" INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY("user_id") REFERENCES "user"("id"),
PRIMARY KEY("id" AUTOINCREMENT)
);''';
And now I want to get the email address when user is filling the form (TextFieldController) for registering.So how can I get the email address and show it on another screen?And if I added some extra fields on register form (eg: Name, Address etc) do I need to update on above sql?I'm actually new to databases. I'm willing to have your help.
I am learning Flutter and right now testing an app to use SQLite. I wanted to use firebase in the long run, so I am building codes to store the token to the DB, but I think that I didn't quite get the process.
The LateInitializationError happens, but then it also does print the token so I guess I messed up the lifecycle?
So my question is,
why does the error happen and then print out the token?
how can I store the tokenValue data into the DB?
been 2 months and still not getting in the hang of flutter...
+Edit
This is the Error Message after putting an empty value
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Builder:
Class 'Future<dynamic>' has no instance method 'insertToken'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: insertToken(Instance of 'Token')
The relevant error-causing widget was:
MaterialApp file:///C:/Users/katej/Desktop/firem6_demo/lib/main.dart:17:5
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _MyAppState.initState (package:firem6_demo/main.dart:49:15)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4711:57)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5)
... Normal element mounting (166 frames)
...
====================================================================================================
I/flutter ( 9579): (token)
I/flutter ( 9579): []
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Builder:
Class 'Future<dynamic>' has no instance method 'insertToken'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: insertToken(Instance of 'Token')
The relevant error-causing widget was:
MaterialApp file:///C:/Users/katej/Desktop/firem6_demo/lib/main.dart:17:5
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _MyAppState.initState (package:firem6_demo/main.dart:49:15)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4711:57)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5)
... Normal element mounting (4 frames)
...
This is the main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(home: MyApp()),
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late FirebaseMessaging messaging;
late String tokenValue;
void copyToken() {
(() {
if (tokenValue != null) {
Clipboard.setData(ClipboardData(text: tokenValue));}
}());
}
#override
void initState() {
messaging = FirebaseMessaging.instance;
messaging.getToken().then((value) {
tokenValue = value!;
copyToken();
print(tokenValue);
});
tokenDb();
var user1 = Token(token: tokenValue);
tokenDb().insertToken(user1);
tokenDb().updateToken(user1);
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "DemoApp",
home: BottomBarScreen(),
routes: {
MonitoringScreen.routeName: (context) => MonitoringScreen(),
GuideScreen.routeName: (context) => GuideScreen(),
PracticeScreen.routeName: (context) => PracticeScreen(),
SettingsScreen.routeName: (context) => SettingsScreen()
},
);
}
}
And this is the db_test.dart which has tokenDb() function in it.
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
tokenDb() async {
final database = openDatabase(
join(await getDatabasesPath(), 'token_list.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE tokens (token INTEGER PRIMARY KEY)",
);
},
version: 1,
);
Future<void> insertToken(Token token) async {
final Database db = await database;
await db.insert(
'tokens',
token.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Token>> tokens() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('tokens');
return List.generate(maps.length, (i) {
return Token(
token: maps[i]['token']
);
});
}
Future<void> updateToken(Token token) async {
final db = await database;
await db.update(
'tokens',
token.toMap(),
where: "id = ?",
whereArgs: [token.token],
);
}
Future<void> deleteToken(int id) async {
final db = await database;
await db.delete(
'tokens',
where: "id = ?",
whereArgs: [id],
);
}
print(await tokens());
}
class Token {
String? token;
Token({this.token});
Map<String, dynamic> toMap() {
final map = Map<String, dynamic>();
map['token'] = token;
return map;
}
factory Token.fromMap(Map<String, dynamic> map) {
return Token(token: map['token']);
}
}
Inside the Main initState(), the tokenDb().insertToken(user1) does not work; the insertToken is not pointing to the function in the tokenDb.
thank you!
From
late String tokenValue;
To
String tokenValue = '';
Would resolve it.
I'm having trouble querying a SQFlite db table in Flutter. I get the following warning several times:
I/chatty (32047): uid=10160(com.example.SQFLite_test) 1.ui identical 18498 lines 2
I/flutter (32047): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction
object for database operations during a transaction
I get the warning when calling the getClients() method to get all clients from the Client table. The main issue though is that it seems to freeze the code as well. Even when I only try to select the top 100, it still gives me the warning and it freezes and doesn't progress.
My db class helping me to init and manage the database:
class LogServiceTwo {
LogServiceTwo._();
static final LogServiceTwo logRepo = LogServiceTwo._();
static Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
var db = await openDb();
// if (db == null) {
// _database = await initDB();
// return _database;
// }
var hasClientTableB = await hasClientTable(db);
if (hasClientTableB) {
_database = db;
return _database;
}
// var backup = await restoreBackup(db);
// if (backup != null) {
// _database = backup;
// return _database;
// }
await createClientTable(db);
_database = db;
return _database;
}
Future createClientTable(Database db) async {
await db.execute("CREATE TABLE Client ("
"id INTEGER PRIMARY KEY,"
"first_name TEXT,"
"last_name TEXT,"
"blocked BIT"
")");
}
Future<bool> hasClientTable(Database db) async {
try {
var table = await db.query("Client");
return table != null;
} catch (e) {
return false;
}
}
Future<Database> openDb() async {
try {
var path = await getPersistentDbPath();
var db = await openDatabase(path, version: 1);
return db;
} catch (e) {
return null;
}
}
Future initDB() async {
var path = await getPersistentDbPath();
return await openDatabase(path, version: 1, onOpen: (db) {}, onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE Client ("
"id INTEGER PRIMARY KEY,"
"first_name TEXT,"
"last_name TEXT,"
"blocked BIT"
")");
});
}
Future newClient(Client newClient) async {
final db = await database;
var res = await db.insert("Client", newClient.toMap());
return res;
}
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
clientMaps.forEach((clientMap) async {
await db.insert("Client", clientMap);
});
}
Future<Client> getClient(int id) async {
final db = await database;
var res = await db.query("Client", where: "id = ?", whereArgs: [id]);
return res.isNotEmpty ? Client.fromMap(res.first) : Null;
}
Future<List<Client>> getAllClients() async {
final db = await database;
var res = await db.query("Client");
List<Client> list = res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
return list;
}
Future<List<Client>> getBlockedClients() async {
final db = await logRepo.database;
var res = await db.rawQuery("SELECT * FROM Client WHERE blocked=1");
List<Client> list = res.isNotEmpty ? res.toList().map((c) => Client.fromMap(c)) : null;
return list;
}
Future<List<String>> getTables() async {
var db = await logRepo.database;
var tableNames = (await db.query('sqlite_master', where: 'type = ?', whereArgs: ['table'])).map((row) => row['name'] as String).toList(growable: false);
return tableNames;
}
Future<String> getPersistentDbPath() async {
return await createPersistentDbDirecotry();
}
Future createPersistentDbDirecotry() async {
var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory();
var persistentDirectory = "$externalDirectoryPath/db_persistent";
await createDirectory(persistentDirectory);
return "$persistentDirectory/persistent.db";
}
Future createDirectory(String path) async {
await (new Directory(path).create());
}
Future<bool> askForWritePermission() async {
var status = await Permission.storage.status;
if (!status.isGranted) {
status = await Permission.storage.request();
return status.isGranted;
}
return status.isGranted;
}
Future mockData() async {
var clients = ClientMocker.createClients();
await newClients(clients);
}
Future deleteAll() async {
var db = await database;
await db.rawDelete("DELETE FROM Client");
}
// Get all clients, throws warnings and stops proceeding in the code.
Future getClients() async {
try {
var db = await database;
return await db.rawQuery("SELECT * FROM Client");
} catch (e) {
print(e);
}
}
}
My main class calling the database service for testing purposes:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
// firstTest();
// secondTest();
thirdTest();
testText = "";
super.initState();
}
String testText;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Text(testText),
)
],
),
),
);
}
Future firstTest() async {
testText = "";
// var client = new Client(blocked: false, firstName: "Tobias", lastName: "Eliasson", id: null);
// await LogRepository.logRepo.newClient(client);
// await LogRepository.logRepo.newClient(client);
// await LogRepository.logRepo.newClient(client);
var clients = await LogRepository.logRepo.getAllClients();
clients.forEach((c) {
setState(() {
testText += "\n${c.toMap()}";
});
print(c.toMap());
});
setState(() {
testText += "Length of found clients: ${clients.length.toString()}";
});
var success = await LogRepository.logRepo.saveBackup();
print(success);
}
Future secondTest() async {
try {
await LogRepository.logRepo.deleteAll();
await LogRepository.logRepo.mockData();
var a = DateTime.now();
print("Saving backup $a");
var backupSuccess = await LogRepository.logRepo.saveBackup();
print("Backup success: $backupSuccess");
var b = DateTime.now();
print("Saved backup:${a.difference(b)}");
} catch (e) {
print("Error!!!");
print(e);
}
}
Future thirdTest() async {
await LogServiceTwo.logRepo.database;
await LogServiceTwo.logRepo.mockData();
var clients = await LogServiceTwo.logRepo.getClients();
print(clients.length);
}
}
As far as I can see, I await all db operations and only use on db object to access it so there shouldn't be any weird parallell access going on. Maybe you find an error somewhere I'm missing though. In case you wonder why I create the database in external memory, is that the database needs to be persistent and saved when uninstalling the app or updating it.
Thanks!
I found the problem and learnt a lesson. In short, follow conventions and best practices when accessing a database. The problem was that I inserted one client at the time inside the method:
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
clientMaps.forEach((clientMap) async {
await db.insert("Client", clientMap);
});
}
When inserting or doing many db operations at the same moment, use batch and commit instead like this:
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
var batch = db.batch();
clientMaps.forEach((clientMap) async {
batch.insert("Client", clientMap);
});
await batch.commit(noResult: true);
}
With the batch and commit solution I could insert 90 000 clients on first try with no errors and could query them all after.