initState method

  1. @override
void initState()
override

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then be sure to subscribe and unsubscribe properly in initState, didUpdateWidget, and dispose:

  • In initState, subscribe to the object.
  • In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
  • In dispose, unsubscribe from the object.

You should not use BuildContext.dependOnInheritedWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.dependOnInheritedWidgetOfExactType can be used there.

Implementations of this method should start with a call to the inherited method, as in super.initState().

Implementation

@override
void initState() {
  VisibilityDetectorController.instance.updateInterval = Duration.zero;
  this._viewModel = createViewModel();
  // 初始化ViewModel
  this._viewModel.init(context, widget.lifecycle);

  this._detector = VisibilityDetector(
    key: UniqueKey(),
    // 内容控件交由子类自行实现
    child: const SizedBox(
      width: double.infinity,
      height: double.infinity,
    ),
    // page可见性回调,用于处理page的onPause、onResume事件
    onVisibilityChanged: (visibilityInfo) {
      var visiblePercentage = visibilityInfo.visibleFraction * 100;
      // double keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
      if (visiblePercentage > 0) {
        _onResume(false);
      } else {
        _onPause(false);
      }
    },
  );

  // 添加第一次绘制完成监听
  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    if (widget.lazyCreate) {
      // 绘制完成之后检查是否需要执行onCreate
      _onCreate(context);
    }
  });

  // 添加屏幕尺寸变化监听
  _onScreenSizeChangeOb = _OnScreenSizeChangeOb(this);
  WidgetsBinding.instance.addObserver(_onScreenSizeChangeOb!);

  _onCreate(context);

  // App的生命监听
  _lifecycleListener = AppLifecycleListener(
    onResume: () {
      // app从后台转到前台
      _onResume(true);
    },
    onHide: () {
      // 主要是web、macos这些从前台转到后台
      if (!isAndroid() && !isIOS()) {
        _onPause(true);
      }
    },
    onPause: () {
      // app从前台转到后台
      if (isAndroid() || isIOS()) {
        _onPause(true);
      }
    },
  );

  super.initState();
}