How to check if a controller has put with Flutter GetX?
Asked Answered
S

2

11

I have the following code:

Get.put(DbController(HabitDao(AppDb())));

When I hot reload my app, I get the following error:

"WARNING (moor): It looks like you've created the database class AppDb multiple times. When these two databases use the same QueryExecutor, race conditions will occur and might corrupt the database."

I need to check if I have put a DbController before creating a new AppDb instance. I never had this problem while using the Provider package.

What is the best practice to solve this?

Shuman answered 13/7, 2021 at 12:2 Comment(0)
I
47

You can check with Get.isRegistered.

For your code:

bool test = Get.isRegistered<DbController>(tag: 'TagInPut');

If you didn't use tag, you can delete it.

bool test = Get.isRegistered<DbController>();
Iseult answered 20/7, 2021 at 8:35 Comment(0)
R
0

You may find this useful while writing widget test when you want to use your mocked controller instead of putting a controller in screen

late ParentProfileController controller;

  @override
  void initState() {
    if (Get.isRegistered<ParentProfileController>()) {
      controller = Get.find<ParentProfileController>();
    } else {
      controller = Get.put(ParentProfileController());
    }
    super.initState();
  }
Remontant answered 30/8, 2023 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.