Home > Software design >  Is there a difference between these ways of initializing values in Flutter using GetX?
Is there a difference between these ways of initializing values in Flutter using GetX?

Time:03-09

I can think of these 3 ways to initialize a value using GetX

Initializing at the declaration:

class StatusPane extends StatelessWidget {
  final HomeController homeController = Get.find();

  StatusPane({Key? key}) : super(key: key);

in the initializer list:

class StatusPane extends StatelessWidget {
  final HomeController homeController;

  StatusPane({Key? key}) : homeController = Get.find(), super(key: key);

or in the constructor

class StatusPane extends StatelessWidget {
  late final HomeController homeController;

  StatusPane({Key? key}) : super(key: key) {
    homeController = Get.find(); 
  }

Is there any significant difference between the 3? Like, can one way lead to crashes or bugs? Or is one way better performance wise? Or are they actually identical? Would it be any different if GetX wasn't used, like final HomeController homeController = HomeController() for example? Or is it pretty much down to personal preference?

CodePudding user response:

These 3 are identical but if you want a bit more performance you can get controller by a method or a getter like:

HomeController get controller => GetInstance().find<HomeController>()

this way, if you use Get.lazyPut instead of Get.put, HomeController and its lifecycle like onInit, onReady,etc gets called when neccessary. Otherwise it gets called immediately on constructor. Also there is a built in GetView class which you can use instead of StatelessWidget. it has a getter for controller

  • Related