在两个模型之间共享数据颤振



我的应用程序从REST API获取一些帖子,这些帖子带有以下数据:{标题、图片、标识……}我想做的是不显示userID,我想要用户名。我想过把id从post模型传递给user模型,但是我不知道怎么做,也不知道这是不是最好的方法。

用户模型

class User {
String id;
String name;
String email;
String createdAt;

User(
{
this.id,
this.name,
this.createdAt,
this.email
});
User.fromJson(Map<String, dynamic> json) {
id = json['_id'];
name = json['name'];
email = json['email'];
createdAt = json['createdAt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.id;
data['name'] = this.name;
data['email'] = this.email;
data['createdAt'] = this.createdAt;
return data;
}
}

Post模型

class Post {
String user;
String id;
String title;
String content;
String address;
String category;
String price;
String photo;
Post(
{this.user,
this.title,
this.category,
this.content,
this.address,
this.price,
this.id,
this.photo});
Post.fromJson(Map<String, dynamic> json) {
id = json['_id'];
title = json['title'];
price = json['price'];
user = json['user'];
content = json['content'];
category = json['category'];
address = json['address'];
photo = json['photo'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['price'] = this.price;
data['user'] = this.user;
data['content'] = this.content;
data['category'] = this.category;
data['address'] = this.address;
return data;
}
}

主屏幕我想显示用户名

AutoSizeText(
reversedList[index].user,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18),
)

如果我得到了它的权利,你只需要有一个用户对象(与您的User. fromjson),并注入到Post初始化。

一样:

final user = User.fromJson(jsonUser);
final post = Post.fromJson(jsonPost..['user']=user.name);
//like this you don't need to refactor anything for now

一个更好的方法是创建另一个类,其中包含您期望的特定参数,如post和name。因为我真的不知道它们是哪一个,你可以这样做:

class UserPostModel{
final User user;
final Post post;
UserPostModel(this.user,this.post);
}

使用这种方法,AutoSizeText可以按如下方式安装:

final userPost = UserPost(user, post);
return AutoSizeText(
reversedList[index].user.name,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18),
);

如果不是你的情况,你可以再问一遍。

最新更新