【问题标题】:Flutter stopwatchtimer doesn't respond to changing time颤振秒表计时器不响应更改时间
【发布时间】:2021-06-13 06:25:42
【问题描述】:

我在我的应用程序中使用这个包https://pub.dev/packages/stop_watch_timer 来跟踪正在播放的音乐。但是,如果我想通过更改秒表上的时间来更改歌曲,它会说我必须先重置计时器,我已经完成了。如果我第二次按下按钮,它就会起作用。这是代码:

  final StopWatchTimer _stopWatchTimer = StopWatchTimer(
    mode: StopWatchMode.countUp,
    onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
  );



  void change_timer_value(int song_index) {
    int new_time = TimerState(
            song_index: song_index,
            record_side: current_side_list(
                record_sides[selectedValue], widget.album_data))
        .get_start_value();
    print(new_time);

    _stopWatchTimer.onExecute.add(StopWatchExecute.reset);
    _stopWatchTimer.setPresetSecondTime(new_time); // this is where I set new time
  }

我不知道如何解决这个问题。我已经在创作者 GitHub 上创建了一个问题,但没有任何回应。所以这里有人可以帮助我

【问题讨论】:

    标签: flutter dart timer package


    【解决方案1】:

    正如您在 github 问题中提到的,问题的根本原因似乎是重置操作是异步发生的,因此在您尝试设置时间时尚未完成。

    解决此问题的一种方法是定义您自己的异步函数,该函数会重置秒表,然后在返回之前等待操作完成:

    Future<void> _resetTimer() {
      final completer = Completer<void>();
    
      // Create a listener that will trigger the completer when
      // it detects a reset event.
      void listener(StopWatchExecute event) {
        if (event == StopWatchExecute.reset) {
          completer.complete();
        }
      }
    
      // Add the listener to the timer's execution stream, saving
      // the sub for cancellation
      final sub = _stopWatchTimer.execute.listen(listener);
    
      // Send the 'reset' action
      _stopWatchTimer.onExecute.add(StopWatchExecute.reset);
    
      // Cancel the sub after the future is fulfilled.
      return completer.future.whenComplete(sub.cancel);
    }
    

    用法:

    void change_timer_value(int song_index) {
      int new_time = TimerState(
              song_index: song_index,
              record_side: current_side_list(
                  record_sides[selectedValue], widget.album_data))
          .get_start_value();
      print(new_time);
    
      _resetTimer().then(() {
        _stopWatchTimer.setPresetSecondTime(new_time);
      });
    }
    

    或者(使用 async/await):

    void change_timer_value(int song_index) async {
      int new_time = TimerState(
              song_index: song_index,
              record_side: current_side_list(
                  record_sides[selectedValue], widget.album_data))
          .get_start_value();
      print(new_time);
    
      await _resetTimer();
      _stopWatchTimer.setPresetSecondTime(new_time);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2019-07-22
      • 1970-01-01
      • 2021-05-31
      • 2022-11-20
      • 2019-07-03
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多