Flutter does not run Async function - flutter

I am trying to get an async function _read() to run and the function does not pass the line:
Reading reading = await helper.queryReading(rowId); in this function:
_read() async {
DatabaseHelper helper = DatabaseHelper.instance;
int rowId = 1;
//lines above here executes
Reading reading = await helper.queryReading(rowId); //this is the line it stops on
// nothing below here is executed
if (reading == null) {
print('read row $rowId: empty');
} else {
print('read row $rowId: ${reading.reading}');
}
}
It is being called from the following function
class Profile {
Widget getScreen(){
print("Attempting to read db");
_read();
return Scaffold( ...)
Here is my helper class:
import 'dart:ffi';
import 'dart:io';
import 'package:ema/Readings.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
//table structure
final String tableName = 'Readings';
final String databasecolumnId = '_id';
final String databaseReading = 'Reading';
final String databaseDate = 'Time';
class DatabaseHelper {
//This is the name of the database file on disk
static final _databaseName = "readings.db";
//handles versioning for databases
static final _databaseVersion = 1;
//makes a singleton classs
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
//allows only one item to access the database
static Database _database;
Future<Database> get database async {
_database = await _initDatabase();
return database;
}
//this opens and creates the database
_initDatabase() async {
// The path_provider plugin gets the right directory for Android or iOS.
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
// Open the database. Can also add an onUpdate callback parameter.
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
//Creates the database
Future _onCreate(Database db, int version) async {
await db.execute(
'''
CREATE TABLE $tableName (
$databasecolumnId INTEGER PRIMARY KEY,
$databaseReading REAL NOT NULL,
$databaseDate INTERGER NOT NULL
)
'''
);
}
Future<int> insertReading(Reading reading) async {
Database db = await database;
int id = await db.insert(tableName, reading.toMap());
return id;
}
//gets reading
Future<Reading> queryReading(int id) async {
print("queryReading"); //gets here
Database db = await database;
print("Getting Db"); // not actually getting here
List<Map> maps = await db.query(tableName,
columns: [databasecolumnId, databaseReading, databaseDate],
where: '$databasecolumnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Reading.fromMap(maps.first);
}
print('maps length : ${maps.length}');
return null;
}
}
Here is my Readings class:
class Reading {
int id;
double reading;
DateTime date;
//constructor
Reading({this.id, this.reading, this.date});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
databaseReading: reading,
databaseDate: date.millisecondsSinceEpoch,
};
if (id != null) {
map[databasecolumnId] = id;
}
return map;
}
//extracts a node object from the map obect
Reading.fromMap(Map<String, dynamic> map) {
id = map[databasecolumnId];
reading = map[databaseReading];
date = new DateTime.fromMillisecondsSinceEpoch(map [databaseDate]);
}
}

Turns out there was a deadlock in getting the database. By putting a lock on it it worked.
Here is the code to resolve it:
///declreation of the database
Database _database;
///Gets the database ensuring that there are no locks currently on the database
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}

Related

I got issue when i wanna create db to sqflite, DatabaseException(Error Domain=FMDatabase Code=1 "no such table)

I wanna create db with sqflite but this no create and show something issue, Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "no such table: todo" UserInfo={NSLocalizedDescription=no such table: todo}) sql 'SELECT * FROM todo WHERE id = ?' args [11], oke let's check it my db helper :
db helper
import 'package:sqflite/sqflite.dart';
import 'model.dart';
class DatabaseHelper {
//singleton base
static DatabaseHelper? _instance;
DatabaseHelper._internal() {
_instance = this;
}
factory DatabaseHelper() => _instance ??= DatabaseHelper._internal();
//TODO: add database name
static late Database _database;
//TODO: add get database
Future<Database> get databse async {
_database = await _initializeDatabase();
return _database;
}
//TODO: add db name
static String _tableName = 'todo';
//TODO: initialize db
Future<Database> _initializeDatabase() async {
final path = await getDatabasesPath();
final db = openDatabase('notes.db', version: 1, onCreate: (db, version) {
version:
1;
db.execute('''CREATE TABLE $_tableName(
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT,
)''');
});
return db;
}
Future<void> insertData(Note note) async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(
_tableName,
where: 'id = ?',
whereArgs: [note.id],
);
await db.insert(_tableName, note.toJson());
}
//get
Future<List<Note>> getAllNotes() async {
final Database db = await databse;
List<Map<String, dynamic>> result = await db.query(_tableName);
return result.map((e) => Note.fromJson(e)).toList();
}
}

Issues sqflite in flutter

