我正在尝试为我的项目实施反应式 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,
),...
有什么线索吗,伙计们?
IN Getx,Rx<T>
是T
.
这意味着当您调用时,controller.posts
您将获得一个响应式类型的实例,即Rx<Post>
.
现在,Rx<Post>
不会直接知道内部存在哪些成员Post
,这就是您无法直接访问它们的原因。
相反,您必须首先value
从反应式对象中获取 ,它为您提供了包装的实际Post
实例Rx
。从中您可以访问您的实例变量。
controller.posts.value.thumbnail
这里,controller.posts.value
是 类型Post
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句