flutter - 没有为类型“Rx”定义吸气剂“某个变量”' 在使用 getx 控制器时
问题描述
我正在尝试为我的项目实现响应式 getx以实现更清晰的代码。
在控制器飞镖文件中,我有:
class ReadSinglePostController extends GetxController {
var posts = Post(
postID: 1,
userID: 0,
thumbnail: 'some base64string',
imageList: 'some base64string',
title: 'title',
description: 'description',
createdTime: DateTime.now())
.obs;//initialization and make the class Post observable
var postid = 0.obs; //initialize postid and make it observable
void updateID(var postID) {
postid = postID;
} //update the postid variable when a specific post is clicked in the post list
@override
void onInit() {
super.onInit();
readPost(postid);
}
Future readPost(var postID) async {
var result = await PostsDatabase.instance.readNote(postID);
posts = result;
}//function to read the detailed content of that specific post from database passing in the postid
}
然后在 UI 的主页上,我将所有帖子都放在一个网格中,我实现了这个控制器来更新postid
点击特定帖子的时间。单击帖子时,它会导航到帖子详细信息页面,并在该 UI 文件中出现错误:
Error:The getter "thumbnail" isn't defined for the type 'Rx<Post>'.
当我使用 getter 'title'、'description' 等时也会出现同样的错误。
这是代码:
class PostBody extends StatelessWidget {
PostBody({
Key? key,
}) : super(key: key);
final readSinglePostController = Get.put(ReadSinglePostController());
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.bodyText2!,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: GetX<ReadSinglePostController>(
builder: (controller) {
return ...
...
...
child: FadeInImage(
placeholder: MemoryImage(kTransparentImage),
image:
Utility.imageFromBase64String(
controller.posts.thumbnail)//Error:The getter "thumbnail" isn't defined for the type 'Rx<Post>'. and the same error comes up when I use getter 'title', 'description' and etc.
.image,
),...
任何线索,伙计们?
解决方案
在 Getx 中,Rx<T>
是T
.
这意味着当您调用时,controller.posts
您将获得一个反应类型的实例,即Rx<Post>
.
现在,Rx<Post>
不会直接知道内部存在哪些成员Post
,这就是您无法直接访问它们的原因。
相反,您必须首先value
从反应对象中获取 ,它为您提供了包装的实际Post
实例。Rx
从那里您可以访问您的实例变量。
controller.posts.value.thumbnail
在这里,controller.posts.value
是类型Post
。
推荐阅读
- c# - 如何从 Asp.net Core Razor 页面中的 IdentityUser 列表中获取没有角色的用户
- docker - Jhipster 6.0.1 的 Keycloak 无法启动
- ruby-on-rails - Rails6如何将文本从db填充到ActionText
- lit-element - LitElement 和 .bind(this)
- c# - 启用不同对象时是否可以运行 OnEnable() ?
- list - 我应该如何初始化我的元组列表
- php - 对数组进行两次排序或使用 php 微调数组
- mysql - MySQL:将 MAX 方法与 GROUP BY 子句 ERROR 1055 结合使用
- json - Vuex 在对象中找不到对象,返回未定义
- php - 无法运行 php artisan serve