GetX is a useful widget when you want to inject the controller into
the init property, or when you want to retrieve an instance of the controller within the widget itself.
In other cases, you can insert your widget into an Obx, which receives a widget function.
This looks much easier and clearer, just like this...
class Home extends StatelessWidget {
final controller = Get.put(Controller());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("counter")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(() => Text(
'clicks: ${controller.count}',
)),
ElevatedButton(
child: Text('Next Route'),
onPressed: () {
Get.to(Second());
},
),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: controller.increment(),
),
);
}
}
class Second extends StatelessWidget {
final Controller ctrl = Get.find();
@override
Widget build(context){
return Scaffold(body: Center(child: Text("${ctrl.count}")));
}
}