我正在使用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);
}
},
);
},
),
);
},
),
但我得到这个异常:
不能将类型为"未来"的值分配给类型为"int"的变量。
我通过为 OnPressed 添加异步来解决此问题
onPressed: () async {...}
然后使用此行 fo 代码
int count = await getCount();
感谢
使用await
来获取Future
的响应
int number = await getNumberOfUsers();
int count = await getCount();
您只需在调用 Future 之前设置关键字 "await":
你做什么:
int count = getCount();
什么是正确的:
int count = await getCount();
you need to add the "await" keyword before calling the function
int count = await getCount((;