Search code examples
flutterdartflutter-layout

how a child can get the width / height of it's parent dynamically


let's say I have a ChildWidget() and ParentWidget() and I want to say something like :

  • however, the parent width is, the child's width should be 20% of it

example : if a parent has a width: 200, the child's width should be width: 40.

and I want a way that's dynamic and not actually hardcoded values, so I will change the parent width and expect that the child

any ideas are welcome.


Solution

  • As pskink mentioned, FractionallySizedBox is handy in your case.

    class MyStatelessWidget extends StatelessWidget {
      const MyStatelessWidget({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Container(
              width: 400,
              height: 400,
              color: Colors.deepPurpleAccent,
              child: FractionallySizedBox(
                widthFactor: 0.2, //20% width
                heightFactor: .5, //50% height
                alignment: FractionalOffset.center,
                child: DecoratedBox(
                  decoration: BoxDecoration(
                    color: Colors.amber,
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
    

    enter image description here

    Also, you can check eamirho3ein's answer on LayoutBuilder.