flutter ListViewBuilder或ListView中的行的mainAxisSize属性不起作用

x7rlezfr  于 2023-02-25  发布在  Flutter
关注(0)|答案(2)|浏览(149)

ListView.builderListView中的RowmainAxisSize属性不起作用。

return ListView.builder(
  itemCount: 5,
  shrinkWrap: true,
  itemBuilder: (context, index) {
    return Container(
      color: Colors.grey,
      margin: const EdgeInsets.all(2),
      child: Row(
        mainAxisSize: MainAxisSize.min, // not working
        children: [
          Text(index.toString()),
        ],
      ),
    );
  },
);

我期望MainAxisSize.min属性能够缩短Row,但是它没有。

yrefmtwq

yrefmtwq1#

ListView总是使children覆盖父宽度。因此,根据您的要求,您可以删除Row上的Container,并使用Text Package 相同的Container,如下所示。

ListView.builder(
  itemCount: 5,
  shrinkWrap: true,
  itemBuilder: (context, index) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
            color: Colors.grey,
            margin: const EdgeInsets.all(2),child: Text(index.toString())),
      ],
    );
  },
)
oxf4rvwz

oxf4rvwz2#

The Container widget that wraps the Row widget also needs to have its height set to the minimum required height of the Row. You can achieve this by setting the height property of the Container widget to null or double.infinity.

return ListView.builder(
  itemCount: 5,
  shrinkWrap: true,
  itemBuilder: (context, index) {
    return Container(
      color: Colors.grey,
      margin: const EdgeInsets.all(2),
      height: null, // or height: double.infinity
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(index.toString()),
        ],
      ),
    );
  },
);

With this change, the Row widget will be able to shrink to its minimum size, and the ListView widget will adjust its height accordingly.

相关问题