gpt4 book ai didi

flutter - 异常 : type 'String' is not a subtype of type 'int' in type cast

转载 作者:行者123 更新时间:2023-12-02 16:36:39 27 4
gpt4 key购买 nike

我试图在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com