dart - Flutter Future 返回 null

标签 dart flutter

我已经看过了:https://stackoverflow.com/a/49146503/1757321

遵循了解决方案,但在我的情况下它不起作用。

今天下午一些启示对我有帮助

  Future<String> loadInterest() async {
    print('Going to load interests');

    final whenDone = new Completer();

    SharedPreferences prefs = await SharedPreferences.getInstance();

    final token = await prefs.getString('token');

    print('The token ${token}');

    await this.api.interests(token).then((res) {
      // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
      whenDone.complete(res['interests']);
    });

    return whenDone.future;
  }

然后我尝试在未来的构建器中使用上面的 Future,如下所示:

new FutureBuilder(
  future: loadInterest(),
  builder: (BuildContext context, snapshot) {
     return snapshot.connectionState == ConnectionState.done
            ? new Wrap(
                 children: InterestChips(snapshot.data),
              )
            : Center(child: CircularProgressIndicator());
         },
     ),

InterestChips(...) 是这样的:

  InterestChips(items) {
    print('Interest Chips ${items}');
    List chipList;

    for (Object item in items) {
      chipList.add(Text('${item}'));
    }

    return chipList;
  }

但是,我总是得到 null 作为快照,这意味着 FutureloadInterest() 没有返回任何东西。

如果我正确地理解了这个答案,那么我将按照以下方式做我的:https://stackoverflow.com/a/49146503/1757321

最佳答案

您不需要为此使用Completer。由于您的方法已经是 async,因此您应该只为您的第一个代码块执行此操作:

Future<String> loadInterest() async {
  print('Going to load interests');

  final whenDone = new Completer();

  SharedPreferences prefs = await SharedPreferences.getInstance();

  final token = await prefs.getString('token');

  print('The token ${token}');

  final res = await this.api.interests(token).then((res) {
  // print('The response: ${res['interests']}'); <-- this prints response alright. Data is coming.
  return res['interests']);
}

您可能还想检查 snapshot.hasError 以确保其中没有任何异常。

关于dart - Flutter Future 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101553/

相关文章:

flutter - 为 Flutter 应用程序添加启动画面

android - 通过图标点击 flutter 打开设备上的联系人

android - 如何在后台从 Android 调用 Dart

flutter - 错误 Flutter Firebase Auth 和 Google 登录

flutter - VS 代码中缺少运行和调试启动配置按钮

dart - 找不到AngularDart模板

dart - 无法从其Git存储库中添加three.dart软件包

flutter - 滚动 future 的 ListView

dart - 我们如何在flutter Text或RichText中使用上标和下标文本

flutter - flutter :从 flutter 应用程序构建apk失败