填充占子身高的百分比(未知高度)

问题描述 投票:0回答:1

我正在尝试向 Flutter 中的子元素添加填充,但我希望填充是子元素高度的百分比。问题是在构建小部件时孩子的身高是未知的。

例如,如果孩子的身高是500px,我想在顶部和底部添加20%的内边距(100px)。我尝试过使用

EdgeInsets.symmetric
构造函数,但它只允许我设置固定的填充值(以像素为单位)。

在 Flutter 中是否有办法实现这一点,即使孩子的身高未知?

这是我的代码示例:

Padding(
  child: Image.network(getRandomImage()),
  padding: EdgeInsets.symmetric(vertical: 50), // This should be 20% of child height
),

任何帮助将不胜感激!

flutter dart padding
1个回答
0
投票

使用LayoutBuilder测量孩子的身高,这里是一个例子

class _MyHomePageState extends State<MyHomePage> {
  double height = 0;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: height * 0.2),
      child: LayoutBuilder(builder: (context, constraint) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          setState(() {
            height = constraint.maxHeight;
          });
        });

        return Container(
          color: Colors.red,
          height: 500,
        );
      }),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.