OBX

  • Steps

    It provides a simple and reactive way to update your UI when the state changes. The Obx widget is used to listen to an observable variable or Rx value and rebuilds the UI whenever that value changes.

    pubspec.yaml

    
                          dependencies:
                            flutter:
                              sdk: flutter
                            get: ^4.6.1 # Use the latest version available
    
    
                          

    view screen

    
    
                          import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyController extends GetxController {
      // Define an observable variable
      var count = 0.obs; // ".obs" makes the variable observable
    
      // Method to increment count
      void increment() {
        count.value++; // Update the value of the observable variable
      }
    }
    
    class MyApp extends StatelessWidget {
      final MyController controller = Get.put(MyController()); // Create an instance of the controller
    
      @override
      Widget build(BuildContext context) {
        return GetMaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('GetX Obx Example'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Observe the 'count' variable and rebuild the UI whenever it changes
                  Obx(() => Text(
                        'Count: ${controller.count.value}', // Access the value using '.value'
                        style: TextStyle(fontSize: 24.0),
                      )),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      // Call the increment method from the controller
                      controller.increment();
                    },
                    child: Text('Increment'),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }