在FutureBuilder中,snapshot.ConnectionState始终在等待,但未来的功能已成功完成。在不同的页面中,相同的代码块工作,ConnectionState从等待完成转换。
未来的功能:
Future getDoctors() async {
var res = await http.get(globals.domain + "users/docs/");
var resBody = json.decode(utf8.decode(res.bodyBytes));
print(res.statusCode);
if (res.statusCode == 200) {
if (mounted) {
setState(() {
doctors = resBody;
});
}
}
}
未来的建设者:
FutureBuilder(
future: getDoctors(),
builder: (BuildContext context, snapshot) {
print(snapshot);
}
)
实际结果:qazxsw poi预期结果:过渡到qazxsw poi
EDIT1:虽然调试注意到定期调用未来函数getDoctors(),我猜这就是为什么快照总是在等待
调用AsyncSnapshot<dynamic>(ConnectionState.waiting, null, null)
会导致窗口小部件树重建。因此,当重建AsyncSnapshot<dynamic>(ConnectionState.done, null, null)
时,再次调用setState
函数,导致无限循环(FutureBuilder
-> getDoctors()
-> rebuild-> getDoctors()
......)
解决方案是从setState()
方法中移除getDoctors()
或在setState
方法中调用getDoctors
一次,存储getDoctors()
并将其传递给initState()
,从而确保它只进行一次。
Future
您需要从Future返回值以完成连接。将你的未来变成这样的东西:
FutureBuilder
并将FutureBuilder更改为:
Future _doctorsFuture;
initState() {
...
_doctorsFuture = getDoctors();
}
.
.
// Somewhere in build()
FutureBuilder(
future: doctorsFuture,
builder: (BuildContext context, snapshot) {
print(snapshot);
}
),
请修改以匹配您的变量和类。