[英]Flutter Future returns null
I've seen this already: https://stackoverflow.com/a/49146503/1757321 我已经看过了: https : //stackoverflow.com/a/49146503/1757321
Followed the solution, but it is not working in my case. 遵循了解决方案,但在我的情况下不起作用。
Some enlightenment would do for me this afternoon 今天下午会有一些启发给我
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;
}
Then I'm trying to use the above Future
in a future builder like so: 然后,我试图在像这样的未来构建器中使用上述
Future
:
new FutureBuilder(
future: loadInterest(),
builder: (BuildContext context, snapshot) {
return snapshot.connectionState == ConnectionState.done
? new Wrap(
children: InterestChips(snapshot.data),
)
: Center(child: CircularProgressIndicator());
},
),
Where InterestChips(...)
is this: 这是
InterestChips(...)
的地方:
InterestChips(items) {
print('Interest Chips ${items}');
List chipList;
for (Object item in items) {
chipList.add(Text('${item}'));
}
return chipList;
}
But, I always get null
as the snapshot, which means the loadInterest()
for the Future
is not returning anything. 但是,我总是将
null
作为快照,这意味着Future
的loadInterest()
不返回任何内容。
If I understand this answer correctly, then I'm doing mine along the lines of that: https://stackoverflow.com/a/49146503/1757321 如果我正确理解了这个答案,那么我正在按照以下方式进行: https : //stackoverflow.com/a/49146503/1757321
You don't need to use a Completer
for this. 您不需要为此使用
Completer
器。 Since your method is already async
, you should just do this for your first code block: 由于您的方法已经
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']);
}
You might also want to check for snapshot.hasError
to make sure you're not getting any exceptions in there. 您可能还需要检查
snapshot.hasError
,以确保其中没有任何异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.