getx: 未找到 AddController。您需要调用 Get.put(AddController())

getx: AddController not found. You need to call Get.put(AddController())

我在我的项目中使用 getx,我正在尝试使用 getx 依赖注入。我创建 AddBinding class:

class AddBinding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut<AddController>(
      () => AddController(
        AddRepository(),
        Get.find<DialogService>(),
      ),
    );
  }
}

并且在 GetPage 中我添加了这个绑定,例如:

GetPage(
  name: Routes.ADD,
  page: () => AddPage(),
  binding: AddBinding(),
),

现在在我的主页上

class HomePage extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // title: const Text('HomePage'),
        title: TabBar(
          controller: controller.controller,
          tabs: controller.myTabs,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: TabBarView(
          controller: controller.controller,
          physics: const NeverScrollableScrollPhysics(),
          children: [
            Container(),
            Container(),
            Container(),
            AddPage(),
          ],
        ),
      ),
    );

我添加我的AddPage。这是添加页面:

class AddPage extends GetView<AddController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(child: Container()),
      floatingActionButton: FloatingActionButton(
        elevation: 0.0,
        backgroundColor: const Color(0xFFE57373),
        onPressed: () async {
          controller.showAddDialog();
        },
        child: const Icon(Icons.add),
      ),

    );
  }
}

但是当我点击 fab controller.showAddDialog(); 时出现错误: E/flutter (26699): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: "AddController" not found. You need to call "Get.put(AddController())" or "Get.lazyPut(()=>AddController())" E/flutter (26699): #0 GetInstance.find package:get/…/src/get_instance.dart:332 E/flutter (26699): #1 Inst.find package:get/…/src/extension_instance.dart:70

这是添加控制器:

class AddController extends GetxController {
  final AddRepository repository;
  final DialogService dialogService;
  AddController(this.repository, this.dialogService);

  void showAddDialog() {

  }
}

有什么问题?

这是 MaterialApp:

GetMaterialApp(
        debugShowCheckedModeBanner: false,
        initialRoute: Routes.INITIAL,
        theme: appThemeData,
        defaultTransition: Transition.fade,
        initialBinding: MainBinding(),
        locale: const Locale('fa', 'IR'),
        translationsKeys: AppTranslation.translations,
        getPages: AppPages.pages,
      ),
    ),
  );

您没有使用 GetX 导航系统导航至 AddPage。您正在做的是从同一页面(主页)切换选项卡。因此 AddBinding class 对它没有影响。它只会在您使用 Get.toNamed(Routes.ADD)Get.to(()=>AddPage(), binding: AddBinding()).

导航时生效

一种解决方法是将您的 AddBinding 依赖项放到选项卡父项(主页)绑定中,您将 HomeController