我已经看到了这一点: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作为快照,这意味着loadInterest()Future不返回任何内容。
如果我正确理解了这个答案,那我就是在做我的事情:https://stackoverflow.com/a/49146503/1757321
答案 0 :(得分:0)
您无需为此使用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
,以确保其中没有任何异常。