0

I'm very new to Flutter so please bear with me. I wonder whether I can retrieve and use the width of a widget inside the build method. The RoundButton widget below illustrates two cases where having the width could be useful:

  • to display the width as text
  • to create a circular Container, I could use radius=width/2 (Note: I know this can be done using shape: BoxShape.circle so it's just an example where having the width could be useful)

So I have two questions:

  • is it possible to get the width of the widget
  • if so, can you outline how this can be done?
class RoundButton extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Container (
            decoration: BoxDecoration(
              border: Border.all(width: 6, color: Colors.green),
              borderRadius: const BorderRadius.all(const Radius.circular(**width**/2)),
              //shape: BoxShape.circle,
            ),

            child: Center (
              child: Text(
              "w="+**width**.toString(),
            ),
          )
        ));
  }
}

Marc Van Daele
  • 2,856
  • 1
  • 26
  • 52
  • 1
    Does this answer your question? [How to get height of a Widget?](https://stackoverflow.com/questions/49307677/how-to-get-height-of-a-widget) – Midhun MP May 18 '21 at 16:38

1 Answers1

0

Apparently, this can be done without LayoutBuilder using the code below. Note that the two const on the borderRadius line had to be removed

  @override
  Widget build(BuildContext context) {
    RenderBox rb = context.findRenderObject() as RenderBox;
    final Size size = rb?.size ?? Size.zero;
    return Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Container (
            decoration: BoxDecoration(
              border: Border.all(width: 6, color: Colors.green),
              borderRadius: BorderRadius.all(Radius.circular(size.width.toInt()/2)),
              //shape: BoxShape.circle,
            ),

            child: Center (
              child: Text(
              "w="+size.height.toString(),
            ),
          )
        ));
  }

Marc Van Daele
  • 2,856
  • 1
  • 26
  • 52