如何在 flutter 中获取 sqflite 中列值的总和?
How to get the total of column values in sqflite in flutter?
我想获取价格列值的总和并将其保存在一个变量中,然后 return 它...我浏览了其他帖子,其中一篇是我要问的问题,但它在 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)
}
根据 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 ...', ... )
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 ...', ... )
我想获取价格列值的总和并将其保存在一个变量中,然后 return 它...我浏览了其他帖子,其中一篇是我要问的问题,但它在 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)
}
根据 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 ...', ... )
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 ...', ... )