简体   繁体   English

Flutter 方向改变后的 ListView adjustPositionForNewDimensions

[英]Flutter ListView adjustPositionForNewDimensions after orientation change

I am currently implementing a ListView that tries to keep the current "selected" item in the middle of the ListView.我目前正在实施一个 ListView,它试图将当前“选定”项目保留在 ListView 的中间。

This is achieved simply by implementing a custom ScrollPhysics that looks familiar to the PageScrollPhysics这可以通过实现一个看起来与PageScrollPhysics相似的自定义 ScrollPhysics 来简单地实现

However if the orientation of the screen changes (and thus the dimensions of the ListView) the item in the middle isn't correct anymore.但是,如果屏幕的方向发生变化(因此 ListView 的尺寸发生变化),中间的项目将不再正确。 I noticed there is a method that we can overwrite in the ScrollPhysics called adjustPositionForNewDimensions which works perfectly if the dimensions of the ListView changes programatically but somehow this method doesn't get triggered if the orientation changes.我注意到我们可以在 ScrollPhysics 中覆盖一个名为adjustPositionForNewDimensions的方法,如果 ListView 的尺寸以编程方式更改,该方法可以完美运行,但不知何故,如果方向更改,则不会触发此方法。

This method should get called from here which in turn gets called here .这个方法应该从这里调用,然后又在这里调用。 But somehow on the ListView its dimensions change the variable haveDimensions is true but after an orientation change (and thus dimension change) its false resulting in skipping the correctForNewDimensions check.但是不知何故,在 ListView 上,它的维度发生了变化,变量haveDimensions为 true,但在方向发生变化(并因此发生维度变化)之后,它的false导致跳过correctForNewDimensions检查。

It's not completly clear to me why this variable is false even though the dimensions did change.我不完全清楚为什么这个变量是false的,即使尺寸确实发生了变化。 Am I missing something, or should this behavior be implemented in a different way?我错过了什么,还是应该以不同的方式实现这种行为?

Well if you want to change some values on orientation change then it is pretty easy with flutter, you can use an OrientationBuilder which can detect when the orientation of the current device is being changed and update your code accordingly:好吧,如果您想在方向更改时更改某些值,那么使用 flutter 非常容易,您可以使用OrientationBuilder ,它可以检测当前设备的方向何时更改并相应地更新您的代码:

body: OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      // Create a grid with 2 columns in portrait mode,
      // or 3 columns in landscape mode.
      crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
    );
  },
),

You can find more about it on: https://docs.flutter.dev/cookbook/design/orientation您可以在以下网址找到更多相关信息: https://docs.flutter.dev/cookbook/design/orientation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM