flutterdartflutter-layoutscreen-size

Sizing elements to percentage of screen width/height


Is there a simple (non-LayoutBuilder) way to size an element relative to screen size (width/height)? For example: how do I set the width of a CardView to be 65% of the screen width.

It can't be done inside the build method (obviously) so it would have to be deferred until post build. Is there a preferred place to put logic like this?


Solution

  • FractionallySizedBox may also be useful. You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

    MediaQuery.of(context).size.width * 0.65
    

    if you really want to size as a fraction of the screen regardless of what the layout is.