【问题标题】:Future Builder is returning null data from API even if snapshot is not null即使快照不为空,Future Builder 也会从 API 返回空数据
【发布时间】:2021-06-26 08:24:04
【问题描述】:

我在 API 调用中的 FutureBuilder 内的 ListView.builder 中得到空值,当我打印出响应正文时,它不是空的,当我打印出 snapshot.hasData 时它返回 true .当我从 API 调用硬编码返回对象(用户)的值时,它会返回该硬编码值。这是代码: API 调用:

Future<User> getUser() async {
    final response = await apiRequest(
        Method.GET, '/user/ID');
    Map<String, dynamic> jsonDecodedResponse = jsonDecode(response.body);
    return User(
      id: jsonDecodedResponse['id'],
      dob: jsonDecodedResponse['dob'], // when I hardcode this to dob: 'QWERTY' it returns the value QWERTY to the FutureBuilder
    );
  }

带有 Future Builder 的用户列表,我在其中调用 api getUser()

 Future<User> _getUserList() async {
   
    var _userData = await APICalls.instance.getUser();

    return _userData;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: FutureBuilder<User>(
          future: _getUserList(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
print(snapshot.hasData); // returns true
              return ListView.builder(
                itemCount: 2, //snapshot.data.length is not working so I had to set it to count 2
                itemBuilder: (context, index) {
                return Text("${snapshot.data.dob}"); // this is null unless I hard code it in the API call return statement
                       }
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
            return Container();
          },
        ),
      ),
    );
  }
}

用户模型:

class Userextends ChangeNotifier {
  final String id,dob;

  User(
      {this.id,
      this.dob});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      dob: json['dob'],
    
    );
  }
}

感谢任何形式的帮助,在此先感谢!

【问题讨论】:

  • 我会在 Map jsonDecodedResponse = jsonDecode(response.body);并检查正文,然后查看 jsonDecodedResponse 对象

标签: flutter mobile flutter-futurebuilder


【解决方案1】:

好的,所以我必须在Map&lt;String, dynamic&gt; jsonDecodedResponse = jsonDecode(response.body); 的末尾添加['data'],所以这个“问题”的最终解决方案是

Map<String, dynamic> jsonDecodedResponse = jsonDecode(response.body)['data'];

应该多注意jsonResponse!

感谢大家的帮助。

【讨论】:

    【解决方案2】:

    您正在使用FutureBuilder&lt;VehicleData&gt;,但您想访问FutureBuilder&lt;User&gt;

    改成&lt;User&gt;

    【讨论】:

    • 错别字,会在原帖改。
    • 请发布您的 json 文件。
    • 当我复制/粘贴 json 文件时,我意识到了错误,将其发布为答案。再次感谢伙计!
    • 虽然我在打扰你,但你知道为什么我在同一个模块的itemCount: snapshot.data.length 中使用snapshot.data.length 时会得到Error: The getter 'length' isn't defined for the class 'User'. 并出错吗?我应该将模型定义为列表,然后使用snapshot.data.length
    • 完全不用担心,因为 user 不是列表或可迭代对象。如果你有一个用户列表,你可以捕获他们的长度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多