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.
2
Answers
declaring controllers inside the
build()
method will cause to extra unnecessaryGet.put()
that will be called every time widget rebuilds.Instead of calling your controller as a variable like this:
You prevent this error and let your widget
const
, by using agetter
to get theGetxController
like this:You can use the controller now simply like you will do if you declare it as
final
, and your widget is stillconst
.Consider also using
GetView<T>
since it makes you achieve the same thing:You need just to specify the generic type of your controller with
GetView<T>
, then you can refer to that controller with thecontroller
getter without defining it manually.First of all, create a controller
Then create an instance of that controller inside the binding
Then extends your view with GetView and Assign HomeController to generic type of GetView
while navigating to that page you can initialize that binding too which will create the instance of that controller
you can access variables and functions residing inside HomeController by using controller. and controller. i.e. controller.connectButtonAction(), controller.userName