【发布时间】: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