Asynchronous 颤振:未来与共同偏好
我有一个名为“retrieveDB”的函数,它使用shared_preferences.dart插件来检索数据,我将使用这些数据来决定是否从Firestore检索哪个集合/文档名称。我已经在类的顶部初始化了usersDB和notifDoc=“”Asynchronous 颤振:未来与共同偏好,asynchronous,dart,flutter,future,Asynchronous,Dart,Flutter,Future,我有一个名为“retrieveDB”的函数,它使用shared_preferences.dart插件来检索数据,我将使用这些数据来决定是否从Firestore检索哪个集合/文档名称。我已经在类的顶部初始化了usersDB和notifDoc=“” Future retrieveDB() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String db = prefs.getS
Future retrieveDB() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String db = prefs.getString('db');
if (db == "MISS") {
usersDB = "users_miss";
notifDoc = "notifTokenMISS";
} else if (db == "SDD") {
usersDB = "users";
notifDoc = "notifToken";
}
}
我将'retrieveDB'放在initState()中的第一个位置(在super.initState()之后)
我的问题(我认为)是共享的_首选项使用Future,它暂停执行并继续使用其他函数从Firestore检索数据,而文档名(usersDB和notifDoc=“”)为空,从而产生错误。是否有办法在继续执行其他功能之前先等待'retrieveDB',或者是否有任何地方可以放置'retrieveDB',让它首先执行/完成?或者在实现我想要的东西时有没有更好的逻辑 异步是有传染性的。无法从异步返回到同步。 如果函数使用了
async
,则在调用时需要使用wait
,以确保以下代码仅在异步函数完成后执行:
Future foo() async {
await retrieveDB();
// other code that depends on the result or side effects of retrieveDB()
}
异步是有传染性的。无法从异步返回到同步。 如果函数使用了
async
,则在调用时需要使用wait
,以确保以下代码仅在异步函数完成后执行:
Future foo() async {
await retrieveDB();
// other code that depends on the result or side effects of retrieveDB()
}
改用匿名函数
@override
void initState() {
super.initState();
() async {
await retrieveDB();
}
}
改用匿名函数
@override
void initState() {
super.initState();
() async {
await retrieveDB();
}
}
看,嗨,冈特。如果依赖retrieveDB()结果的其他代码位于其他函数上,该怎么办?在我的例子中,retrieveeDB()处于initState,其他需要其输出的函数在我的构建中。有什么解决方法吗?在
build
中使用FutureBuilder并调用'retrieveDB from thereHi Gunter'。如果依赖retrieveDB()结果的其他代码位于其他函数上,该怎么办?在我的例子中,retrieveeDB()处于initState,其他需要其输出的函数在我的构建中。有什么解决方法吗?在build
中使用FutureBuilder并从那里调用'retrieveDB'