Flutter in

In Getthe state management library, GetxControllerit is a base class used to manage state and logic. It has a series of life cycle methods for performing related operations at different stages. The following are GetxControllerthe life cycle methods and their execution order:

  1. onInit(): This method GetxControlleris called when a manager is created and added to it. You can perform some initialization operations here, such as initializing variables, subscribing to streams, etc.
  2. onReady(): This method GetxControlleris called after being loaded asynchronously. You can perform some asynchronous operations here, such as network requests, database reads, etc. It should be noted that this method will only be called when loading for the first time, and will not be triggered on subsequent page refreshes.
  3. onClose(): This method GetxControlleris called when it is permanently closed, usually when the page is destroyed. You can perform resource release, unsubscription and other cleanup operations here to prevent memory leaks.

In addition to life cycle methods, GetxControllersome other commonly used methods and properties are also provided, such as:

  • update(): Used to notify the manager of status changes and update the UI.
  • ever(): Used to monitor changes in a variable or Rx value, similar to the method Streamin listen.
  • once(): Monitor the first change of a variable or Rx value, and then no longer monitor it.
  • debounce(): When there are multiple changes in a specified time interval, only the last change will be executed.
  • interval(): When there are multiple changes continuously within the specified time interval, execute it every once in a while.

Example code used GetxController:

import 'package:get/get.dart';

class MyController extends GetxController {
  var count = 0;

  @override
  void onInit() {
    print('onInit called');
    super.onInit();
  }

  @override
  void onReady() {
    print('onReady called');
    super.onReady();
  }

  @override
  void onClose() {
    print('onClose called');
    super.onClose();
  }

  void increment() {
    count++;
    update(); // 通知状态变化,更新UI
  }
}

Use controllers in pages:

class MyPage extends StatelessWidget {
  final MyController myController = Get.put(MyController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Page'),
      ),
      body: Center(
        child: Obx(() => Text('Count: ${myController.count}')),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => myController.increment(),
        child: Icon(Icons.add),
      ),
    );
  }
}

Guess you like

Origin blog.csdn.net/BianHuanShiZhe/article/details/132227447