【问题标题】:Flutter GetX controller not calling method when revisit the app screen重新访问应用程序屏幕时,Flutter GetX 控制器未调用方法
【发布时间】:2021-09-06 03:44:36
【问题描述】:

我是 Flutter GetX 包的新手,在使用 Flutter GetX 包时遇到问题。我有几个应用程序屏幕,其中一个屏幕用于列出数据库中的所有产品。

在我的产品控制器中,我正在从数据库中获取所有数据并使用 listview 显示,如下面的代码所示,它工作正常。

问题:当我从另一个控制器插入新记录并返回到产品列表控制器时,它不会显示新添加的数据。其实这次onInit方法不会触发。

控制器代码

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');

     }

}

产品索引屏幕

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

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

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

【问题讨论】:

    标签: flutter flutter-getx


    【解决方案1】:

    由于 GetX 依赖管理器控制依赖的生命周期,因此您不应手动调用它们。何时调用它们是 GetX 的责任。

    因此,您需要在ProductCreateCtrlsaveData() 方法中手动调用ProductIndexCtrl 控制器的getAll() 方法,例如:

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

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2021-10-03
      • 2021-07-09
      • 2021-12-14
      • 2021-06-02
      • 2023-01-04
      相关资源
      最近更新 更多