flutterflutter-getx

What is the different between onInit and onReady and constructor of controller?


i want to understand complete way about this 3 methods Calling class constructor, init, onready

i fould some users user different approch to fetch data, sometime oninit sometime onready and sometime by class constructor

what are the differences?

class TransactionProvider extends GetxController {
  List<TransactionModel> _transactions = [];
  

  TransactionProvider() {
 
 fetchTransaction();
   
  }
  
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
fetchTransaction();

  }
  
  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
fetchTransaction();
 
  }
}

which willl


Solution

  • onInit()

    onReady()

    constructor()

    class TransactionProvider extends GetxController {
      List<TransactionModel> _transactions = [];
      final Dependency _dependency;
      
      // Constructor for dependency injection
      TransactionProvider(this._dependency) {
        // Simple initialization
        print('TransactionProvider Constructor');
      }
      
      @override
      void onInit() {
        super.onInit();
        // Initialize variables 
        //perform initial data fetch
    
        fetchTransaction();
        print('TransactionProvider onInit');
      }
      
      @override
      void onReady() {
        super.onReady();
        // Perform UI-dependent operations
        showWelcomeSnackbar();
        print('TransactionProvider onReady');
      }
      
      void fetchTransaction() async {
        // Asynchronous data fetching
        _transactions = await _dependency.getTransactions();
      }
      
      void showWelcomeSnackbar() {
        // Show a snackbar
        Get.snackbar('Welcome', 'Transactions loaded!');
      }
    }