Flutter SQFLite can't assign Future Int to int

58 Views Asked by At

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

There are 2 best solutions below

5
On

The issue is that countDBRecords() returns a Future<int?> and so you can't assign the Future object to the int variable.

To get the int value itself, add the await keyword before the countDBRecords() function call.

Like this:

Future<int?> countRecordsTotal() async{
    myCount = await countDBRecords(); 
    return myCount;
}
1
On

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.

Future<int> countRecordsTotal() async {
        myCount = (await countDBRecords())!; //! is for null check
        return myCount;
    }

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.