【问题标题】:Flutter Future returns null颤振未来返回 null
【发布时间】:2018-06-29 12:16:01
【问题描述】:

我已经看过了: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

【问题讨论】:

  • 发送您发送 HTTP 请求的链接。

标签: dart flutter


【解决方案1】:

您不需要为此使用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 以确保您没有在其中遇到任何异常。

【讨论】:

  • 你在检查 snapshot.hasError 吗?
猜你喜欢
  • 2022-06-18
  • 2020-02-07
  • 2022-08-06
  • 2020-06-01
  • 2022-07-19
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多