free geoip
47

How to Use GetX for Simple State Management

Want to manage app state easily in Flutter using Android Studio? GetX is a powerful and lightweight solution that simplifies…

Want to manage app state easily in Flutter using Android Studio? GetX is a powerful and lightweight solution that simplifies state management without boilerplate code. In this tutorial, we’ll show you how to implement simple state management using GetX in a Flutter project.

Why GetX?
GetX is known for its simplicity, high performance, and minimal code. It supports reactive programming and works seamlessly with navigation and dependency injection. You can learn more about it from GetX official documentation.

GetX simple state management

Step-by-Step Guide Using Android Studio

Step 1: Add Dependency in pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.6

Run flutter pub get to install the package.

Step 2: Create the Controller Class

Create a controller to manage the counter state.

// counter_controller.dart
import 'package:get/get.dart';

class CounterController extends GetxController {
  var count = 0.obs;

  void increment() {
    count++;
  }
}

Step 3: Initialize Controller in Main File

Use Get.put() for dependency injection.

// main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'counter_controller.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final CounterController counterController = Get.put(CounterController());

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'GetX Simple State',
      home: CounterPage(),
    );
  }
}

Step 4: Build UI with Reactive State

Use Obx widget to rebuild UI when state changes.

// counter_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'counter_controller.dart';

class CounterPage extends StatelessWidget {
  final CounterController controller = Get.find();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('GetX Counter')),
      body: Center(
        child: Obx(() => Text(
              'Count: ${controller.count}',
              style: TextStyle(fontSize: 30),
            )),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: controller.increment,
        child: Icon(Icons.add),
      ),
    );
  }
}

Final Notes

With just a few lines of code, you’ve created a reactive app using GetX. This makes Flutter development cleaner and more maintainable especially useful for beginners or small apps.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *