【问题标题】:Flutter: Futures and shared preferencesFlutter:期货和共享偏好
【发布时间】:2018-09-03 08:48:03
【问题描述】:

我有一个名为“retrieveDB”的函数,它使用 shared_preferences.dart 插件来检索数据,我将使用这些数据来决定是否从 Firestore 检索什么集合/文档名称。我已经在类的顶部初始化了 usersDB 和 notifDoc = ""。

    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";
    }
    }

我首先在 initState() 中放置了“retrieveDB”(在 super.initState() 之后)。

我的问题(我认为)是 shared_preferences 使用 Future 并暂停其执行并继续执行从 Firestore 检索数据的其他函数,使文档名称(usersDB 和 notifDoc = "")为空,从而产生错误。有没有办法在继续执行其他功能之前先等待“retrieveDB”,或者有什么地方可以放置“retrieveDB”以使其首先执行/完成?或者有没有更好的逻辑来实现我想要的?

【问题讨论】:

标签: asynchronous dart flutter future


【解决方案1】:

异步具有传染性。您无法从异步返回到同步。 如果函数使用async,则在调用它时需要使用await,以确保只有在异步函数完成后才执行以下代码:

Future foo() async {
  await retrieveDB();
  // other code that depends on the result or side effects of retrieveDB()
}

【讨论】:

  • 你好,甘特。如果依赖于retrieveDB() 结果的其他代码在其他函数上怎么办?就我而言,retrieveeDB() 位于 initState 中,而其他需要其输出的函数位于我的构建中。有什么解决方法吗?
  • build 中使用FutureBuilder 并从那里调用'retrieveDB
【解决方案2】:

改用匿名函数

@override
      void initState() {
        super.initState();
    () async {
    await retrieveDB();
    }
    }

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 2021-10-11
    • 2019-03-18
    • 2023-01-25
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多