It's been a while I started flutter. And now I am working on the database part. I started with sqflite since it was the ideal one for offline apps but now I can't understand a thing please can somebody help me with this.
import 'package:flutter/widgets.dart';
import 'note.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper = DatabaseHelper();
static Database? _database;
String noteTable = 'note_table';
String colID = 'id';
String colTitle = 'title';
String colDescription = 'description';
String colPriority = 'priority';
String colDate = 'date';
DatabaseHelper._createInstance();
factory DatabaseHelper() {
if (_databaseHelper == null) {
var databaseHelper = DatabaseHelper._createInstance();
_databaseHelper = databaseHelper;
}
return _databaseHelper;
}
//custom getter for the database
Future<Database> get database async {
// ignore: prefer_conditional_assignment
if (_database == null) {
_database = await initializeDatabase();
}
return _database!;
}
Future<Database> initializeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'note.db';
var notesDatabase =
await openDatabase(path, version: 1, onCreate: _createDb);
return notesDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $noteTable($colID INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)');
}
Future<List<Map<String, dynamic>>> getNoteMapList() async {
Database db = await this.database;
var result = await db.query(noteTable, orderBy: '$colPriority ASC');
return result;
}
Future<int> insertData(Note note) async {
Database db = await this.database;
var result = await db.insert(noteTable, note.toMap());
return result;
}
Future<int> updateNote(Note note) async {
Database db = await this.database;
var result = await db
.update(noteTable, note.toMap(), where: '$colID', whereArgs: [note.id]);
return result;
}
Future<int> deleteNote(int id) async {
Database db = await this.database;
var result =
await db.rawDelete('DELETE FROM $noteTable where $colID = $id');
return result;
}
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x =
await db.rawQuery('SELECT COUNT (*) FROM $noteTable');
int? result = Sqflite.firstIntValue(x);
return result!;
}
Future<List<Note>> getNoteList() async {
var noteMapList = await getNoteMapList();
int count = noteMapList.length;
}
}
This is the whole code. I have watched many videos but can't understand a thing. The problem starts when I the database part starts. And while answering the questions please try to be a little simple.

Sqlflite - Null check operator used on a null value

I received - Null check operator used on a null value this error while trying to test my sqflite application. Even thought the code is working in emulator. but it didnt passed the test.
Kindly help.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DbHelper {
static final DbHelper instance = DbHelper._instance();
DbHelper._instance();
static Database? _db;
Future<Database> get db async {
if (_db != null) return db;
_db = await _initDb();
return _db!;
}
Future<Database> _initDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + '/account_keeper.db';
final accountManagerDb = await openDatabase(
path,
version: 1,
onCreate: _createDb,
);
return accountManagerDb;
}
void _createDb(Database db, int version) async {
// Table 1- BusinessProfile Profile
print('creating db');
print('--create database--');
const String businessProfileTable = 'businessProfile_table';
String businessId = 'id';
String businessName = 'businessName';
await db.execute(
'''
CREATE TABLE
$businessProfileTable(
$businessId INTEGER PRIMARY KEY AUTOINCREMENT,
$businessName TEXTT )''',
);
}
}

Why the Id of object addedItem is always return 1 until I refresh page

