Ad

Is There A Way To Get The Size Of An Existing Widget?

- 1 answer

I'm trying to get my UI to show two buttons with one slightly overlapping the other, in the middle of a full-width card. Because a Stack will only be as wide as its non-positioned children, I added a non-positioned child of a SizedBox with width double.INFINITY to give me a canvas to place the buttons on, but I don't know what to put as the SizedBox height. Ideally, I want this widget to size itself appropriately whether the user is on a phone or a tablet so I'd rather base the SizedBox height around the current size of the buttons instead of just hard coding a number.

Is there a way to find the size of a given existing widget? If not, what is the way to determine the height for objects that need to look good on multiple screen sizes?

Example code:

new Card(
  child: new Stack(
    children: <Widget>[
      new SizedBox(
        width: double.INFINITY,
      ),
      new Positioned(
        left: 1.0,
        child: getButtonOne(),
      ),
      new Positioned(
        right: 1.0,
        child: getButtonTwo(),
      ),
    ],
  ),
),
Ad

Answer

The short answer is no, because at the time of the build function the widgets haven't been laid out yet so they don't have a size.

The longer answer is that to achieve custom layout effects you can use a custom layout builder, though in your case that wouldn't help because a custom layout builder can't size itself to its children. The next level up is to just build a custom render object directly, which is just what Stack and Row and Column and so forth actually are. Then you can do whatever you want, layout-wise.

Ad
source: stackoverflow.com
Ad