fixed_height_grid_delegate.dart 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import 'package:flutter/rendering.dart';
  2. class FixedHeightGridDelegate extends SliverGridDelegate {
  3. /// Creates a delegate that makes grid layouts with a fixed number of tiles in
  4. /// the cross axis.
  5. ///
  6. /// All of the arguments must not be null. The `mainAxisSpacing` and
  7. /// `crossAxisSpacing` arguments must not be negative. The `crossAxisCount`
  8. /// and `childAspectRatio` arguments must be greater than zero.
  9. const FixedHeightGridDelegate({
  10. required this.crossAxisCount,
  11. this.mainAxisSpacing = 0.0,
  12. this.crossAxisSpacing = 0.0,
  13. this.height = 56.0,
  14. }) : assert(crossAxisCount > 0),
  15. assert(mainAxisSpacing >= 0),
  16. assert(crossAxisSpacing >= 0),
  17. assert(height > 0);
  18. /// The number of children in the cross axis.
  19. final int crossAxisCount;
  20. /// The number of logical pixels between each child along the main axis.
  21. final double mainAxisSpacing;
  22. /// The number of logical pixels between each child along the cross axis.
  23. final double crossAxisSpacing;
  24. /// The height of the crossAxis.
  25. final double height;
  26. bool _debugAssertIsValid() {
  27. assert(crossAxisCount > 0);
  28. assert(mainAxisSpacing >= 0.0);
  29. assert(crossAxisSpacing >= 0.0);
  30. assert(height > 0.0);
  31. return true;
  32. }
  33. @override
  34. SliverGridLayout getLayout(SliverConstraints constraints) {
  35. assert(_debugAssertIsValid());
  36. final double usableCrossAxisExtent =
  37. constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1);
  38. final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
  39. final double childMainAxisExtent = height;
  40. return SliverGridRegularTileLayout(
  41. crossAxisCount: crossAxisCount,
  42. mainAxisStride: childMainAxisExtent + mainAxisSpacing,
  43. crossAxisStride: childCrossAxisExtent + crossAxisSpacing,
  44. childMainAxisExtent: childMainAxisExtent,
  45. childCrossAxisExtent: childCrossAxisExtent,
  46. reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
  47. );
  48. }
  49. @override
  50. bool shouldRelayout(FixedHeightGridDelegate oldDelegate) {
  51. return oldDelegate.crossAxisCount != crossAxisCount ||
  52. oldDelegate.mainAxisSpacing != mainAxisSpacing ||
  53. oldDelegate.crossAxisSpacing != crossAxisSpacing ||
  54. oldDelegate.height != height;
  55. }
  56. }