skip to Main Content

I am trying to add padding to a child element in Flutter, but I want the padding to be a percentage of the child’s height. The problem is that the child’s height is unknown at the time of building the widget.

For example, if the child’s height is 500px, I want to add 20% padding (100px) to the top and bottom. I have tried using the EdgeInsets.symmetric constructor, but it only allows me to set a fixed padding value in pixels.

Is there a way to achieve this in Flutter, even if the child’s height is unknown?

Here is an example of my code:

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

Any help would be greatly appreciated!

2

Answers


  1. Use LayoutBuilder to measure child‘s height, here is an example

    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,
            );
          }),
        );
      }
    }
    
    Login or Signup to reply.
  2. Try this simpler way :

    Padding(
        child: Image.network(getRandomImage()),
        padding: EdgeInsets.symmetric(vertical: MediaQuery.of(context).size.height * 0.2),
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search