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

问题描述

我有两个页面:HomePageDetailsPage 以及相关的 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"],);
                },);
            },),);
  }
}

HomeController

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),);
  }
}

DetailsController

class DetailsController extends GetxController {
  final taskDetail = ''.obs;

  @override
  void onInit() {
    super.onInit();
    taskDetail.value = Get.arguments;
  }
}

我创建了一个 AppDependencies 类来初始化依赖项(控制器、存储库、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,你可以在你的点击方法中使用这样的东西:

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 参数:

[builder()] 的内部寄存器会留在内存中重新创建 如果已使用 [Get.delete()] 删除了 Instance,则为 Instance。 因此,以后对 [Get.find()] 的调用将返回相同的实例。

,

使用绑定更新答案:

您可以更好地控制控制器如何以及何时使用绑定和智能管理进行初始化。因此,如果每次访问页面时都需要 onInit 触发,则可以使用绑定来实现。为您的详细信息页面设置专用绑定类。

class DetailsPageBinding extends Bindings {
  @override
  void dependencies() {
    // any controllers you need for this page you can lazy init here without setting fenix to true
  }
}

如果您尚未使用 GetMaterialApp 而不是 MaterialApp,则需要这样做。我建议在您的页面上抛出 static const id = 'details_page';,这样您就不必为了路由而弄乱原始字符串。

GetMaterialApp 的基本示例如下所示。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: HomePage.id,title: 'Material App',getPages: [
        GetPage(name: HomePage.id,page: () => HomePage()),// adding the new bindings class in the binding field below will link those controllers to the page and fire the dependancies override when you route to the page

        GetPage(name: DetailsPage.id,page: () => DetailsPage(),binding: DetailsPageBinding()),],);
  }
}

然后您需要通过

进行路由
Get.toNamed(DetailsPage.id)

原答案:

fenix: true 添加到您的惰性初始化;查看lazyPut 上的文档。

Get.lazyPut(() => HomeController(repository: Get.find()),fenix: true);
,

您需要在GetMaterialApp中绑定所有控制器和add。

您面临这个问题是因为当时您使用 back 时它会删除或删除控制器,例如:[GETX] "LoginController" onDelete() 调用

为防止此问题,您需要创建InitialBinding

初始绑定

class InitialBinding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => LoginController(LoginRepo()),fenix: true);
    Get.lazyPut(() => HomeController(HomeRepo()),fenix: true);
  }
}

在 Main 方法中:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Get.put(AppController());
    return GetMaterialApp(
      title: StringConst.APP_NAME,debugShowCheckedModeBanner: false,defaultTransition: Transition.rightToLeft,initialBinding: InitialBinding(),theme: ThemeData(
        primarySwatch: ColorConst.COLOR,visualDensity: VisualDensity.adaptivePlatformDensity,),initialRoute: RoutersConst.initialRoute,getPages: routes(),);
  }
}

谢谢

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...