作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在 flutter 中列出用户,但我收到错误消息,即字符串不是类型转换中 int 类型的子类型。我无法检测到是代码的哪一部分导致了问题。
型号
class User {
final int id;
final String email;
bool auth;
User({this.id, this.email,});
factory User.fromJSON(Map<String, dynamic> jsonMap) {
return User(
id: jsonMap['id'] as int,
email: jsonMap['email'] as String,
);}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["email"] = email;
return map;}
@override
String toString() {
var map = this.toMap();
map["auth"] = this.auth;
return map.toString();
}}
实际部分
Future<List<User>> fetchUsers(http.Client client) async {
final response = await http.get("http://a6df36670036.ngrok.io/api/users/?format=json");
return compute(parseUsers, response.body);
}
List<User> parseUsers(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<User>((json) => User.fromJSON(json)).toList();
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: FutureBuilder<List<User>>(
future: fetchUsers(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? UsersList(users: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class UsersList extends StatelessWidget {
final List<User> users;
UsersList({Key key, this.users}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return Text(users[index].email);
},
);
}
}
我认为这是由模型的 id 部分引起的,但我不确定它是否真的是 id。
有人能帮帮我吗?
最佳答案
您的 API 中的 id
是一个 String
,因此您需要将模型中的 id 更改为 String
class User {
final String id;
final String email;
bool auth;
User({this.id, this.email,});
factory User.fromJSON(Map<String, dynamic> jsonMap) {
return User(
id: jsonMap['id'] as String,
email: jsonMap['email'] as String,
);}
Map toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["email"] = email;
return map;}
@override
String toString() {
var map = this.toMap();
map["auth"] = this.auth;
return map.toString();
}}
关于flutter - 异常 : type 'String' is not a subtype of type 'int' in type cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62597784/
我是一名优秀的程序员,十分优秀!