feat(kline): 首次加载时让最新K线居中显示
- 新增 _scrollToCenter() 方法,计算让最新K线居中的滚动位置 - 初始化时调用 _scrollToCenter() 替代 _scrollToEnd() - 如果K线总宽度小于屏幕宽度,不滚动,从左开始显示 - 保留 _scrollToEnd() 方法供刷新按钮等场景使用 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
8326f8c35c
commit
a97e0b51b8
|
|
@ -83,13 +83,38 @@ class _KlineChartWidgetState extends State<KlineChartWidget> {
|
|||
_candleWidth = idealWidth.clamp(_minCandleWidth, _maxCandleWidth);
|
||||
_prevCandleWidth = _candleWidth;
|
||||
|
||||
// 滚动到最右边(显示最新数据)
|
||||
_scrollToEnd();
|
||||
// 首次加载时让最新 K 线居中显示
|
||||
_scrollToCenter();
|
||||
}
|
||||
|
||||
/// 滚动使最新 K 线居中显示
|
||||
///
|
||||
/// 计算逻辑:
|
||||
/// - 如果 K 线总宽度小于屏幕宽度,不滚动,从左开始显示
|
||||
/// - 否则计算让最新 K 线中心位于屏幕中央的滚动位置
|
||||
void _scrollToCenter() {
|
||||
if (widget.klines.isEmpty || _chartWidth == 0) return;
|
||||
|
||||
final totalWidth = widget.klines.length * _candleWidth;
|
||||
|
||||
if (totalWidth <= _chartWidth) {
|
||||
// K 线总宽度小于等于屏幕宽度,不需要滚动,从左开始显示
|
||||
_scrollX = 0;
|
||||
} else {
|
||||
// 计算让最新 K 线居中的滚动位置
|
||||
// 最新 K 线的中心位置 = (K线数量 - 0.5) * 单根K线宽度
|
||||
final lastKlineCenter = (widget.klines.length - 0.5) * _candleWidth;
|
||||
// 目标滚动位置 = 最新K线中心 - 屏幕宽度的一半
|
||||
final targetScroll = lastKlineCenter - _chartWidth / 2;
|
||||
// 限制在有效滚动范围内
|
||||
final maxScroll = totalWidth - _chartWidth;
|
||||
_scrollX = targetScroll.clamp(0.0, maxScroll);
|
||||
}
|
||||
}
|
||||
|
||||
/// 滚动到最右边(显示最新数据在右侧)
|
||||
void _scrollToEnd() {
|
||||
if (widget.klines.isEmpty || _chartWidth == 0) return;
|
||||
// 滚动到最右边(显示最新数据)
|
||||
final totalWidth = widget.klines.length * _candleWidth;
|
||||
final maxScroll = math.max(0.0, totalWidth - _chartWidth);
|
||||
_scrollX = maxScroll;
|
||||
|
|
|
|||
Loading…
Reference in New Issue