Flutter best way to get size/position of widget when it doesn't render Flutter best way to get size/position of widget when it doesn't render dart dart

Flutter best way to get size/position of widget when it doesn't render


You can use LayoutBuilder to determine the widget's size. Here's a sample to demonstrate how the widget works.

One of the use case of the LayoutBuilder widget is determining the dimension of where widgets can be displayed and adapt their size to it.

import 'package:flutter/material.dart';void main() {  runApp(MyApp());}class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Flutter Demo',      theme: ThemeData(        visualDensity: VisualDensity.adaptivePlatformDensity,      ),      home: MyHomePage(title: 'Flutter Demo Home Page'),    );  }}class MyHomePage extends StatefulWidget {  MyHomePage({Key key, this.title}) : super(key: key);  final String title;  @override  _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  var dimension = 40.0;  increaseWidgetSize() {    setState(() {      dimension += 20;    });  }  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text(widget.title),      ),      body: Center(        child: Column(children: <Widget>[          Text('Dimension: $dimension'),          Container(            color: Colors.teal,            alignment: Alignment.center,            height: dimension,            width: dimension,            // LayoutBuilder inherits its parent widget's dimension. In this case, the Container in teal            child: LayoutBuilder(builder: (context, constraints) {              debugPrint('Max height: ${constraints.maxHeight}, max width: ${constraints.maxWidth}');              return Container(); // create function here to adapt to the parent widget's constraints            }),          ),        ]),      ),      floatingActionButton: FloatingActionButton(        onPressed: increaseWidgetSize,        tooltip: 'Increment',        child: Icon(Icons.add),      ),    );  }}

Demo

demo

Logs

I/flutter (26712): Max height: 40.0, max width: 40.0I/flutter (26712): Max height: 60.0, max width: 60.0I/flutter (26712): Max height: 80.0, max width: 80.0I/flutter (26712): Max height: 100.0, max width: 100.0