Search code examples
flutterdartflutter-getx

Flutter GetX: Where Does Get.put Go in a Widget?


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?


Solution

  • 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.