gpt4 book ai didi

flutter - ListView PageScrollPhysics 捕捉基于子宽度/PageView with viewportFraction < 1 align left

转载 作者:行者123 更新时间:2023-12-05 02:54:52 24 4
gpt4 key购买 nike

我有一个 viewportFraction 为 0.8 的 PageView/ListView 来显示下一张幻灯片的预览。它看起来像这样:

enter image description here

似乎无法让当前幻灯片向左对齐,如下所示。对吗?

enter image description here

我找到了这个解决方案。将水平滚动的 ListView 与 PageScrollPhysics() 一起使用,起初看起来很有希望,但是,这种方式页面捕捉基于屏幕宽度(?)而不是基于 ListView 子级,因此捕捉关闭相当多。

有没有办法让页面根据 child 的大小对齐?

最佳答案

我的回答有点晚了,但它可能会帮助其他人寻找同样的东西。PageScrollPhysics 使用屏幕宽度。您需要创建自己的 ScrollPhysics,它使用您的项目宽度来分页。这是一个例子:

ListView.builder(
physics: PagingScrollPhysics(itemDimension: YOUR_ITEM_WIDTH),
itemCount:items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return YOUR_CHILD();
}
)

以及新的 ScrollPhysics:

import 'package:flutter/material.dart';

class PagingScrollPhysics extends ScrollPhysics {
final double itemDimension;

PagingScrollPhysics({required this.itemDimension, ScrollPhysics? parent}) : super(parent: parent);

@override
PagingScrollPhysics applyTo(ScrollPhysics? ancestor) {
return PagingScrollPhysics(itemDimension: itemDimension, parent: buildParent(ancestor));
}

double _getPage(ScrollMetrics position) {
return position.pixels / itemDimension;
}

double _getPixels(double page) {
return page * itemDimension;
}

double _getTargetPixels(ScrollMetrics position, Tolerance tolerance, double velocity) {
double page = _getPage(position);
if (velocity < -tolerance.velocity) {
page -= 0.5;
} else if (velocity > tolerance.velocity) {
page += 0.5;
}
return _getPixels(page.roundToDouble());
}

@override
Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) || (velocity >= 0.0 && position.pixels >= position.maxScrollExtent)) return super.createBallisticSimulation(position, velocity);
final Tolerance tolerance = this.tolerance;
final double target = _getTargetPixels(position, tolerance, velocity);
if (target != position.pixels) return ScrollSpringSimulation(spring, position.pixels, target, velocity, tolerance: tolerance);
return null;
}

@override
bool get allowImplicitScrolling => false;
}

关于flutter - ListView PageScrollPhysics 捕捉基于子宽度/PageView with viewportFraction < 1 align left,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com