scrollController.animateTo异步调用多次

时间:2020-06-06 03:43:06

标签: flutter dart

我有RawKeyboardListener,每次按住KeyDown时都会调用_getIDCardInfo。

问题是多次调用了_getIDCardInfo。这造成了问题,因为scrollcontroller.animateTo仅在上一次调用_getIDCardInfo时才动画。

我希望每次调用_getIDCardInfo时都要使scrollcontroller.animateTo动画化,而不仅是在_getIDCardInfo的最后一次调用中。

如何使_getIdCardInfo()同步调用。或者没有任何方法可以使scrollController动画化而无需多次调用。

  _getIdCardInfo() async {
    try {
      final String result = await platform.invokeMethod('scanIDCard');
      await _myItems.insert(0, {"id": result});
      await _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          curve: Curves.easeIn,
          duration: Duration(milliseconds: 30));
      await _scrollController.animateTo(0,
          curve: Curves.easeIn, duration: Duration(milliseconds: 50));
    } on PlatformException catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    FocusNode _focusNode = FocusNode();
    return RawKeyboardListener(
      focusNode: _focusNode,
      autofocus: true,
      onKey: (RawKeyEvent event) async {
        if ((event.runtimeType == RawKeyDownEvent &&
            event.logicalKey.keyId == 1108101562648)) {
          await _getIdCardInfo();
        }
      },
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我猜您需要的是像这样递归运行动画:

  final _scrollController = ScrollController();
  final _focusNode = FocusNode();

  int _animateTimes = 0;        // How many times we need to run an animation
  Future<void> _animateFuture;  // Is animation currently running

  Future<void> _getIdCardInfo() async {    
    await _scrollController.animateTo(
      Random().nextInt(1000).toDouble(),
      duration: Duration(milliseconds: 1000), 
      curve: Curves.linear
    );

    _runNext();
  }

  void _runAnimation() {
    _animateTimes++;

    if (_animateFuture == null) {
      _animateFuture = _getIdCardInfo();
    }
  }

  void _runNext() {
    _animateTimes--;
    _animateFuture = null;

    if (_animateTimes > 0) {
      _animateFuture = _getIdCardInfo();
    }
  }

  @override
  void dispose() {
    _focusNode.dispose(); // Don't forget to dispose of focus node
    super.dispose();
  }
...
RawKeyboardListener(
  focusNode: _focusNode,
  autofocus: true,
  onKey: (RawKeyEvent event) async {
    if (event is RawKeyDownEvent && event.logicalKey.keyId == 1108101562648) {
      _runAnimation();
    }
  },
  child: Text('asd')
),
...