在flutter中如何得到sqflite中列值的总和?

ckocjqey  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(127)

我想得到价格列值的总和,并将其保存在一个变量中并返回它...我已经看过其他帖子,其中之一是我问的问题,但它是在android原生,我是新的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)
}
kpbwa7wx

kpbwa7wx1#

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

s4chpxco2#

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

相关问题