Search code examples
flutterflutter-getx

Flutter GetX controller not calling method when revisit the app screen


I am new to the Flutter GetX package and facing problem when using the flutter GetX package. I have several app screens where one screen for listing all the products from the database.

In my product controller, I am fetching all the data from the database and showing with listview like as given code below and It's working fine.

Problem: When I'm inserting a new record from another controller and come back to the product list controller it'll not showing newly added data. Actually this time onInit method won't fire.

Controller code

class ProductIndexCtrl extends GetxController {
    
    var products = [].obs;

    @override
    void onInit() {
     super.onInit();
     getAll();
    }

    void getAll() {
      Product.getAll().then((jsonList) {
        products.value = Product.fromJsonList(jsonList);
      });
    }
}



class ProductCreateCtrl extends GetxController {
    
     void saveData(Product product) {
        ...
        ...

        //after successful insert
        Get.toNamed('productIndex');

     }

}

Product index screen

final ctrl = Get.put(ProductIndexCtrl());

GetX<ProductIndexCtrl>(builder: (controller) {
    return _listview(controller.products);
}

Widget _listview(data) {
    ...
    ...
}

Solution

  • As the GetX dependency manager controls the lifecycle of dependencies, you should not manually call them. It's GetX's responsibility when to call them.

    Therefore you need to manually call getAll() method of your ProductIndexCtrl controller inside the saveData() method of your ProductCreateCtrl like:

    saveData(Product product){
      .... 
      ....
      final indexCtrl= Get.find<ProductIndexCtrl>();
      indexCtrl.getAll();
    
    }