I want to get the real Id of object how's I create in real time without close page and return back to it
because I use initState() to get data from Database and if I tried to get Id without do that it will return 1 ;
any one know why this happened and who to fix it ?
this my Function:
item(String name,String desc,int rate) async{
int savedItem = await db.saveMovie(Movie(name, desc,rate.toString()));
Movie addedItem = await db.getMovie(savedItem);
setState(() {
movies.add(addedItem);
});
print("Item id :${addedItem.id} Saved item : ${savedItem}");
}
and this my database helper code :
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mblists/models/movies.dart';
class DatabaseHelper {
final String moviesTable = "moviesTable";
final String idColumn = "id";
final String nameColumn = "name";
final String descriptionColumn = "description";
final String rateColumn = "rate";
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async{
if(_db != null){
return _db;
}
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async{
Directory fileDirectory = await getApplicationDocumentsDirectory();
String path = join(fileDirectory.path,"maindatabase.db");
var maindb = await openDatabase(path,version: 1,onCreate: _onCreate);
return maindb;
}
void _onCreate(Database db,int newVersion) async{
await db.execute(
"CREATE TABLE $moviesTable($idColumn INTEGER PRIMARY KEY, $nameColumn TEXT, $descriptionColumn TEXT, $rateColumn TEXT)");
}
Future<int> saveMovie(Movie movie) async{
var dbClient = await db;
int res = await dbClient.insert("$moviesTable", movie.toMap());
return res;
}
Future<List> getAllMovies() async{
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable");
return result;
}
Future<Movie> getMovie(int id) async{
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $id = $id");
if(result.length == 0) {
return null;
}
return Movie.formMap(result.first);
}
Future<int> getCount() async {
var dbCllient = await db;
return Sqflite.firstIntValue(
await dbCllient.rawQuery("SELECT COUNT(*) FROM $moviesTable")
);
}
Future<int> deleteMovie(int id) async {
var dbClient = await db;
return await dbClient.delete(moviesTable,where: "$idColumn = ?",whereArgs: [ id]);
}
Future<int> deleteMovies() async {
var dbClient = await db;
return await dbClient.delete(moviesTable);
}
Future<int> updateMovie(Movie movie) async {
var dbClient = await db;
return await dbClient.update(moviesTable,movie.toMap(),
where: "$idColumn = ?" , whereArgs: [movie.id]
);
}
Future colse() async{
var dbClient = await db;
return await dbClient.close();
}
}
Insert method returns correct new id, but you have a typo in getMovie:
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $id = $id");
WHERE condition should contain column name, but your has id = id condition (which is always true) and then it takes the first element (always the same one). Fix it by passing id column's name:
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $idColumn = $id");
And it works:
I/flutter ( 5996): Item id :13 Saved item : {id: 13, name: test, description: desc, rate: 1}
I/flutter ( 5996): Item id :14 Saved item : {id: 14, name: test, description: desc, rate: 1}
I/flutter ( 5996): Item id :15 Saved item : {id: 15, name: test, description: desc, rate: 1}

throw ArgumentError("nullColumnHack required when inserting no data");Exception in Flutter

I am working on SqFlite programme but it shows ArgumentError Exception.
My code is not working it showing I can not insert data into database.
Please some one help me with this.SQFlite Operation like CRUD is not performing.
Exception like ArgumentError Exception like occurring some default dart file with Exception Showing.
Exception throw ArgumentError("nullColumnHack required when inserting no data");
import 'dart:async';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite_app/models/note.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper;
static Database _database;
String noteTable = 'note_table';
String colId = 'id';
String colTitle = 'title';
String colDescription = 'description';
String colPriority = 'priority';
String colDate = 'date';
DatabaseHelper._createInstance();
factory DatabaseHelper(){
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._createInstance();
}
return _databaseHelper;
}
Future<Database> get databse async {
if (_database == null) {
_database = await initalizeDatabase();
}
return _database;
}
Future<Database> initalizeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'note.db';
var noteDatabase = await openDatabase(
path, version: 1, onCreate: _createDb);
return noteDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $noteTable ($colId INTEGER PRIMARY KEY AUTOINCREMENT,$colTitle TEXT,'
'$colDescription TEXT,$colPriority INTEGER,$colDate TEXT)');
}
Future<List<Map<String, dynamic>>> getNoteMapList() async {
Database db = await this.databse;
//var result=await db.rawQuery('SELECT * FROM $noteTable order by $colPriority ASC');
var result = await db.query(noteTable, orderBy: '$colPriority ASC');
return result;
}
Future<int> insertNote(Note note) async {
Database db = await this.databse;
var result = await db.insert(noteTable, note.toMap());
return result;
}
Future<int> updateNote(Note note) async {
var db = await this.databse;
var result = await db.update(
noteTable, note.toMap(), where: '$colId=?', whereArgs: [note.id]);
return result;
}
Future<int> deleteNote(int id) async {
var db = await this.databse;
int result = await db.rawDelete('DELETE FROM $noteTable WHERE $colId=$id');
return result;
}
Future<int> getCount() async {
Database db = await this.databse;
List<Map<String, dynamic>> x = await db.rawQuery(
"SELECT COUNT (*) from $noteTable");
int result = Sqflite.firstIntValue(x);
return result;
}
Future<List<Note>> getNoteList() async {
var noteMapList = await getNoteMapList();
int count = noteMapList.length;
List<Note> noteList = List<Note>();
for (int i = 0; i < count; i++) {
noteList.add(Note.fromMapObject(noteMapList[i]));
}
return noteList;
}
}
Just pass one more argument in db.insert(i.e. nullColumnHack) with value equal to the Auto Incrementing ID Integer...it will work...Do this for all other operations...
Future<int> insertNote(Note note) async {
Database db = await this.databse;
var result = await db.insert(noteTable, note.toMap(),nullColumnHack: colId);
return result;
}