我正在创建一个flutter应用程序来显示列表中的用户。我可以获取和打印数据,但我无法显示数据,因为我得到这个错误Exception has occurred. _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')
我使用dio包来获取数据。下面是用于进行API调用的代码
class DioClient {
final Dio _dio = Dio();
final _farmerUrl = 'https://retoolapi.dev/Rzl99e/farmers';
Future<Users?> getUser() async {
Users? users;
try {
Response userData = await _dio.get(_farmerUrl);
print('User Info: ${userData.data}');
users = Users.fromJson(userData.data);
} on DioError catch (e) {
if (e.response != null) {
print('Dio error!');
} else {
print('Error sending request! '+ e.message);
}
}
return users;
}
}
这是我用来解析json响应的模型类
List<Users> usersFromJson(String str) => List<Users>.from(json.decode(str).map((x) => Users.fromJson(x)));
String usersToJson(List<Users> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Users {
Users({
this.id,
this.bio,
this.email,
this.lastName,
this.firstName,
this.phoneNumber,
this.memberNumber,
});
int? id;
String? bio;
String? email;
String? lastName;
String? firstName;
String? phoneNumber;
String? memberNumber;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"],
bio: json["bio"],
email: json["email"],
lastName: json["last_name"],
firstName: json["first_name"],
phoneNumber: json["phone_number"],
memberNumber: json["member_number"],
);
Map<String, dynamic> toJson() => {
"id": id,
"bio": bio,
"email": email,
"last_name": lastName,
"first_name": firstName,
"phone_number": phoneNumber,
"member_number": memberNumber,
};
}
这是我用来显示用户列表的代码
body: SingleChildScrollView(
child: Center(
child: FutureBuilder<Users?>(
future: _client.getUser(),
builder: (context, snapshot) {
if (snapshot.hasData) {
Users? userInfo = snapshot.data;
if (userInfo != null) {
return ListTile(
title: Text(userInfo.firstName! + ' ' + userInfo.lastName!),
subtitle: Text(userInfo.phoneNumber!),
);
}
}
return CircularProgressIndicator();
},
),
),
),
为了完全显示用户列表,我可以做哪些更改。
2条答案
按热度按时间nwnhqdif1#
sr4lhrrt2#
解码数据并以列表格式存储,因为API返回列表数据
为用户列表创建响应类
并调用API一样,你的未来将返回列表响应:
您可以从UI调用