首页 > 解决方案 > Flutter:允许容器内溢出?

问题描述

是否可以允许容器内溢出而不使内容可滚动?例如:

Container(
  height: 100,
  width: MediaQuery.of(context).size.width,
  child: Row(
    children: List.generate(10, (i) => Container(height: 100.0, width: 300).toList();
   ),
)

我知道它理论上会在发布时正常工作,但我希望在调试时抑制溢出警告。

我尝试将 Container() 包装在 OverflowBox() 中,但它仍然显示溢出警告。我尝试过的所有其他方法都使列表可滚动 - 它需要保持固定。

标签: flutterflutter-layout

解决方案


使用将 scrollDirection 设置为 Axis.horizo​​ntal 的 SingleChildScrollView,虽然它有效,但我推荐 ListViewBuilder

Container(
          height: 100,
          width: MediaQuery.of(context).size.width,
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: List.generate(
                10,
                (i) => Container(
                  height: 100.0,
                  width: 300,
                  margin: EdgeInsets.all(8),
                  color: Colors.green,
                ),
              ).toList(),
            ),
          ),
        ),

使用 ListviewBuilder

ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 100,
              itemBuilder: (context, i) {
                return Container(
                  height: 100.0,
                  width: 300,
                  margin: EdgeInsets.all(8),
                  color: Colors.green,
                );
              },
            )

编辑: Wrap 小部件可以解决问题。

SizedBox(
        height: 100,
        width: MediaQuery.of(context).size.width,
        child: Wrap(
          clipBehavior: Clip.hardEdge,
          direction: Axis.horizontal,
          children: List.generate(
            10,
            (i) => Container(
              height: 100.0,
              width: 300,
              margin: EdgeInsets.all(8),
              color: Colors.green,
            ),
          ).toList(),
        ),
      ),

推荐阅读