How to manage state in Flutter using GetX State Management Library?
Introduction to GetX State Management
GetX simplifies dependency injection, state management, and routing in Flutter applications. In this blog, we’ll focus on dependency management in GetX, where you can manage how services and controllers are created, injected, and accessed throughout your app.

What is Dependency Management?
Dependency management refers to how objects or services are injected into different parts of the application. Instead of creating instances of classes throughout your widgets, you define these dependencies centrally using GetX, making it easy to manage services such as APIs, databases, or controllers. This helps in achieving decoupled architecture and simplifies the code.


GetX offers various ways to manage dependencies, such as:
- Permanent Injection: Ensures the dependency stays alive throughout the app lifecycle.
- Lazy Loading: Dependency is created when it is first accessed, improving app performance.
- Factory Method: Creates a new instance of the dependency each time it is accessed.
Setting Up GetX in Your Flutter Project
Before you can use GetX, you’ll need to set it up in your Flutter project.
- Add GetX to
pubspec.yaml
: First, add the GetX package to your project by updating thepubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
get: ^4.6.5
Then, run flutter pub get
to install the dependencies.
2. Create an API Service
To demonstrate dependency management, let’s first create a simple ApiService class that simulates an API call.
import 'package:get/get.dart';
class ApiService extends GetxService {
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data from API';
}
}
The ApiService
class is a GetX service, which will simulate fetching data from an API.
3. Inject the Service
Next, inject the service in the main.dart
file using Get.lazyPut()
. This ensures that the ApiService will only be created when first needed.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'api_service.dart';
import 'home_page.dart';
void main() {
Get.lazyPut<ApiService>(() => ApiService());
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: HomePage(),
);
}
}
4. Access the Dependency
Once injected, you can access the ApiService in any widget using Get.find()
.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'api_service.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Fetch the ApiService
final ApiService apiService = Get.find();
return Scaffold(
appBar: AppBar(title: Text("GetX Dependency Management")),
body: Center(
child: FutureBuilder<String>(
future: apiService.fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasData) {
return Text(snapshot.data ?? 'No Data');
} else {
return Text('Error fetching data');
}
},
),
),
);
}
}
This code demonstrates how to inject and access the ApiService in a Flutter widget using GetX. The FutureBuilder widget displays data fetched from the API service.
Key Features of GetX Dependency Management
- Lazy Loading of Services
In the above example, theApiService
is injected usingGet.lazyPut()
. This means that the service is only instantiated when it’s first accessed, making your app more efficient in terms of memory usage. - Service Management
With GetX, you can define global services that persist throughout the app’s lifecycle. For instance, services likeApiService
,AuthService
, andDatabaseService
can be initialized at the start and accessed anywhere in the app usingGet.find()
. - Permanent Instances
You can also ensure that certain services are always available by usingGet.put()
.
Example: Managing Multiple Dependencies
Let’s see how to manage multiple dependencies like width animation and color change using GetX.
- Multiple Dependency Injection Example
In this example, we create two animations and manage their dependencies using GetX. We will animate the width of a container and its color simultaneously.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class MultiTweenExample extends StatefulWidget {
@override
_MultiTweenExampleState createState() => _MultiTweenExampleState();
}
class _MultiTweenExampleState extends State<MultiTweenExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _widthAnimation;
late Animation<Color?> _colorAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
_widthAnimation = Tween<double>(begin: 100, end: 300).animate(_controller);
_colorAnimation = ColorTween(begin: Colors.red, end: Colors.blue).animate(_controller);
_controller.forward();
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
width: _widthAnimation.value,
height: 100,
color: _colorAnimation.value,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
Conclusion
GetX simplifies dependency management in Flutter, making your application architecture clean and scalable. By using Get.lazyPut()
or Get.put()
, you can easily inject dependencies like API services, controllers, and more. GetX provides powerful tools for state management, navigation, and dependency injection, helping Flutter developers create more efficient and organized apps.
Mastering dependency management in GetX is essential for building scalable Flutter applications. By utilising lazy loading, permanent instances, and clear separation of concerns, your app becomes easier to maintain and test.
Explore Other Flutter Topics…
- Introduction to Flutter and Dart
- Why choose Flutter
- Installing Flutter On Your Windows Mac And Linux System
- Your first Flutter app
- Flutter project structure
- Building blocks of Flutter
- Stateful vs. Stateless Widgets Explained
- Flutter layout system
- Flutter text widget
- Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
- Handling User Input with Flutter Forms
- Container class in Flutter
- Flutter Navigation
- Flutter – Pass Data One Screen To Another Screen
- Managing Device Orientation in Flutter
- Stateful widget lifecycle in Flutter
- Future of Flutter
- Flutter Themes
- Flutter Animations
- Flutter AppBar Customization
- ListView in Flutter
- Flutter GridView
- Flutter Expanded Widget
- Flutter BottomNavigation Bar
- Floating Action Button
- Drawer Widgets in Flutter
- Form Validation in Flutter
- Flutter TextField
- Adding AdMob ads to a Flutter app
- Building Flutter Web & Desktop Applications
- What is Async and Await in Flutter
- HTTP requests in Flutter
- Parsing JSON in Flutter
- Tinder-Style Swipe Cards in Flutter
- Flutter Tic Tac Toe Game Tutorial
- Flutter Login UI Tutorial
- Flutter Card Widget Tutorial
- Flutter music player app tutorial
- Flutter introduction screens
- Shared Preferences in Flutter
- SQLite Database in Flutter
- Firebase Authentication in Flutter
- Firebase Firestore in Flutter
- Push Notifications in Flutter
- Handling File Uploads in Flutter
- Responsive Design in Flutter
- Provider in Flutter
- Riverpod in Flutter
- Flutter BLoC Pattern Tutorial