How to get size of widget from custom widget in flutter?

Viewed 424

Let's say I have the following custom widget:

MyWidget extends StatelessWidget{
  Widget child;
......
  const MyWidget(
      {Key key,
      this.child})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    //get child's size and use it in layout
  }
}

How can I reach this? I know that I can do it using global keys but as I see this solution doesn't work here.

How would I do it if I didn't need to create separate StatelessWidget: I'd create GlobalKey and provided it in constructor, but here I can't provide it in constructor because I have already created child Widget in my custom widget.

1 Answers

You can set a GlobalKey for a widget wrapping the child widget, e.g., a Container or an IntrinsicHeight(which sets its height to its child's height) and get this widget's size using that key:

class MyWidget extends StatelessWidget {
  final Widget child;
  MyWidget({Key key, this.child}) : super(key: key);
  final GlobalKey key1 = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        IntrinsicHeight(child: child, key: key1),
        FlatButton(
          onPressed: () {
            print(key1.currentContext.size);
          },
          child: Text('get height'),
        )
      ],
    );
  }
}
Related