You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中just_audio的Seek方法后退拖动滑块报错

解决just_audio滑块向后拖动报错问题

问题原因

你的代码里通过newValue.clamp(_value, playerState.duration.inSeconds.toDouble())强制限制滑块只能向前调整,当尝试向后拖动时,newValue会被拉回当前_value值,此时调用seek到和当前位置相同的点,和播放器实时播放状态冲突,触发了内部缓存错误。另外,单独维护的_value变量会和playerState中的currentPosition不同步,进一步加剧状态不一致问题。

修复方案

  1. 移除限制滑块向后拖动的clamp逻辑,允许自由调整到合法范围内的任意位置
  2. 不再维护本地_value变量,滑块的value直接绑定playerState.currentPosition,播放器执行seek后会自动更新位置,Consumer会自动重建滑块同步UI

修复后的代码:

Consumer<PlayerStateModel>(
  builder: (context, playerState, child) {
    return Slider(
      value: playerState.currentPosition.inSeconds.toDouble(),
      min: 0.0,
      max: playerState.duration.inSeconds.toDouble(),
      inactiveColor: globals.shadowColor,
      onChanged: (newValue) {
        // 仅限制在合法时长范围内,不限制拖动方向
        final targetValue = newValue.clamp(0.0, playerState.duration.inSeconds.toDouble());
        audioPlayer.seek(Duration(seconds: targetValue.toInt()));
      },
    );
  },
)

补充说明

如果需要确保拖动值不会超出音频时长范围,只需要用clamp(0.0, 最大时长)即可,不要限制最小值为当前位置,这样既能保证参数合法,又支持前后自由拖动。

内容的提问来源于stack exchange,提问作者Dhanrajsinh Parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 13:47:22