GetX in flutter (Simple and powerful State Management)
Implementing GetX in Flutter can significantly simplify state management, routing, and dependency injection in your application. GetX is a lightweight and powerful package that provides a combination of high-performance state management, intelligent dependency injection, and route management.
Example: Building a Simple Counter App
We will make a simple Counter App using GetX State Management to completely understand GetX implementation in Flutter.
1. Add GetX to Your Project
First, add the get
package to your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
get: ^4.6.5 # Check for the latest version on pub.dev
Note: Flutter Machine Learning & AI Courses
If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for a limited time
- Flutter & ML : Train Tensorflow Lite models for Flutter Apps
- Face Recognition and Detection in Flutter — The 2024 Guide
- Flutter & OCR — Build Document Scanner Clone in Flutter
- FlutterFlow for Beginners: Build “No Code” Apps in 2024
- Flutter & Google Gemini — Build Chatbots and Assistants in Flutter
- Train Image Classification Models & Build Smart Flutter Apps
- Build Gallery App Clone in Flutter With Circle To Search Feature
- Machine Learning for Flutter- The Complete 2024 Guide
- Build Flutter Apps Effortlessly with ChatGPT — Zero Coding
- Flutter & AI: Build Image & Art Generation Flutter App
2. Project Structure with GetX
Organizing your project using GetX typically involves:
- Views: UI components.
- Controllers: Handle business logic and state.
- Bindings: Manage dependencies.
- Routes: Define navigation paths.
Here’s a suggested structure:
lib/
│
├── main.dart
├── app/
│ ├── bindings/
│ │ └── home_binding.dart
│ ├── controllers/
│ │ └── home_controller.dart
│ ├── routes/
│ │ └── app_routes.dart
│ └── views/
│ ├── home_page.dart
│ └── second_page.dart
3. Navigation with GetX
GetX simplifies navigation without the need for BuildContext
.
1. Basic Navigation
Navigate to a new page:
Get.to(SecondPage());
Go back to the previous page:
Get.back();
2. Named Routes
Define named routes for better organization. Create a new class named as AppRoutes and declared navigations in it for all of your screens. Currently, we have two screens, so we add two navigations Home and Second page.
app/routes/app_routes.dart
// app_routes.dart
class AppRoutes {
static const HOME = '/';
static const SECOND = '/second';
}
Set up routes in GetMaterialApp
:
GetMaterialApp(
initialRoute: AppRoutes.HOME,
getPages: [
GetPage(
name: AppRoutes.HOME,
page: () => HomePage(),
binding: HomeBinding(),
),
GetPage(
name: AppRoutes.SECOND,
page: () => SecondPage(),
),
],
);
Navigate using named routes: Now you can use code below instead of Get.to(SecondPage());
Get.toNamed(AppRoutes.SECOND);
Now, we add GetMaterialApp in main.dart file and implement navigation by adding GetPages in it.
3. main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'app/routes/app_routes.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'GetX Counter App',
initialRoute: AppRoutes.HOME,
getPages: [
GetPage(
name: AppRoutes.HOME,
page: () => HomePage(),
binding: HomeBinding(),
),
GetPage(
name: AppRoutes.SECOND,
page: () => SecondPage(),
),
],
);
}
}
Finally your main.dart looks like this.
4. Binding with GetX
In GetX, Bindings play a crucial role in managing the dependencies of your application, ensuring that the necessary controllers and services are properly instantiated and available when needed.
app/bindings/home_binding.dart
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
class HomeBinding extends Bindings {
@override
void dependencies() {
Get.lazyPut<HomeController>(() => HomeController());
}
}
Get.lazyPut
: A method provided by GetX for lazy dependency injection. It registers the HomeController
so that it is instantiated only when it's first used.
5. Controller with GetX
A controller extends GetxController
and holds the state and business logic. It includes all your business logic like methods and variables you need.
app/controllers/home_controller.dart
import 'package:get/get.dart';
class HomeController extends GetxController {
var count = 0.obs;
void increment() {
count++;
}
}
In above code, we make a observer variable with .obs, this observer variable is used for reactively update the UI.
6. Views with GetX
app/views/home_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
import '../routes/app_routes.dart';
class HomePage extends StatelessWidget {
// Retrieve the controller
final HomeController controller = Get.find();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Counter Home'),
),
body: Center(
child: Obx(() => Text(
'Clicks: ${controller.count}',
style: TextStyle(fontSize: 30),
)),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: controller.increment,
heroTag: 'increment',
child: Icon(Icons.add),
),
SizedBox(height: 10),
FloatingActionButton(
onPressed: () => Get.toNamed(AppRoutes.SECOND),
heroTag: 'navigate',
child: Icon(Icons.navigate_next),
),
],
),
);
}
}
Within the HomePage
, the controller is accessed using Get.find()
, which retrieves the instance of HomeController
that was instantiated by the binding.
We use Obx widget to access the observer variable count, we made in our controller for reactively update the UI. Because if we don’t get observer variable within Obx widget, then UI is not updated as observer variable changed.
app/views/second_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
// No need for AppBar if not desired
appBar: AppBar(
title: Text('Second Page'),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Get.back(),
),
),
body: Center(
child: Text(
'This is the second page',
style: TextStyle(fontSize: 25),
),
),
);
}
}
Running the App:
flutter run
You should see a home page displaying the number of clicks. Pressing the “+” button increments the count, and the navigate button takes you to the second page.
Conclusion
GetX is a versatile and efficient package that can greatly enhance your Flutter development workflow. By providing simple and powerful tools for state management, navigation, and dependency injection, GetX allows you to build scalable and maintainable applications with ease.
Key Benefits of Using GetX:
- Simplicity: Easy to learn and implement.
- Performance: Minimal overhead ensures high performance.
- Flexibility: Supports multiple paradigms (MVC, MVVM, etc.).
- All-in-One Solution: Combines state management, routing, and DI.
Note: Flutter Machine Learning & AI Courses
If you want to build Machine Learning and AI based smart Flutter apps then check our Mobile Machine Learning courses on udemy. Avail 92% off with coupon code “MOBILEMLAI” only for a limited time
- Flutter & ML : Train Tensorflow Lite models for Flutter Apps
- Face Recognition and Detection in Flutter — The 2024 Guide
- Flutter & OCR — Build Document Scanner Clone in Flutter
- FlutterFlow for Beginners: Build “No Code” Apps in 2024
- Flutter & Google Gemini — Build Chatbots and Assistants in Flutter
- Train Image Classification Models & Build Smart Flutter Apps
- Build Gallery App Clone in Flutter With Circle To Search Feature
- Machine Learning for Flutter- The Complete 2024 Guide
- Build Flutter Apps Effortlessly with ChatGPT — Zero Coding
- Flutter & AI: Build Image & Art Generation Flutter App