gpt4 book ai didi

dart - Flutter Future 返回 null

转载 作者:行者123 更新时间:2023-12-03 03:06:09 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com