Search code examples
flutterdartflutter-getx

How to use GetxController inside my view without removing the const keyword on the constructor


using Getx, when I have a GetxController and I want to use it inside my view UI, it required removing const on the widget constructor :

Controller :

class TestController extends GetxController {
// ...
}

View :

 class TextWidget extends StatelessWidget {
  const TextWidget({super.key}); //  throws error
   final controller = Get.put(TestController());
  
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

it throws an error on the const line :

> Can't define the 'const' constructor because the field 'controller' is initialized with a non-constant value.

so it requires me to delete the const, but since adding const is recommended for better performance, I want to let it there and use my controller.

I could shut down this error by declaring the controller inside the build() method, but I guess it's not a good idea.


Solution

  • declaring controllers inside the build() method will cause to extra unnecessary Get.put() that will be called every time widget rebuilds.

    Instead of calling your controller as a variable like this:

    final controller = Get.put(TestController());
    

    You prevent this error and let your widget const, by using a getter to get the GetxController like this:

    TestController get controller => Get.put(TestController());
    

    You can use the controller now simply like you will do if you declare it as final, and your widget is still const.

    Consider also using GetView<T> since it makes you achieve the same thing:

    class TextWidget extends GetView<TestController> {
      const TextWidget({super.key});
      @override
      Widget build(BuildContext context) {
        return Text("${controller.index}"); // use controller directly to access controller.
      }
    }
    

    You need just to specify the generic type of your controller with GetView<T>, then you can refer to that controller with the controller getter without defining it manually.