0

我有一堆不同高度的卡片,我想将它们显示在一个网格中,其中行高是该行最高小部件的高度,如下所示:

╔════╗╔════╗╔════╗╔════╗
║    ║║    ║║    ║║    ║
║    ║╚════╝║    ║║    ║
╚════╝      ║    ║╚════╝
            ╚════╝
╔════╗╔════╗╔════╗╔════╗
║    ║║    ║║    ║║    ║
║    ║║    ║╚════╝║    ║
╚════╝║    ║      ║    ║
      ║    ║      ╚════╝
      ╚════╝
╔════╗╔════╗╔════╗╔════╗
║    ║║    ║║    ║║    ║
║    ║╚════╝║    ║║    ║
╚════╝      ╚════╝║    ║
                  ╚════╝

我怎样才能做到这一点?我不想使用第三方软件包;flutter_staggered_grid_view,例如,有一个与窗口大小调整相关的严重错误,使我无法使用它。

4

2 回答 2

0

我已经使用ListViewwith Rows 实现了这一点,并利用ListView.builder了良好的性能。

LayoutBuilder,以及package::quiverpartition函数,用于计算宽度以实现类似于 aGridView和 a 的行为SliverGridDelegateWithMaxCrossAxisExtent

LayoutBuilder(
  builder: (context, constraints) {
    // Set minimum and maximum item width bounds.
    const minimumItemWidth = 200.0;
    const maximumItemWidth = 270.0;

    // Divide the maximum available width by the minimum item width to determine
    // the maximum amount of items that can fit in one row.
    //
    // If there's less than the minimum item width available, just use 1 item per
    // row.
    final itemsPerRow = constraints.maxWidth <= minimumItemWidth
        ? 1
        : constraints.maxWidth ~/ minimumItemWidth;

    // Partition the data into rows.
    final rows = quiver
        .partition(data, itemsPerRow)
        .toList(growable: false);

    return ListView.builder(
      itemCount: rows.length,
      itemBuilder: (context, index) {
        return Row(
          children: rows[index]
              .map((data) => SizedBox(
                  // Size row items to their maximum available width, constrained
                  // by the maximum width constant.
                  width: min(constraints.maxWidth / itemsPerRow, maximumItemWidth),
                  child: Tile(data: data),
              )).toList(growable: false),
        );
      },
    );
  },
);
于 2021-04-25T10:08:43.073 回答
0

你可以尝试使用ListView + Row. 请记住将crossAxisAlignment设置为 start 并将mainAxisSize设置为 min

在此处输入图像描述

import 'dart:math' as math;

class CustomGrid extends StatelessWidget {
  final r = math.Random();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Text('123'),
          _aRow(4),
          _aRow(4),
          _aRow(4),
          _aRow(4),
        ],
      ),
    );
  }

  Widget _aRow(int count){
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: List.generate(count, (index) => Expanded(child: _child())),
    );
  }

  Widget _child(){
    final h = r.nextDouble()*150;
    return Container(
      margin: const EdgeInsets.all(10),
      width: double.infinity,
      height: h,
      color: Colors.grey,
    );
  }
}
于 2021-04-25T09:46:46.920 回答