GetBuilder

  • Steps

    GetBuilder is a widget provided by the GetX package, which is a powerful state management library. GetBuilder simplifies the process of updating UI components based on changes in a controller or state.

    1. pubspec.yaml

    
    dependencies:
      flutter:
        sdk: flutter
      get: ^4.1.4  # Ensure the version is updated
    
    

    2. screen

    
    
    import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    // Controller class using GetX
    class MyController extends GetxController {
      var count = 0.obs; // Observable variable
    
      void increment() {
        count.value++; // Increment count
      }
    }
    
    class MyApp extends StatelessWidget {
      final MyController myController = MyController();
    
      @override
      Widget build(BuildContext context) {
        return GetMaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('GetBuilder Example'),
            ),
            body: Center(
              child: GetBuilder<MyController>(
                init: myController, // Pass the controller instance
                builder: (controller) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Counter: ${controller.count}', // Access the observable variable
                        style: TextStyle(fontSize: 24),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          controller.increment(); // Call the function to increment count
                        },
                        child: Text('Increment'),
                      ),
                    ],
                  );
                },
              ),
            ),
          ),
        );
      }
    }
    
    
    

    In this example:

    GetBuilder is used to rebuild a part of the widget tree whenever the state in the controller changes.
    MyController is a simple GetX controller class containing an observable variable count and an increment function that updates the count.
    The GetBuilder widget listens to changes in MyController and rebuilds the UI whenever the count value changes.
    The UI contains a Text widget displaying the current count and an ElevatedButton that triggers the increment function when pressed.