OBS variables

  • Steps

    obs stands for "observable." It's a part of GetX's reactive programming paradigm that allows you to create reactive variables and update the UI automatically whenever these variables change.

    The obs modifier converts a variable into a reactive object. When the value of the observed object changes, it automatically triggers a re-rendering of the UI that relies on that object.

    1. Primitive types:

    
    import 'package:get/get.dart';
    
    void main() {
      var count = 0.obs; // Making count observable
      print(count.value); // Accessing the value of the observable
      count.value++; // Updating the value of the observable
    }
    
    

    2. List:

    
    import 'package:get/get.dart';
    
    void main() {
      var myList = <String>[].obs; // Making a List observable
      myList.add('Hello'); // Updating the observable List
    }
    
    

    3. Map:

    
    import 'package:get/get.dart';
    
    void main() {
      var myMap = <String, int>{}.obs; // Making a Map observable
      myMap['key'] = 10; // Updating the observable Map
    }
    
    

    4. Custom class:

    
    import 'package:get/get.dart';
    
    class Person {
      var name = 'John'.obs; // Making a property of a custom class observable
    }
    
    void main() {
      var person = Person();
      print(person.name.value); // Accessing the value of the observable property
      person.name.value = 'Alice'; // Updating the value of the observable property
    }