Sizing elements to percentage of screen width/height

前端 未结 10 1747
情深已故
情深已故 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:37

    This might be a little more clear:

    double width = MediaQuery.of(context).size.width;
    
    double yourWidth = width * 0.65;
    

    Hope this solved your problem.

    0 讨论(0)
  • 2020-11-30 17:45

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-30 17:52
    MediaQuery.of(context).size.width
    
    0 讨论(0)
提交回复
热议问题