10

我有两个页面: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"],
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

家庭控制器

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

详细信息控制器

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

主页

详情页第一次

返回主页,然后再次转到详细信息页面

正如您在第三张图片中看到的那样,从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());

这不是我想要的,因为我不想手动跟踪之前的内容。我发现这会导致如果有一个后退按钮(几乎每个页面都有)。

我在这里做错了什么?

4

3 回答 3

6

如果您不想使用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参数很重要:

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

于 2021-06-09T15:21:19.800 回答
3

您需要绑定所有控制器和GetMaterialApp中的添加。

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

为了防止这个问题,您需要创建InitialBinding

初始绑定

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

在主要方法中:

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

谢谢

于 2021-03-30T02:45:23.310 回答
1

使用绑定更新答案:

您可以更好地控制控制器如何以及何时通过绑定和智能管理进行初始化。因此,如果您需要在每次访问页面时触发 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);
于 2021-02-10T15:54:08.560 回答