Vamsi
Vamsi

Reputation: 145

flutter specifying width, height, paddings, margins etc in percentages?

Is there a way in flutter which allows the widths, heights, paddings, margins etc being specified in percentages of screen dimensions instead of writing calculations in every widget?

Passing around a provider or extending some base class for this trivial thing is not feeling right.

Upvotes: 1

Views: 1106

Answers (1)

Sidak
Sidak

Reputation: 1283

The only known solution is to use MediaQuery. I implemented a helper class that I just call the methods for:

class SizeManager {
  var _context;
  double _screenHeight;
  double _screenWidth;

  SizeManager(this._context) {
    _screenHeight = MediaQuery.of(_context).size.height;
    _screenWidth = MediaQuery.of(_context).size.width;
  }

  double scaledHeight(double value) {
    return value * _screenHeight / 100;
  }

  double scaledWidth(double value) {
    return value * _screenWidth / 100;
  }
}

In every build(), just before the return, call it like:

SizeManager sizeManager = new SizeManager(context);

And whenever you want to set margins/padding/size:

Container(
  padding: EdgeInsets.symmetric(vertical: sizeManager.scaledHeight(2.5)), //Gives a 2.5 % height padding
),

Upvotes: 1

Related Questions