snapshot.ConnectionState总是在等待

问题描述 投票:0回答:2

在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(),我猜这就是为什么快照总是在等待

dart flutter
2个回答
2
投票

调用AsyncSnapshot<dynamic>(ConnectionState.waiting, null, null)会导致窗口小部件树重建。因此,当重建AsyncSnapshot<dynamic>(ConnectionState.done, null, null)时,再次调用setState函数,导致无限循环(FutureBuilder-> getDoctors()-> rebuild-> getDoctors() ......)

解决方案是从setState()方法中移除getDoctors()或在setState方法中调用getDoctors一次,存储getDoctors()并将其传递给initState(),从而确保它只进行一次。

Future

0
投票

您需要从Future返回值以完成连接。将你的未来变成这样的东西:

FutureBuilder

并将FutureBuilder更改为:

Future _doctorsFuture;

initState() {
    ...
    _doctorsFuture = getDoctors();
}

.
.

// Somewhere in build()
    FutureBuilder(
        future: doctorsFuture,
        builder: (BuildContext context, snapshot) {
            print(snapshot);
        }
    ),

请修改以匹配您的变量和类。

© www.soinside.com 2019 - 2024. All rights reserved.