Flutter how to draw widget to know its size but user should not see it?
- User
Flutter how to draw widget to know its size but user should not see it?
- Assistant
You can use an
Offstagewidget to draw a widget without it being visible to the user. TheOffstagewidget is build on the Flutter SDK with the purpose of hiding some widget offstage, making it maintain its size/layout while hidden.Here's an example:
Offstage( offstage: true, child: Container( width: 100, height: 100, child: YourWidget(), ), )The
offstageproperty ofOffstageshould be set totrueto hide the widget, and you can set the width and height of theContainerwidget to be the size that you want to measure.YourWidgetis the widget that you want to measure the size of.After building this widget, you can access the size of the hidden
Containerwidget by callingkey.currentContext.size, wherekeyis the key that you assigned to theOffstagewidget. - User
Flutter how to get widget size before showing and placing (important) it for user?
- Assistant
To get the size of a widget before it is shown and placed on the screen for the user, you can use a
LayoutBuilderwidget. TheLayoutBuilderwidget will build its child and pass aBoxConstraintsobject to its builder function that describes the available size for the child.Here's an example:
LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final Size widgetSize = Size(constraints.maxWidth, constraints.maxHeight); // Do something with widgetSize here return YourWidget(); }, );In this example, the
LayoutBuilderwidget will create an invisible widget that will determine the size it can be up to given the constraints imposed by the parent. You can use theBoxConstraints.maxWidthandBoxConstraints.maxHeightproperties to get the size of the widget.Once you have the widget size, you can use it to position the widget on the screen as desired. You can also use it to inform the design of your app by using different layouts or styles based on the size of the widget.