Flutter Future 返回 null。

3
我已经看过了这个: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 builder中使用上述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请求的链接。 - Son of Stackoverflow
1个回答

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,以确保您在其中没有收到任何异常。


2
你正在检查 snapshot.hasError 吗? - Dan Field

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接