Flutter GetX Get.back() 或 navigator.pop() 从内存中删除 Controller 并且无法重新创建它

标签 flutter dart dependency-injection getx flutter-getx

我有两个页面: HomePage DetailsPage 和关联的 GetxControllers
主页 :

class HomePage extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('HomePage')),
      body: Container(
        child: Obx(
          () => ListView.builder(
            itemCount: controller.task.length,
            itemBuilder: (context, index) {
              return ListTile(
                leading: Text('${index + 1}'),
                title: Text(controller.task[index]["name"]),
                onTap: () {
                  Get.to(
                    DetailsPage(),
                    arguments: controller.task[index]["name"],
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}
家庭 Controller :
class HomeController extends GetxController {
  final TaskRepository repository;
  HomeController({@required this.repository}) : assert(repository != null);

  final _task = [].obs;
  set task(value) => this._task.assignAll(value);
  get task => this._task;

  onInit() {
    super.onInit();
    getAllTask();
  }

  getAllTask() {
    repository.getAll().then((value) => task = value);
  }
}
如您所见, HomeController 依赖于 TaskRepository ,它是一个模拟存储库。
还有我的 DetailsPage :
class DetailsPage extends GetView<DetailsController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          GestureDetector(
            onTap: () {
              Get.back();
            },
            child: Row(
              children: [
                Icon(Icons.arrow_back),
                Text('Go Back'),
              ],
            ),
          ),
          Expanded(
            child: Center(
              child: Obx(
                () => Text(controller.taskDetail.value),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
详细信息 Controller :
class DetailsController extends GetxController {
  final taskDetail = ''.obs;

  @override
  void onInit() {
    super.onInit();
    taskDetail.value = Get.arguments;
  }
}
我创建了一个 AppDependencies 类来初始化依赖项( Controller 、存储库、API 客户端等):
class AppDependencies {
  static Future<void> init() async {
    Get.lazyPut(() => HomeController(repository: Get.find()));
    Get.lazyPut(() => DetailsController());
    Get.lazyPut(() => TaskRepository(apiClient: Get.find()));
    Get.lazyPut(() => TaskClient());
  }
}
我通过在 AppDependencies.init() 上调用 main() 来初始化所有依赖项:
void main() async {
  await AppDependencies.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}
HomePage
DetailsPage first time
Going back to HomePage and then Going again to DetailsPage
正如您在第三张图片中看到的,从 DetailsPage 返回到 HomePage 并返回到 DetailsPage 会导致异常:
"DetailsController" not found. You need to call "Get.put(DetailsController())" or "Get.lazyPut(()=>DetailsController())"
但我已经在 main() 上这样做了。我也尝试过使用 Get.put() 而不是 Get.lazyPut() 但我发现对于 Get.put() 任何其他依赖项的任何依赖项都必须在依赖项之前注册。例如,HomeController 依赖于 TaskRepository 所以 TaskRepository 必须在 HomeController 之前,如果使用 Get.put() 像:
Get.put(TaskRepository());

Get.put(HomeController());
这不是我想要的,因为我不想手动跟踪之前的内容。
我发现这会导致是否有后退按钮(几乎每个页面都有)。
我在这里做错了什么?

最佳答案

如果你不想使用 fenix = true ,你可以在你的 click 方法中使用这样的东西:

try {
   ///find the controller and 
   ///crush here if it's not initialized
   final authController = Get.find<AuthController>();

   if(authController.initialized)
     Get.toNamed('/auth');
   else {
     Get.lazyPut(() => AuthController());
     Get.toNamed('/auth');
   }

} catch(e) {

   Get.lazyPut(() => AuthController());
   Get.toNamed('/auth');
}
关于内存,重要的是要考虑 fenix 参数:

The internal register of [builder()] will remain in memory to recreate the Instance if the Instance has been removed with [Get.delete()]. Therefore, future calls to [Get.find()] will return the same Instance.

关于Flutter GetX Get.back() 或 navigator.pop() 从内存中删除 Controller 并且无法重新创建它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66138542/

相关文章:

flutter - 如何在Flutter中的AnimationController.repeat()之间增加一些延迟

firebase - 未定义类 'FirebaseUser'

flutter - 如何在不改变 AppBar 的情况下更改 TabBar 的背景颜色?

android - 如何在 SmartRefresher 上实现 FutureBuilder - Flutter Dart

c# - .NET Core IServiceScopeFactory.CreateScope() 与 IServiceProvider.CreateScope() 扩展

android - Android Studio在运行Flutter项目中出现问题

flutter - 在 flutter 中格式化按钮和嵌套ListView

api - 如何从Api请求响应中检索动态值

c# - 依赖注入(inject)和类继承

iOS Storyboard和注入(inject)属性