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() {
  super.initState();
  _status = widget.status;
  // 初始化范围和距离
  _slideRange = widget.width - widget.height;
  _slideDistance = widget.status == SlideStatus.START ? 0.0 : _slideRange;
  // 初始化滑动归位动画
  _animationController = new AnimationController(duration: const Duration(milliseconds: 250), vsync: this);
  _animation = new Tween(begin: 0.0, end: _slideRange).animate(_animationController)
    ..addListener(() {
      // 判断是左滑还是右滑
      if (_status == SlideStatus.START && _isChangeStatus || _status == SlideStatus.END && !_isChangeStatus) {
        _onSlide(_animation.value);
      }else {
        _onSlide(-_animation.value);
      }
    });
  _animation.addStatusListener((status) {
    if (status == AnimationStatus.forward) {
      // 初始化偏移量
      _lastOffsetX = 0.0;
      // 计算是否需要改变状态
      if (_isChangeStatus) return;
      if (_status == SlideStatus.START && _slideDistance > _slideRange - widget.height + widget.padding) {
        _isChangeStatus = true;
      }else if (_status == SlideStatus.END && _slideDistance < widget.height - widget.padding) {
        _isChangeStatus = true;
      }else {
        _isChangeStatus = false;
      }
    }else if (status == AnimationStatus.completed) {
      // 初始化偏移量
      _lastOffsetX = 0.0;
      _animationController.reset();
      // 是否需要触发事件
      if (!_isChangeStatus) return;
      if (_status == SlideStatus.START) {
        // 判断是否滑动到最右端
        _onEnd();
      } else {
        // 判断是否滑动到最左端
        _onStart();
      }
      _isChangeStatus = false;
    }
  });
}