Search code examples
layoutflutter

Display widget with based on sibling max width


I got a Column, it contains many Text entries of different sizes and I'd like to have them expand to the same width than the largest text.

My Text entries are wrapped in a container with a Color and I want to align all them with the container so it can be rendered with straight borders.

How can I instruct this in Flutter ?


Solution

  • This is a good use case for IntrinsicWidth. You can use it with CrossAxisAlignment.stretch to determine the intrinsic width of the children and use it to set the width of your Column:

    screenshot

    Here's the example code that generates the above image.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(new MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          home: new Material(
            child: new Center(
              child: new IntrinsicWidth(
                child: new Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    new Container(
                      decoration: new BoxDecoration(color: Colors.blue[200]),
                      child: new Text('Hello'),
                    ),
                    new Container(
                      decoration: new BoxDecoration(color: Colors.green[200]),
                      child: new Text('world!!!!!!!'),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }