You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:如何让ConnectionManagerController始终保持可用?

解决GetX中ConnectionManagerController页面跳转后被销毁的问题

问题出在你用了Get.lazyPut初始化全局控制器——这个方法默认会在控制器不再被任何页面监听/引用时自动销毁,而全局的网络检测控制器需要长期驻留内存,所以得调整初始化方式:

方案一:改用Get.put永久初始化

把ControllerBinding里的lazyPut替换成Get.put,这个方法会将控制器永久存入GetX的依赖容器,不会自动销毁:

class ControllerBinding extends Bindings {
  @override
  void dependencies() {
    // 替换原lazyPut代码
    Get.put<ConnectionManagerController>(ConnectionManagerController());
    // 异步初始化的话用putAsync
    // Get.putAsync<ConnectionManagerController>(() async => await ConnectionManagerController.init());
  }
}

方案二:给lazyPut添加fenix: true参数

如果必须用延迟初始化,开启fenix模式后,控制器被销毁后再次调用Get.find时会自动重新初始化,避免找不到的错误:

Get.lazyPut<ConnectionManagerController>(
  () => ConnectionManagerController(),
  fenix: true, // 开启凤凰模式,自动重建已销毁的控制器
);

额外注意

不要在任何地方手动调用Get.delete<ConnectionManagerController>(),这会主动销毁控制器,导致后续无法获取。

内容的提问来源于stack exchange,提问作者WatsMyName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:31:05