GetX返回页面时自动销毁依赖问题求助
解决GetX路由返回后依赖被自动销毁的问题
核心原因
GetX默认会在路由出栈(比如调用Get.back())时,自动销毁与该路由绑定的所有依赖实例,这就是返回页面后CatalogDiseaseRemoteService、CatalogDiseaseRepository、GetCatalogDisease被销毁的原因。
可行解决方案
使用永久注入参数
在注入依赖时添加permanent: true,告诉GetX不要自动销毁这些实例:// 普通注入 Get.put(CatalogDiseaseRemoteService(), permanent: true); Get.put(CatalogDiseaseRepository(), permanent: true); Get.put(GetCatalogDisease(), permanent: true); // 懒加载注入(按需创建,销毁后可自动重建) Get.lazyPut(() => CatalogDiseaseRemoteService(), fenix: true); Get.lazyPut(() => CatalogDiseaseRepository(), fenix: true); Get.lazyPut(() => GetCatalogDisease(), fenix: true);其中
fenix: true是懒加载的特殊参数,当实例被销毁后,下次调用Get.find()时会自动重新创建,兼顾内存优化和可用性。绑定到全局/父级路由
如果这些依赖是多个页面共用的,不要在当前页面的Bindings中注入,而是创建全局绑定类,在App启动时初始化:class GlobalDependencies extends Bindings { @override void dependencies() { Get.put(CatalogDiseaseRemoteService()); Get.put(CatalogDiseaseRepository()); Get.put(GetCatalogDisease()); } } // 在main函数中配置 void main() { runApp(GetMaterialApp( initialBinding: GlobalDependencies(), routes: Routes.routes, // 其他配置项 )); }这样依赖会和根路由绑定,不会因为子页面的出栈操作被销毁。
手动控制依赖销毁时机
若需要更精细的控制,可以避免使用路由绑定的自动销毁逻辑,而是在合适的业务节点手动调用Get.delete()清理依赖,但这种方式需要自行维护生命周期,仅适合特殊场景。
内容的提问来源于stack exchange,提问作者Vishal Kumar
相关产品推荐
相关产品推荐

