I am a completely a beginner to sqlite and flutter. I was trying to create a local database to my flutter to do app. So I watched some youtube videos and started to implementing a database using flutter sqflite plugin. Everything worked fine because all I did was copy typing the you tubers code, until I had to add an extra parameter to the code which is a boolean, in order to track the status of the task (like done the task or not). I used an int value to save the bool, while sqlite does not supports boolean values. I used two functions, one to update the text and the other to update the switch value.
And secondly when I tap on a switch it triggers all the switches in the list. I want to solve that issue as well.
Model class for the Task
class Tasksdb {
final int? id;
final String taskName;
bool isDone;
Tasksdb({
this.id,
required this.taskName,
required this.isDone,
});
factory Tasksdb.fromMap(Map<String, dynamic> json) => Tasksdb(
id: json['id'],
taskName: json['taskName'],
isDone: (json['isDone'] as int) == 0 ? false : true);
Map<String, dynamic> toMap() {
return {
'id': id,
'taskName': taskName,
'isDone': isDone,
};
}
}
DatabaseHelper class
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'tasks.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS "taskstable" (
"id" INTEGER,
"taskName" TEXT,
"isDone" INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY("id" AUTOINCREMENT)
);
''');
}
Future<List<Tasksdb>> getTasks() async {
Database db = await instance.database;
var tasksQuery = await db.query(
'taskstable',
);
List<Tasksdb> taskList = tasksQuery.isNotEmpty
? tasksQuery.map((c) => Tasksdb.fromMap(c)).toList()
: [];
return taskList;
}
Future<int> add(Tasksdb task) async {
Database db = await instance.database;
return await db.insert('taskstable', {
'id': task.id,
'taskName': task.taskName,
'isDone': 0,
});
}
Future<int> update(Tasksdb task) async {
Database db = await instance.database;
return await db.update(
'taskstable',
task.toMap(),
where: "id = ?",
whereArgs: [task.id],
);
}
Future<int> updateIsDone(bool isDoneTodb) async {
Database db = await instance.database;
return await db.update(
'taskstable',
{
'isDone': isDoneTodb == true ? 1 : 0,
},
);
}
}
HomeScreen widget
class SqliteApp extends StatefulWidget {
const SqliteApp({Key? key}) : super(key: key);
#override
_SqliteAppState createState() => _SqliteAppState();
}
class _SqliteAppState extends State<SqliteApp> {
int? selectedId;
final textController = TextEditingController();
bool isDone = false;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: TextField(
controller: textController,
),
),
body: Center(
child: FutureBuilder<List<Tasksdb>>(
future: DatabaseHelper.instance.getTasks(),
builder: (BuildContext context,
AsyncSnapshot<List<Tasksdb>> snapshot) {
if (!snapshot.hasData) {
return const Center(child: Text('Loading...'));
}
return snapshot.data!.isEmpty
? const Center(child: Text('No tasks in List.'))
: ListView(
children: snapshot.data!.map((task) {
return Center(
child: Card(
color: selectedId == task.id
? Colors.green
: Colors.yellow,
child: ListTile(
trailing: Switch( //the problem is here, doesn't save to db
value: isDone,
onChanged: (val) async {
setState(() {
isDone = val;
});
await DatabaseHelper.instance
.updateIsDone(
isDone,
);
}),
title: Text(task.taskName),
onTap: () {
setState(() {
if (selectedId == null) {
textController.text = task.taskName;
selectedId = task.id;
} else {
textController.text = 'add something';
selectedId = null;
}
});
},
),
),
);
}).toList(),
);
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await DatabaseHelper.instance.add(
Tasksdb(
taskName: textController.text,
isDone: false,
),
);
setState(() {
textController.clear();
selectedId = null;
});
},
),
),
);
}
}
I found the answer: (in case of if someone had the same question)
I removed the bool isDone from the material app widget, and instead of assigning the switch val to that bool I assigned it to database's task.isDone value. To avoid switch's auto trigger, I parsed the Taskdb to the updateIsDone function
Future<int> updateIsDone(Tasksdb task, bool isDoneTodb) async {
Database db = await instance.database;
return await db.update(
'taskstable',
{
'isDone': isDoneTodb == true ? 1 : 0,
},
where: "id = ?",
whereArgs: [task.id]);
}
...
Switch(
value: task.isDone,
onChanged: (val) async {
setState(() {
task.isDone = val;
});
await DatabaseHelper.instance
.updateIsDone(task, task.isDone);
});
Related
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 can't seem to find how to write a constant data into a database to be loaded every start up. I want to write a set of data into the specializeArea table where it has an id column and area column as seen here from the DbHelper.dart and specializeModel.dart:
import 'package:conferenceApp/Model/UserModel.dart';
import 'package:conferenceApp/Model/specializeModel.dart';
import 'package:conferenceApp/Model/loginModel.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'dart:io' as io;
class DbHelper {
static Database conference;
static const String DB_Name = 'conference.db';
static const String Table_conferenceInfo = 'conferenceinfo';
static const String Table_specializeArea = 'specializearea';
static const String Table_login = 'login';
static const String C_UserID = 'id';
static const String C_Name = 'name';
static const String C_UName = 'username';
static const String C_Email = 'email';
static const String C_Phone = 'phone';
static const String C_Role = 'role';
static const String C_Area = 'area';
static const String C_Password = 'password';
static const int Version = 1;
Future<Database> get db async {
if (conference != null) {
return conference;
}
conference = await initDb();
return conference;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, DB_Name);
var db = await openDatabase(path, version: Version, onCreate: _onCreate);
return db;
}
_onCreate(Database db, int intVersion) async {
await db.execute("CREATE TABLE $Table_conferenceInfo ("
" $C_UserID INTEGER, "
" $C_Name TEXT, "
" $C_UName TEXT, "
" $C_Email TEXT,"
" $C_Password TEXT, "
" $C_Phone INTEGER, "
" $C_Role TEXT, "
" PRIMARY KEY ($C_UserID)"
")");
await db.execute("CREATE TABLE $Table_specializeArea ("
" $C_UserID INTEGER, "
" $C_Area TEXT )");
await db.execute("CREATE TABLE $Table_login ("
" $C_UserID INTEGER, "
" $C_UName TEXT, "
" $C_Password TEXT )");
}
Future<int> saveData(UserModel user) async {
var dbClient = await db;
var res = await dbClient.insert(Table_conferenceInfo, user.toMap());
return res;
}
Future<int> saveData1(specializeModel user) async {
var dbClient = await db;
var res1 = await dbClient.insert(Table_specializeArea, user.toMap());
return res1;
}
Future<int> saveData2(loginModel user) async {
var dbClient = await db;
var res2 = await dbClient.insert(Table_login, user.toMap());
return res2;
}
Future<UserModel> getLoginUser(String userId, String password) async {
var dbClient = await db;
var res =
await dbClient.rawQuery("SELECT * FROM $Table_conferenceInfo WHERE "
"$C_UName = '$userId' AND "
"$C_Password = '$password'");
if (res.length > 0) {
return UserModel.fromMap(res.first);
}
return null;
}
Future<specializeModel> getSubject(String subject) async {
var dbClient = await db;
var res =
await dbClient.rawQuery("SELECT * FROM $Table_specializeArea WHERE "
"$C_Area = '$subject'");
if (res.length > 0) {
return specializeModel.fromMap(res.first);
}
return null;
}
Future<int> updateUser(UserModel user) async {
var dbClient = await db;
var res = await dbClient.update(Table_conferenceInfo, user.toMap(),
where: '$C_UserID = ?', whereArgs: [user.user_id]);
return res;
}
Future<int> deleteUser(String user_id) async {
var dbClient = await db;
var res = await dbClient.delete(Table_conferenceInfo,
where: '$C_UserID = ?', whereArgs: [user_id]);
return res;
}
}
class specializeModel {
String user_id;
String user_area;
specializeModel(this.user_id, this.user_area);
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': user_id,
'user_area': user_area,
};
return map;
}
specializeModel.fromMap(Map<String, dynamic> map) {
user_id = map['id'];
user_area = map['user_area'];
}
#override
String toString() {
return 'specializeModel{id: $user_id, user_area: $user_area}';
}
}
The data I want to load is around 5 sets.
Here is the main page of the app, HomeForm.dart:
import 'package:conferenceApp/Model/specializeModel.dart';
import 'package:flutter/material.dart';
import 'package:conferenceApp/Comm/comHelper.dart';
import 'package:conferenceApp/Comm/genTextFormField.dart';
import 'package:conferenceApp/DatabaseHandler/DbHelper.dart';
import 'package:conferenceApp/Model/UserModel.dart';
import 'package:conferenceApp/Screens/LoginForm.dart';
import 'package:shared_preferences/shared_preferences.dart';
class HomeForm extends StatefulWidget {
#override
_HomeFormState createState() => _HomeFormState();
}
class _HomeFormState extends State<HomeForm> {
final _formKey = new GlobalKey<FormState>();
Future<SharedPreferences> _pref = SharedPreferences.getInstance();
DbHelper dbHelper;
final _conUserId = TextEditingController();
final _conName = TextEditingController();
final _conDelUserId = TextEditingController();
final _conUserName = TextEditingController();
final _conEmail = TextEditingController();
final _conPassword = TextEditingController();
final _conCPhone = TextEditingController();
final _conRole = TextEditingController();
#override
void initState() {
super.initState();
getUserData();
dbHelper = DbHelper();
}
Future<void> getUserData() async {
final SharedPreferences sp = await _pref;
setState(() {
_conUserId.text = sp.getString("id");
_conDelUserId.text = sp.getString("id");
_conName.text = sp.getString("name");
_conUserName.text = sp.getString("username");
_conEmail.text = sp.getString("email");
_conPassword.text = sp.getString("password");
_conCPhone.text = sp.getString("phone");
_conRole.text = sp.getString("role");
});
}
update() async {
String uid = _conUserId.text;
String Name = _conName.text;
String uname = _conUserName.text;
String email = _conEmail.text;
String passwd = _conPassword.text;
String phone = _conCPhone.text;
String role = _conRole.text;
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
UserModel user = UserModel(uid, Name, uname, email, passwd, phone, role);
await dbHelper.updateUser(user).then((value) {
if (value == 1) {
alertDialog(context, "Successfully Updated");
updateSP(user, true).whenComplete(() {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => LoginForm()),
(Route<dynamic> route) => false);
});
} else {
alertDialog(context, "Error Update");
}
}).catchError((error) {
print(error);
alertDialog(context, "Error");
});
}
}
delete() async {
String delUserID = _conDelUserId.text;
await dbHelper.deleteUser(delUserID).then((value) {
if (value == 1) {
alertDialog(context, "Successfully Deleted");
updateSP(null, false).whenComplete(() {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => LoginForm()),
(Route<dynamic> route) => false);
});
}
});
}
Future updateSP(UserModel user, bool add) async {
final SharedPreferences sp = await _pref;
if (add) {
sp.setString("username", user.user_name);
sp.setString("Name", user.Name);
sp.setString("email", user.email);
sp.setString("password", user.password);
sp.setString("phone", user.phone);
sp.setString("role", user.role);
} else {
sp.remove('id');
sp.remove('name');
sp.remove('username');
sp.remove('email');
sp.remove('password');
sp.remove('phone');
sp.remove('role');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Form(
key: _formKey,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
margin: EdgeInsets.only(top: 20.0),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//Update
getTextFormField(
controller: _conUserId,
isEnable: false,
icon: Icons.person,
hintName: 'User ID'),
SizedBox(height: 10.0),
getTextFormField(
controller: _conName,
icon: Icons.person,
hintName: 'Name'),
SizedBox(height: 10.0),
getTextFormField(
controller: _conUserName,
icon: Icons.person_outline,
inputType: TextInputType.name,
hintName: 'Username'),
SizedBox(height: 10.0),
getTextFormField(
controller: _conEmail,
icon: Icons.email,
inputType: TextInputType.emailAddress,
hintName: 'Email'),
SizedBox(height: 10.0),
getTextFormField(
controller: _conPassword,
icon: Icons.lock,
hintName: 'Password',
isObscureText: true,
),
SizedBox(height: 10.0),
getTextFormField(
controller: _conCPhone,
icon: Icons.phone,
hintName: 'Phone',
),
SizedBox(height: 10.0),
getTextFormField(
controller: _conRole,
icon: Icons.remove_red_eye,
hintName: 'Role',
),
SizedBox(height: 10.0),
Container(
margin: EdgeInsets.all(30.0),
width: double.infinity,
child: FlatButton(
child: Text(
'Update',
style: TextStyle(color: Colors.white),
),
onPressed: update,
),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(30.0),
),
),
//Specialization area
//Delete
getTextFormField(
controller: _conDelUserId,
isEnable: false,
icon: Icons.person,
hintName: 'User ID'),
SizedBox(height: 10.0),
SizedBox(height: 10.0),
Container(
margin: EdgeInsets.all(30.0),
width: double.infinity,
child: FlatButton(
child: Text(
'Delete',
style: TextStyle(color: Colors.white),
),
onPressed: delete,
),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(30.0),
),
),
],
),
),
),
),
),
);
}
}
If possible, I would also like to display the data stored as buttons or interactables later but storing them comes first.
Thank you
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.
I'm facing some problems when using Hive in Flutter for the first time. Before that, I was using Sqflite, and things just performed as expected, but I switched to Hive to look more performant I switch to Hive.
The problem is that when I initialize two Hive boxes "AvatarsPack" and "AvatarItem" with data, even awaiting for each insertion on DB, it looks like Hive returns before all insertions been done, so my FutureBuilder builds without getting the values. I'm trying to solve this problem for about 3 days and I almost switching back to Sqflite, but I remember that there are amazing guys right here that would solve this issue in seconds, so it's what I'm doing, I'm asking all you for help. Thank you by reading until here, below it's the code:
avatars_view.dart
final _controller = AvatarsController();
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _controller.initializeRepository(),
builder: (context, snapshot) {
Future.delayed(Duration(seconds: 1)).then((value) => print(_controller.getAvatarsPacks()[9].avatars));
if (snapshot.connectionState == ConnectionState.done) {
print('#####${_controller.getAvatarsPacks()[0].avatars}');
return MyShop(
getOwnedItems: _controller.getOwnedAvatars,
ownedTabTile: 'Owned',
isScrollable: true,
headers: _controller.getHeaders(),
bodies:
_controller.getAvatarsPacks().map((e) => e.avatars).toList(),
);
}
return Container();
});
}
}
avatars_controller.dart
final _repository = AvatarsRepository();
final Map<String, int> _AVATARS_PACKS_AMOUNT = {
'superheroes': 50,
'children': 30,
'halloween-1': 50,
'halloween-2': 50,
'halloween-3': 50,
'hospital': 18,
'people-1': 50,
'people-2': 50,
'people-3': 18,
'professions': 50,
};
List<AvatarsPack> getAvatarsPacks() {
return _repository.getAllAvatarsPacks();
}
Future<void> initializeRepository() async {
await _repository
.openBoxes()
.then((value) => print('----Boxes are oppened'));
await _clearBoxes().then((value) => print('----Boxes were cleared'));
if (_repository.isEmpty()) {
print('----boxes are empty');
await _initializeRepositoryData().then((value) =>
print('avatars quantity: ${_repository.getQuantityAvatarItems()}'));
}
return;
}
List<String> getHeaders() {
return _AVATARS_PACKS_AMOUNT.keys.toList();
}
List<AvatarItem> getOwnedAvatars() {
return _repository.getOwnedAvatars();
}
void updateAvatarItem(AvatarItem avatarItem) =>
_repository.updateAvatarItem(avatarItem);
Future<void> _initializeRepositoryData() async {
print('*******_initializeRepositoryData called()');
return _AVATARS_PACKS_AMOUNT.forEach((key, quantity) async {
final avatarsPack = AvatarsPack.create(
packID: key,
quantity: quantity,
packItemPrice: Money.all(coins: 50, diamonds: 5));
await _repository.addPack(avatarsPack);
});
}
Future<void> _clearBoxes() {
return _repository.clearBoxes();
}
#override
FutureOr onClose() {
_repository.closeBoxes();
super.onClose();
}
}
avatars_repository.dart
Box _avatarsPackBox;
Box _avatarItemBox;
final AVATAR_PACK = 'avatarsPack';
final AVATAR_ITEM = 'avatarItem';
Box get _avatarsPackInstance {
return _avatarsPackBox ??= Hive.box(AVATAR_PACK);
}
Box get _avatarItemInstance {
return _avatarItemBox ??= Hive.box(AVATAR_ITEM);
}
Future<void> addPack(AvatarsPack avatarsPack) async {
await _avatarsPackInstance.add(avatarsPack.toJson());
return avatarsPack.avatars.forEach((element) async {
await _avatarItemInstance.add(element.toJson());
});
}
List<AvatarsPack> getAllAvatarsPacks() {
final avatarsPacks = _avatarsPackInstance.values
.map((json) => AvatarsPack.fromJson(json))
.toList();
avatarsPacks.forEach((avatarPack) {
avatarPack.avatars = getAvatarItemsFromPack(avatarPack.packID);
});
return avatarsPacks;
}
Future<void> addAvatarItem(AvatarItem avatarItem) async {
await _avatarItemInstance.add(avatarItem.toJson());
return;
}
Future<void> updateAvatarItem(AvatarItem avatarItem) {
final index =
getAllAvatarItems().indexWhere((e) => e.pack == avatarItem.pack);
return _avatarItemInstance.putAt(index, avatarItem.toJson());
}
List<AvatarItem> getAllAvatarItems() {
return _avatarItemInstance.values
.map((json) => AvatarItem.fromJson(json))
.toList();
}
int getQuantityAvatarItems() {
return _avatarItemInstance.values.length;
}
List<AvatarItem> getAvatarItemsFromPack(String packID) {
final List<AvatarItem> avatars = [];
getAllAvatarItems().forEach((avatarItem) {
if (avatarItem.pack == packID) avatars.add(avatarItem);
});
return avatars;
}
List<AvatarItem> getOwnedAvatars() {
return getAllAvatarItems().where((element) =>
element.isOwned()).toList();
}
Future<void> openBoxes() async {
await Hive.openBox(AVATAR_PACK);
await Hive.openBox(AVATAR_ITEM);
return;
}
Future<void> closeBoxes() async {
await _avatarsPackInstance.close();
await _avatarItemInstance.close();
return;
}
Future<void> clearBoxes() async {
await _avatarsPackInstance.clear();
await _avatarItemInstance.clear();
return;
}
bool isEmpty() {
return _avatarsPackInstance.isEmpty;
}
}
Concerning my avatars images, they are in folders which names are the same as their packID and each folder contains X elements named in this way img-0, img-2, ..., img-[x-1], img-x . Any feedback will be appreciated, thanks :)
Try using a ValueListenableBuilder() instead of the FutureBuilder().
This watches changes on the Box and reflects those accordingly.
import 'package:hive_flutter/hive_flutter.dart';
ValueListenableBuilder(
valueListenable:
Hive.box(YOURBOX).listenable(),
builder: (context, Box box, _) {
return SomeWidget(withSomeData);
},
I'm having problems getting data from my firebase. I have the data but do not know how to display it.
Here is my Database:
This is my code:
class Home extends StatefulWidget {
final dynamic userUid, nicked;
Home({this.userUid, this.nicked});
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final int delayedAmount = 500;
//final AuthService _auth = AuthService();
void getNick() {
//get nickname of this User
final CollectionReference userNickname = Firestore.instance.collection('NickNames of Users');
var documentNick = userNickname.document(widget.userUid);
documentNick.get()
.then((DocumentSnapshot ds){
var nick = ds.data['MyNickName'];
print(nick);
var nicked = Home(nicked: nick,);
});
}
#override
Widget build(BuildContext context) {
return Container(
child: Scaffold(
backgroundColor: Colors.greenAccent[400],
body: SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB( 0 , 50, 0, 0),
child: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: DelayedAnimation(
child:
Text(
widget.nicked,//This i where the firebase data nickName code will go
textScaleFactor : 1,
style: TextStyle(
fontFamily: 'Comic',
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 30,
),
),
So i just dont know how to get the single document from firebase and display it.
So this is how i get userUid...
import 'package:firebase_auth/firebase_auth.dart';
//import 'package:flutter/cupertino.dart';
import 'package:fruithero/model/user.dart';
import 'package:fruithero/services/database.dart';
import 'package:fruithero/pages/myHome.dart';
class AuthService {
final dynamic nickNamesofUser;
AuthService({this.nickNamesofUser});
final FirebaseAuth _auth = FirebaseAuth.instance;
void homeTransporter(uid){
dynamic homeTransport = uid;
Home(userUid: homeTransport,);
}
// create user obj based on firebase user
User _userFromFirebaseUser(FirebaseUser user) {
return user != null ? User(uid: user.uid) : null;
}
// auth change user stream
Stream<User> get user {
return _auth.onAuthStateChanged
//.map((FirebaseUser user) => _userFromFirebaseUser(user));
.map(_userFromFirebaseUser);
}
// sign in anon
Future signInAnon() async {
try {
AuthResult result = await _auth.signInAnonymously();
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
// sign in with email and password
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return user;
} catch (error) {
print(error.toString());
return null;
}
}
// register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
//storing user uid
homeTransporter(user.uid);
//create new document for user with the uid
await DataBaseServices(uid: user.uid).createDocumentWithUid(nickNamesofUser);
//await DatabaseService(uid: user.uid).updateUserData(nickNamesofUser);
return _userFromFirebaseUser(user);
} catch (error) {
return null;
}
}
// sign out
Future signOut() async {
try {
return await _auth.signOut();
} catch (error) {
print(error.toString());
return null;
}
}
}
I hope this helps. Sir..............................................................................................................................................................
String nick,userID;
void initState() {
super.initState();
userID = widget.uid;
getNick();
print(userID);
}
void getNick() {
var users;
//get nickname of this User
Firestore.instance.collection('NickNames of Users').document(userID).get().then((data){
setState(() {
users = data;
nick = users['MyNickName'];
print(nick);
});
});
}