' 在使用 getx 控制器时,flutter,getter,flutter-getx"/>

首页 > 解决方案 > 没有为类型“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,
                                ),...

任何线索,伙计们?

标签: fluttergetterflutter-getx

解决方案


在 Getx 中,Rx<T>T.

这意味着当您调用时,controller.posts您将获得一个反应类型的实例,即Rx<Post>.

现在,Rx<Post>不会直接知道内部存在哪些成员Post,这就是您无法直接访问它们的原因。

相反,您必须首先value从反应对象中获取 ,它为您提供了包装的实际Post实例。Rx从那里您可以访问您的实例变量。

controller.posts.value.thumbnail

在这里,controller.posts.value是类型Post


推荐阅读