I need to extract the number of records for SQFlite database table.
I need to assign the number of records from DB to the myCount int field.
int myCount = 0;
The following code extracts the number of records from DB.
Future<int?> countRecords() async {
final db = await instance.dataBase;
final result = await db.rawQuery('SELECT COUNT(${Fields.id}) FROM $Table');
final list = result.map((json) => Record.fromJson(json)).toList();
if(list.isNotEmpty) return list.length; else throw Exception('Empty List');
}
I need to use the above code below:
Future<int?> countDBRecords() async {
return myCount = (await DB.instance.countDBRecords())!;
}
My Issue: I cannot assign Future int to int.
int countRecordsTotal(){
myCount = countDBRecords(); -> this line is the issue.
return myCount;
}
Could you please suggest how to extract the number of records from DB and assign to a variable.
Thank You
2
Answers
The issue is that
countDBRecords()
returns aFuture<int?>
and so you can’t assign theFuture
object to theint
variable.To get the int value itself, add the
await
keyword before thecountDBRecords()
function call.Like this:
The problem is not something related to SQFlite.
You need to use
await
as long as you’re using asynchronous function.This is the solution to you’re problem.
I hope that’s what you’re looking for.
Also you should learn about asynchronous Dart code, if you don’t know much about it.