Flutter 入门与实战Flutter中文社区Flutter圈子

GetxController 生命周期详解

2022-03-22  本文已影响0人  岛上码农

前言

上一篇我们讲到网络请求等异步操作最好放在 GetxControlleronReady 生命周期函数中处理。本篇我们来介绍 GetxController 的生命周期函数。

GetxController 类

我们自定义的Controller继承关系如下所示。

image.png

其中 GetxController只是有个 update 方法用于通知组件刷新。在 DisposableInterface 中覆盖了onInit 方法,实际多干了一件事:

SchedulerBinding.instance?.addPostFrameCallback((_) => onReady());

其实就是将 onReady 方法作为回调,当 onInit 完成之后的一帧来调用 onInit。这也就是我们上一篇说的,onReady 会在 onInit 完成后一帧后调用。这里有三个方法:

再往上是 GetLifeCycle 类,这个类只是在构造函数中配置了生命周期,实际上也是调用到 mixinGetLifeCycleBase$configureLifeCycle方法。实际上所有生命周期的方法都在这个 mixin 的定义。具体的方法如下:

实际上 onStartonDelete 分别绑定了内部的_onStart_onDelete 方法,在这两个方法里调用了 onInitonClose 方法。

/// 在 GetLifeCycle的构造函数中调用
void $configureLifeCycle() {
  _checkIfAlreadyConfigured();
  onStart._callback = _onStart;
  onDelete._callback = _onDelete;
}

bool _initialized = false;

/// Checks whether the controller has already been initialized.
bool get initialized => _initialized;
、
void _onStart() {
    if (_initialized) return;
    onInit();
    _initialized = true;
  }

  bool _isClosed = false;

  /// Checks whether the controller has already been closed.
  bool get isClosed => _isClosed;

  // Internal callback that starts the cycle of this controller.
  void _onDelete() {
    if (_isClosed) return;
    _isClosed = true;
    onClose();
  }

也就是前面说的,onStart是在controller内存分配的时间点 调用的,完成内存分配后就马上调用了 ``

替代 StatefulWidget

有了 GetxController 的生命周期后,我们就可以完全替换掉 StatefulWidget 了。

@override
void onInit() {
  //网络请求或其他初始化
  apiService.getData();
  super.onInit();
}
class Controller extends GetxController {
  StreamController<String> name = StreamController<String>();
    
  // ...

  @override
  void onClose() {
    name.close();
    super.onClose();
  }
}

总结

基于上面的分析,我们得出GetxController 的生命周期及对应说明如下图。

image.png

整个生命周期我们能够接入的方法就三个:

通过对 GetxController 的生命周期的理解,我们能够知道每个生命周期适合做得事情。

上一篇 下一篇

猜你喜欢

热点阅读