Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the size of an existing widget?

Tags:

flutter

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(),
      ),
    ],
  ),
),
like image 350
Reagankm Avatar asked Dec 13 '16 01:12

Reagankm


People also ask

How do you get the height of a particular widget in flutter?

To get the size/position of a widget on screen, you can use GlobalKey to get its BuildContext to then find the RenderBox of that specific widget, which will contain its global position and rendered size.

How do you use CustomSingleChildLayout?

CustomSingleChildLayout is a widget that defers the layout of its single child to a delegate. The layout constraints and the position of the child are determined by the delegate. The delegate can also be used to set the size of the parent. However, the parent's size cannot depend on the child's size.


1 Answers

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.

like image 130
Ian Hickson Avatar answered Oct 07 '22 13:10

Ian Hickson