Flutter | Sqflite - retrieving elements of queryrow

39 Views Asked by At

this is a function in my dbhelper where it will obtain the filtered result through a rawquery.

static Future <List>  getWaterDrank() async {
    final db = await WaterDBHelper.db();
     List result = await db.rawQuery(
        "SELECT * FROM $tableName WHERE ${columnDate} = ?", [dateCurrent]
    );
     print(result);
    List filteredData = result[0];
    print('this is what we are after ${filteredData[2]}');
    
    return result;
  }

The problem is that i obtain a list like this

[{id: 74, date: Oct 25, 2023, waterDrank: 250}]

but i cant get the value of waterDrank - the element i want

I also played around with the use of my model but i cant seem to link my result to the element waterDrank

1

There are 1 best solutions below

4
On BEST ANSWER

Sqflite Database rawQuery returns a Future<List<Map<String, Object?>>>;. Get the list from the future, then the desired map, then iterate through the map's entries, then use firstWhere dart api checking the element's key with the equality operator against your desired key, waterDrank in this case, then get it's value.

Solution

final waterDrank = filteredData[2]
                .entries
                .firstWhere((element) => element.key == 'waterDrank')
                .value;

debugPrint(waterDrank.toString()); // Should print 250

Edit

Above solution is appropriate when iterating through map entries. In this case, It can be shortened with operator [] which get's the value of the given key.

final waterDrank = filteredData[2]['waterDrank']

debugPrint(waterDrank.toString()); // Should print 250