Future Builder 从 API 返回空数据,即使快照不为空

Future Builder is returning null data from API even if snapshot is not null

我从 API 调用的 FutureBuilder 中的 ListView.builder 中得到空值,当我打印出响应正文时,它不是空的,当我打印时出 snapshot.hasData 它 returns true。当我从 API 调用中硬编码 return 对象(用户)的值时,它 return 就是那个硬编码值。这是代码: 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
    );
  }

UserList with 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'],
    
    );
  }
}

感谢任何形式的帮助,提前致谢!

您正在使用 FutureBuilder<VehicleData> 但您想访问 FutureBuilder<User>

改为<User>

好的,所以我不得不在 Map<String, dynamic> jsonDecodedResponse = jsonDecode(response.body); 的末尾添加 ['data'] 所以这个 'problem' 的最终解决方案是

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

应该多注意jsonResponse!

谢谢大家的帮助。