【问题标题】:Futubuilder snapshot.hasData returning falseFutubuilder 快照.hasData 返回 false
【发布时间】:2021-08-15 05:35:25
【问题描述】:

我编写了代码来获取数据并将它们放入 GridView Buider。

但条件 snapshot.hasData 不起作用,它总是 False 并返回 CircularProgressIndicator()。

但如果我将条件更改为 !snapshot.hasData(true) 我的代码正在运行,并且获取数据会正确显示在屏幕上。

获取 API


List<String> pcBusy = [];
Future fetchDataStandart() async {
  final urlAuth =
      Uri.parse('http://xxx.xx.xxx.xxx/api/usersessions/activeinfo');
  final response = await http
      .get(urlAuth, headers: <String, String>{'authorization': basicAuth});

  if (response.statusCode == 200) {
    List listPc = List.from(json.decode(response.body)['result']);
    pcBusy.clear();
    for (int i = 0; i < listPc.length; i++) {
      pcBusy.add(listPc[i]['hostName']);
    }
    print(pcBusy);
  } else {
    throw Exception('Error');
  }

生成器代码

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          'ЕВРОКО Стандарт',
        ),
      ),
      body: FutureBuilder(
        future: fetchDataStandart(),
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return ComputerGrid();
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

【问题讨论】:

  • 如果您想从 API 获取数据,请参考我的回答 hereherehere 在此示例中我使用了 snapshot.data 希望对您有所帮助

标签: json flutter dart


【解决方案1】:

您的 fetchDataStandart() 函数没有任何返回语句。因此调用它不会给你任何数据。您需要添加一个返回语句。我不知道你是不是没有分享完整的功能,因为最后缺少一个右括号。

【讨论】:

  • 我添加 bool isGetData = false 并在函数中返回 true。非常感谢!)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 2021-12-05
  • 2016-04-01
  • 2021-07-03
  • 2017-03-24
  • 2020-10-12
  • 1970-01-01
相关资源
最近更新 更多