skip to Main Content

Here’s an example of declaring the height & width of a SizedBox:

SizedBox(width: 40, height: 40)

In some cases (on other devices), I’ve noticed that sometimes the dimensions get overflowed and causes errors. In my mind, I thought that declaring by pixel number would be universal across all devices because 200 pixels should be 200 pixels regardless of device screen size. But clearly I was wrong, so is there a quick or easy way to fix my error to make sure the width/height stays universal across all devices?

The problem with using MediaQuery.of(context).size.width is that in some instances whenever you have a wide screen or when the user tilts the phone in landscape view, using MediaQuery would make the width or height way too long & would not pass the esthetic test.

Thank you for any help!

2

Answers


  1. Consider using the FractionallySizedBox to set a percentage of the width/height that should be taken from all screens:

    FractionallySizedBox(
      heightFactor: 0.2, // will take 20% of the screen height.
      widthFactor: 0.4, // will take 40% of the screen width.
    );
    
    Login or Signup to reply.
  2. If you want to create a condition for each screen size but avoid messy code. You should try to do it with an extension.

    For example:

    extension BoxWithSizes on double {
       
       double get conditional {
            return (//size of screen < 600) ? this : this - 30;
       }
    
    }
    

    And use it like

    SizedBox(width: 30.conditional)
    

    The thing with this is that you should do like in CSS, a different getter extension for differents components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search