Flutter State Manageme nt Using GetX H T T P S : / / W W W . B A C A N C Y T E C H N O L O G Y . C O M /
Introduction
Whenever we start building any application in a flutter, we must decide which state management we need to use. It would be easier for you to make this decision with this blog. Here, in this tutorial: Flutter state management using GetX, I would like to explain GetX, a powerful flutter framework.
What is GetX?
State management allows you data transferring within the application. And whenever data is passed, the application’s state is updated, consequently rebuilding the system. Thus, developers have to be particularly careful about managing the state of an application because state updation may sometimes seem costly for a complex application. Flutter traditionally provides Stateful Widget to manage states in applications. However, we need to deal with a few limitations when using Stateful Widgets
To overcome the limitations, we can choose Flutter state management using GetX. GetX is a powerful and lightweight solution provided by Flutter to manage states and their updation. It provides: High-performance state management Intelligent dependency injection Quick and practical route management
Why GetX?
So, let’s dive a little deeper into why we need GetX to manage the state in the flutter app. GetX improves flutter application in three different criteria: Productivity: Developers can easily implement state management with the help of straightforward syntax. No matter how complex a code snippet can be, you can save time with GetX. It increases productivity by decreasing the development time delivering maximum performance. Organization and Readability: GetX decouples the View. It provides easy and uncomplicated syntax, consequently increasing the readability and format of the business logic.
Performance: As mentioned above, GetX focuses on how minimum resources can be consumed, which can help in improving the application performance. It doesn’t use ChangeNotifier or Streams. Look at the below RAM chart depicting various state managers.
Enough of the theory part. Let’s move forward in our Flutter state management using GetX tutorial and implement it in our application.
Install GetX
flutter pub add get
Run the above command in Android studio/vs code’s terminal, and it will add the latest GetX plugin to pubspec.yaml. We are going to cover three sections in this further tutorial 1. State management for basic counter app 2. Navigation using GetX 3. Inflating UI components without context
Put forward your requirements, and we will provide solutions! Develop best, cost-effective, and high-performance Flutter applications with Bacancy! Stop wasting your time and connect us to hire Flutter developer!
Flutter State Management using GetX
Here I will create one counter app by separating UI logic and business logic using a controller, and I would use Obx for this. Don’t worry if you are not aware of all this; I am explaining all these in detail one by one.
You can see the project structure I have created using the recommended GetX pattern, with a view, controller, and binding class. View class handles the code for inflating the UI, which will appear on the screen
The binding class would be associated with a particular page, and in that class, we can instantiate controller classes. In controller class, we can define variables and business logic functions, in our case increment function. Also, In the main.dart, we have declared GetMaterialApp not MaterialApp so we can use all the functionalities of GetX framework.
CounterController class
class CounterController extends GetxController { final count = 0.obs; void increment() { count.value++; } } Here I have declared the count variable with .obs, which means count is observable, and whenever there is a change in this value, we can listen to that value via controller class..
CounterBinding class class CounterBinding extends Bindings { @override void dependencies() { Get.lazyPut( () => CounterController(), ); } }
Here I have declared the count variable with .obs, which means count is observable, and whenever there is a change in this value, we can listen to that value via controller class..
CounterView class class CounterView extends GetView { @override Widget build(BuildContext context) { final CounterController counterController = Get.put(CounterController()); return Scaffold( appBar: AppBar( title: Text('Counter'), centerTitle: true, ),
body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Obx(() => Text( "Counter value is ${counterController.count}", style: TextStyle(fontSize: 25), ), ), SizedBox(height: 16), TextButton( style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue), ), onPressed: () { counterController.increment(); }, child: Text('Increment', style: TextStyle(fontSize: 14, color: Colors.white)), ), ], ), ), ); } }
final CounterController counterController = Get.put(CounterController()); Using the above syntax in the build method, I have defined the controller class. Text button will call increment method defined in controller class and Text which will show the updated value of count. But the main thing you can see is the text widget is wrapped with Obx, which means it can get the value of the observable variable; without Obx, the value would not get reflected.
Here I have used one simple example of counter application to understand all the classes, structure, and state management easily. We can achieve many more using GetX using following this observable pattern and writing cleaner code. Let’s dive into the navigation part.
Navigation using GetX
In the screenshot attached in the state management block, we have also created a page name home. So let’s say we need to go to the home page from the counter class on one button click. We can simply call the GetX navigation block, as shown below.
Get.to(HomeView()); Pretty simple. Isn’t it? Rather than calling up a lot of boilerplate code, we can simply call this and move to a different screen. Moreover, there are different options to redirect to another page too. For instance, you can simply replace the home screen with a currently open screen below. It means the current screen which would get replaced won’t be in the stack.
Get.off(HomeView()); And, if we need to remove all previous stacks, we can call Get.off(HomeView()); Get.offAll(HomeView()); Apart from that, we can pass data between routes and show animation before opening another route and open a screen as a dialog using GetX. Now let’s move to our final point of Inflating UI components without context.
Inflating UI Components without Context
Traditionally, to open a dialog or bottom sheet. If you have a separate file that handles common widgets, we also need to pass context to that class. But with GetX, it is not the case. We can simply inflate that kind of UI block without using context and in an easier way.
To show snackbar Get.snackbar('This is snackbar', 'This is snackbar message', backgroundColor: Colors.red);
Traditionally, to open a dialog or bottom sheet. If you have a separate file that handles common widgets, we also need to pass context to that class. But with GetX, it is not the case. We can simply inflate that kind of UI block without using context and in an easier way.
To show snackbar Get.snackbar('This is snackbar', 'This is snackbar message', backgroundColor: Colors.red);
To show dialog Get.defaultDialog( title: 'This is dialog', middleText: 'This is middle text', buttonColor: Colors.green, textCancel: "cancel", textConfirm: "confirm");
To show bottom sheet Get.bottomSheet( Container( child: Wrap( children: [ ListTile( leading: Icon(Icons.wb_sunny_outlined), title: Text("Light theme"), onTap: () => {Get.changeTheme(ThemeData.light()) },
), ListTile( leading: Icon(Icons.wb_sunny), title: Text("Dark theme"), onTap: () => {Get.changeTheme(ThemeData.dark())}, ) ], ), ), backgroundColor: Colors.green );
I think this is it for GetX. You can go through the below official link to explore more about GetX. https://pub.dev/packages/get With the Git Cli plugin, you can make the project structure more trouble-free. You can check out the link below. https://pub.dev/packages/get_cli
Conclusion
That’s it for Flutter state management using GetX tutorial. If you are a flutter enthusiast, the Flutter tutorials page is for you! Try the tutorials and start implementing them in your application. Write us back if you have any suggestions, queries, or questions.
Thank You !
www.bacancytechnology.com