skip to Main Content

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

2

Answers


  1. onInit()

    • Get called when the controller is created i.e. memory is allocated to the widget/controller.
    • Use this for initialize something for the controller.

    onReady()

    • Called 1 frame after onInit() i.e. Get called after the widget is rendered – on the screen.
    • Perfect place for events like snackBar, dialogs or async request.

    constructor()

    • Use the constructor for straightforward, synchronous initialization that does not involve heavy lifting or async operations
    • Ideal for injecting dependencies or setting initial values
    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!');
      }
    }
    
    
    Login or Signup to reply.
  2. onInit()

    It is called when the controller is loaded into memory

    onReady()

    It is called when the widget associated with the controller has been rendered.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search