7

I have this Getx controller for reading content of a Post from database:

class ReadSinglePostController extends GetxController {
  var isLoading = true.obs;
  var posts = Post(
          postID: 1,
          userID: 0,
          thumbnail: 'thumbnail',
          imageList: 'imageList',
          title: 'title',
          description: 'description',
          createdTime: DateTime.now())
      .obs; //yes this can be accessed

  var postid = 2.obs; //I want this value to change when I click a post in the UI

  @override
  void onInit() {
    super.onInit();
    readPost(postid);
  }

  updateID(var postID) {
    postid.value = postID;
    print('im print ${postid.value}');
  }//should update postid when a post is clicked in the UI

  Future readPost(var postID) async {
    try {
      isLoading(true);
      var result = await PostsDatabase.instance.readPost(postID);
      posts.value = result;
    } finally {
      isLoading(false);
    }
  }
}

But the problem I'm now facing is that: to read a specific Post from database, I need the postID parameter. And as you can imagine, this parameter can be recorded when I click a specific Post in UI, but how do I pass that parameter to this Getx controller? Or maybe I am doing this whole thing wrong?

BigPP
  • 522
  • 2
  • 8
  • 18

2 Answers2

9

You can use the instance of your controller on the Ui.

For example, on the widget you call the controller:

final ReadSinglePostController _controller = Get.put(ReadSinglePostController());

//and when you need to change you do like this:
_controller.updateID(newId);

Inside the updateID method you can call the load method:

updateID(var postID) {
  postid.value = postID;
  print('im print ${postid.value}');
  readPost(postID);
}
Jorge Vieira
  • 2,784
  • 3
  • 24
  • 34
  • Thank you for you answer! It works! I have one more quick question though, in your answer, you use `_controller.update(newId)`. I previously used `GetX( builder: (controller) {` in my widget tree. Are these two methods different? and How? – BigPP Jun 08 '21 at 15:17
  • 3
    So there're 3 types of state management on Getx: Gex, Obx and GetBuilder, you can choose which one is better for your needs. I always used Obx cause i think easier and clear. And i feel easier to hear states changes on the widget too. You can read more about the differences here: https://github.com/jonataslaw/getx/blob/master/documentation/en_US/state_management.md#getbuilder-vs-getx-vs-obx-vs-mixinbuilder – Jorge Vieira Jun 08 '21 at 16:02
2

For those who may be using obs, you can do as follows:

In the controller, you can define

var postid = 0.obs

and from the view just add

controller.postid.value = 20;
Mostafa Wael
  • 2,750
  • 1
  • 21
  • 23