Sizing elements to percentage of screen width/height

前端 未结 10 1755
情深已故
情深已故 2020-11-30 17:11

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 scree

10条回答
  •  囚心锁ツ
    2020-11-30 17:48

    First get the size of screen.

    Size size = MediaQuery.of(context).size;
    

    After this you can get width and multiply it with 0.5 to get 50% of screen width.

    double width50 = size.width * 0.5;
    

    But problem generally comes in height, by default when we use

    double screenHeight = size.height;
    

    The height we get is global height which includes StatusBar + notch + AppBar height. So, in order to get the left height of the device, we need to subtract padding height (StatusBar + notch) and AppBar height from total height. Here is how we do it.

    double abovePadding = MediaQuery.of(context).padding.top;
    double appBarHeight = appBar.preferredSize.height;
    double leftHeight = screenHeight - abovePadding - appBarHeight;
    

    Now we can use following to get 50% of our screen in height.

    double height50 = leftHeight * 0.5
    

提交回复
热议问题