Home > Software engineering >  Flutter GetX: Where Does Get.put Go in a Widget?
Flutter GetX: Where Does Get.put Go in a Widget?

Time:08-27

I am new to GetX and am trying to learn how to use it. I have read different tutorials that inject the controller outside of the widget's build method, and others that put it inside it.

class MyWidget extends StatelessWidget{
  const MyWidget({Key? key}) : super(key:key);

  //Outside...
  final controller = Get.put(Controller()); //<---

  @override
  Widget build(BuildContext context) {
    //Inside...
    final controller = Get.put(Controller()); //<---

    return Obx(
      () => Text(controller.name)
    );
  }
}

Is there a difference between those two locations? If so, why?

Also, where should it go in a StatefulWidget? It seems it should not go inside the build method because it causes a stack overflow error for me.

Does the location of Get.put() matter inside a widget?

CodePudding user response:

The normal way is to put the controller outside the widget, so it will be created once. if you but it inside the widget a new instance of the controller will be created each time you refresh (update) the widget. Also, with GetX there is no need to use StatefulWidget.

CodePudding user response:

When you put it inside the build method, it will create a new instance every time the widget is rebuilt, so it is better to but it outside and in most cases I think you do not need to use StatefulWidgetwith GetX even in animation.

  • Related