1

我想获取价格列值的总和并将其保存在一个变量中并返回它...我已经浏览过其他帖子,其中一个是我要问的问题,但它是在 android native 中,我是新手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)
}
4

2 回答 2

4

根据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 ...', ... )
于 2019-02-08T19:30:04.360 回答
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 ...', ... )
于 2019-07-23T14:04:20.900 回答