Search code examples
flutterlistviewlayout

Making a Container height match the Intrinsic Row Height inside a ListView


I want to make the container height to match the Row height inside this ListView, so I get a nice indicator for every card. The column will have variable length, so I cannot set a specific height. If I try to use Expanded widget, IntrinsicHeight widget or "height: double.infinity" I will get rendering exceptions.

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: 10,
          itemBuilder: (context, index) {
            return Card(
              child: Row(
                children: [
                  Container(
                    width: 10,
                    //height: 50,
                    color: Colors.blue,
                  ),
                  Column(
                    children: [
                      Text('A\nB\nC\nD'),
                    ],
                  ),
                  Column(
                    children: [
                      Text('$index'),
                    ],
                  ),
                ],
              ),
            );
          }),
    );
  }
}

Solution

  • You can wrap your entire Row inside IntrinsicHeight Widget as follows:

    @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView.builder(
              itemCount: 10,
              itemBuilder: (context, index) {
                return Card(
                  child: IntrinsicHeight(
                    child: Row(
                      children: [
                        Container(
                          width: 10,
                          color: Colors.blue,
                        ),
                        const Column(
                          children: [
                            Text('A\nB\nC\nD'),
                          ],
                        ),
                        Column(
                          children: [
                            Text('$index'),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              }),
        );
      }
    

    And remove the height from the container, this will make the container take the full height of the card, this will be the result:

    enter image description here