Search code examples
fluttersqflite

How to get the total of column values in sqflite in flutter?


I want to get the total of the price column values and save it in a variable and return it...I have gone through other posts one of which is the question which i am asking but it was in android native and i am new to sqflite so i couldnt figure out how to write the code. So please help me with suggestions.

this is my code of the columns i am using

void _onCreate(Database db, int version) async {
await db.execute(
    "CREATE TABLE Cart(id INTEGER PRIMARY KEY,name TEXT, price TEXT,category 
TEXT,images TEXT)");
print("DB created");
}

I am trying to do this

Future calculateTotal() async{
var dbClient = await db;// couldnt figure out after this
var cursor = dbClient.rawQuery("SELECT SUM(price) as Total FROM Cart", 
null);
if(cursor.move)
}

Solution

  • According to https://www.techiediaries.com/flutter-sqlite-crud-tutorial/ this should do:

    Future calculateTotal() async {
      var dbClient = await db;
      var result = await dbClient.rawQuery("SELECT SUM(price) as Total FROM Cart");
      print(result.toList());
    }
    
    int _total;
    
    void _calcTotal() async{
      var total = (await db.calculateTotal())[0]['Total'];
      print(total);
      setState(() => _total = total)
    }
    
    @override
    Widget build(BuildContext context) {
      ...  
      Text(_total != null ? _total : 'waiting ...', ... )