如何在flf中获取sqflite中的列值的总和?

时间:2019-02-08 19:06:17

标签: flutter sqflite

我想获取价格列值的总和并将其保存在变量中并返回...我已经浏览了其他帖子,其中之一是我要问的问题,但它在android native和i中是sqflite的新手,所以我无法弄清楚如何编写代码。所以请帮我提建议。

这是我正在使用的列的代码

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");
}

我正在尝试这样做

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)
}

2 个答案:

答案 0 :(得分:1)

Future<List> calculateTotal() async {
  var dbClient = await db;
  var result = await dbClient.rawQuery("SELECT * FROM Cart");
  return result.toList();
}

int _total = 0;
List priceList;

void _calcTotal() async{
   priceList = await db.calculateTotal();
   priceList.forEach((price){ _total = _total + price['price'];});
   print(_total);
   setState(() => _total = total);
}

@override
Widget build(BuildContext context) {
   ...  
   Text(_total != null ? _total : 'waiting ...', ... )

答案 1 :(得分:0)

根据https://www.techiediaries.com/flutter-sqlite-crud-tutorial/,这应该做到:

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 ...', ... )