class - 类的对象没有在 Flutter 的循环中实例化
问题描述
我正在使用json.decode
将我的 JSON 数据转换为 Objects 类型User
。我在Future
小FutureBuilder
部件中使用以下内容。这是代码。
Future<List<User>> _getData() async {
var data = await http.get("http://www.json-generator.com/api/json/get/cvAgrXxhOW?indent=2");
var jsonBody = json.decode(data.body);
List<User> users = [];
for (var user in jsonBody) {
print(user);
User u = new User(user);
users.add(u);
}
print(users.length);
return users;
}
User 类看起来如下所示。
class User {
String _id;
int index;
String about;
String name;
String picture;
String gender;
int age;
String registered;
double longitude;
String email;
String eyeColor;
String phone;
String address;
double latitude;
String balance;
String guid;
String company;
bool isActive;
User(dynamic data){
this._id = json.decode(data)["_id"];
this.index = int.parse(json.decode(data)["index"]);
this.about = json.decode(data)["about"];
this.name = json.decode(data)["name"];
this.picture = json.decode(data)["picture"];
this.gender = json.decode(data)["gender"];
this.age = int.parse(json.decode(data)["age"]);
this.registered = json.decode(data)["registered"];
this.longitude = double.parse(json.decode(data)["longitude"]);
this.email = json.decode(data)["email"];
this.eyeColor = json.decode(data)["eyeColor"];
this.phone = json.decode(data)["phone"];
this.address = json.decode(data)["address"];
this.latitude = double.parse(json.decode(data)["latitude"]);
this.balance = json.decode(data)["balance"];
this.guid = json.decode(data)["guid"];
this.company = json.decode(data)["company"];
this.isActive = json.decode(data)["isActive"];
}
getUser(){
return this;
}
}
该行User u = new User(user);
不允许代码进一步执行。函数中的print
语句_getData()
仅适用于循环的第一次迭代。之后,什么也没有发生。没有错误。
有什么建议么?
解决方案
哟不需要decode
再次数据
尝试这个:
User(dynamic data){
this._id = data["_id"];
this.index = int.parse(data["index"]);
this.about = data["about"];
....
更新
var jsonBody = json.decode(data.body) as List;
最终更新 我发现了错误,您不需要解析为 int 或 double 它已经解析,因为它是一个动态对象。
User(Map<String, dynamic> data) {
this._id = (data)["_id"];
this.index = data["index"];
this.about = (data)["about"];
this.name = (data)["name"];
this.picture = (data)["picture"];
this.gender = (data)["gender"];
this.age = (data)["age"];
this.registered = (data)["registered"];
this.longitude = data["longitude"];
this.email = (data)["email"];
this.eyeColor = (data)["eyeColor"];
this.phone = (data)["phone"];
this.address = (data)["address"];
this.latitude = (data)["latitude"];
this.balance = (data)["balance"];
this.guid = (data)["guid"];
this.company = (data)["company"];
this.isActive = (data)["isActive"];
}
推荐阅读
- javascript - 将日期时间范围拆分为单独的日期时间段,例如访问日期时间范围内每一天的分钟数
- java - For 循环显示前一个值和下一个值
- android - 如何从 mupdf 最新版本 1.14 中提取文本
- angular - 如何根据 Highchart 条形图中的值为条形设置不同的颜色?
- javascript - 正则表达式用链接替换主题标签
- c# - C# LINQ:linq 查询是否只返回延迟枚举?
- typescript - 在打字稿中从量角器发送电子邮件
- c# - 如何在 Visual Studio 中为两个类库创建 exe 文件
- c# - 当 ComboBox ItemsSource 更改时,WPF Combobox 更新但不显示显示
- android - 更新工作室 3.4 后找不到参数的 leftShift() 方法