Home > front end >  Flutter SliverGrid Flip Axis
Flutter SliverGrid Flip Axis

Time:10-31

tl;dr How do I flip the X axis in a SliverGrid?

I have to display a long list in a grid (every cell is equal in size). I can request the list from a server with pagination. Now the user should be able to open that list at any index in the grid and should be able to scroll in both direction.

I am trying to create a GridView in Flutter and lazy load its content in both directions (upwards and downwards) while scrolling.

My first attempt was to modify wrong building order on the x axis in upper half

How do I flip the X axis in a SliverGrid? or achieve increasing order from left to right in the upper half? (I do not know the number of cells per row, so as far as I know I can not manipulate the order by translating the index in the builder).

Demo Code:

var items = <int>[];
  for (var i = 0; i < 300;   i) {
    items.add(i - 100);
  }

/*
 * ...
 */

BidirectionalGridView(
  upperItemCount: 100,
  lowerItemCount: 200,
  itemBuilder: (context, index) {
    return SizedBox.square(
      dimension: 72,
      child: Align(
        alignment: Alignment.center,
        child: Text("${items[index]}"),
      ),
    );
  },
  gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 72,
    crossAxisSpacing: 4,
    mainAxisSpacing: 4,
    childAspectRatio: 1,
  ),
),

CodePudding user response:

Since I am using a SliverGridDelegateWithMaxCrossAxisExtent as my grid delegate I simply subclassed it and slightly modified getLayout method.

class CrossAxisFlippedSliverGridDelegateWithMaxCrossAxisExtent
    extends SliverGridDelegateWithMaxCrossAxisExtent {
  /// Creates a delegate that makes grid layouts with tiles that have a maximum
  /// cross-axis extent and are flipped along the cross axis.
  /// ...
  const CrossAxisFlippedSliverGridDelegateWithMaxCrossAxisExtent({
    ...
    }) : super(...);

  @override
  SliverGridLayout getLayout(SliverConstraints constraints) {
    var tileLayout = super.getLayout(constraints) as SliverGridRegularTileLayout;

    return SliverGridRegularTileLayout(
      crossAxisCount: tileLayout.crossAxisCount,
      mainAxisStride: tileLayout.mainAxisStride,
      crossAxisStride: tileLayout.crossAxisStride,
      childMainAxisExtent: tileLayout.childMainAxisExtent,
      childCrossAxisExtent: tileLayout.childCrossAxisExtent,

      // Where the actual magic happens
      reverseCrossAxis: !tileLayout.reverseCrossAxis,
    );
  }
}
  • Related