how to get height of a widget?

Here and there we needed to compute the stature of gadgets by any motivation to deliver the having a place gadgets on the screen. Along these lines, we should jump somewhere inside to realize how ripple figures the size.

So prior to hopping towards code, We would see How gadgets are delivered on screen? for that we need to initially take a gander at RenderObject.

RenderObject: Rendering of the gadget is finished by RenderObject, It handles the size, design, and painting of the gadget when Flutter Engine draws UI. Every gadget has the delivered object which holds the design of gadgets that are drawn on the screen.

So with the above clarification, you may as of now have a thought, about how we can get the stature of the gadget.

There is no immediate method to figure the size of the gadget, so to find that we need to take the assistance of the setting of the gadget.

Calling context.size returns us the Size object, which contains the stature and width of the gadget. context.size ascertains the render box of a gadget and returns the size.

Calling this getter is hypothetically generally costly (O(N) in the profundity of the tree), yet practically speaking is normally modest in light of the fact that the tree typically has many render objects and subsequently the distance to the closest render object is generally short.

Example:

class WidgetSize extends StatefulWidget {
  final Widget child;
  final Function onChange;

  const WidgetSize({
    Key key,
    @required this.onChange,
    @required this.child,
  }) : super(key: key);

  @override
  _WidgetSizeState createState() => _WidgetSizeState();
}

class _WidgetSizeState extends State<WidgetSize> {
  @override
  Widget build(BuildContext context) {
    SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
    return Container(
      key: widgetKey,
      child: widget.child,
    );
  }

  var widgetKey = GlobalKey();
  var oldSize;

  void postFrameCallback(_) {
    var context = widgetKey.currentContext;
    if (context == null) return;

    var newSize = context.size;
    if (oldSize == newSize) return;

    oldSize = newSize;
    widget.onChange(newSize);
  }
}

Use above Widget Like:

WidgetSize gadget restores the onChange callback which incorporates the size of the kid gadget.

Size textSize;
WidgetSize(
  onChange: (Size size) {
    setState(() {
      textSize = size;
    });
  },
  child: Text(
    "Size - $textSize",
    textAlign: TextAlign.center,
  ),
),

Output:

Image for post

Leave a Comment