首页 > 解决方案 > 在两个模型之间共享数据颤动

问题描述

我的应用程序从 REST API 获取一些帖子,这些帖子带有以下数据:{ title, photo,userID...} 我想要做的不是显示userID,而是显示user name。我想也许将 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;
}
 }

后模型

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),
   )

标签: flutterhttpdartdio

解决方案


如果我做对了,您只需要拥有一个用户对象(使用您的 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

更好的方法是使用您期望的特定参数(如帖子和名称)创建另一个类。因为我真的不知道它们是什么,你可以这样做:

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),
);

请随时再次询问,这不是您的情况。


推荐阅读