【发布时间】:2020-05-12 17:43:54
【问题描述】:
我正在使用sqflite,我正在通过以下代码获取特定记录的行数:
Future<int> getNumberOfUsers() async {
Database db = await database;
final count = Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM Users'));
return count;
}
Future<int> getCount() async {
DatabaseHelper helper = DatabaseHelper.instance;
int counter = await helper.getNumberOfUsers();
return counter;
}
我想将此函数的结果放入 int 变量中,以便在FloatingActionButton 中的onPressed 中使用它
int count = getCount();
int countParse = int.parse(getCount());
return Stack(
children: <Widget>[
Image.asset(
kBackgroundImage,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
child: Icon(
Icons.add,
color: kButtonBorderColor,
size: 30.0,
),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) => AddScreen(
(String newTitle) {
setState(
() {
//--------------------------------------------
//I want to get the value here
int count = getCount();
int countParse = int.parse(getCount());
//--------------------------------------------
if (newTitle != null && newTitle.trim().isNotEmpty) {
_save(newTitle);
}
},
);
},
),
);
},
),
但我遇到了这个异常:
“Future”类型的值不能分配给“int”类型的变量。
【问题讨论】:
-
看来您已经知道如何使用
await关键字了。你能解释一下为什么这里还不够吗? -
要么使用
FutureBuilder,要么使用await关键字来获取Future的值。 -
@nvoigt 这行代码会导致异常 int count = getCount();我想将值作为整数获取,然后检查它是否不大于 100
-
我知道你想要什么。但是您已经使用该方法在您发布的代码中将
Future<T>解析为T3 次。为什么现在还不够好?为什么不能第四次使用它?