Home > Software engineering >  Flutter expand/collapse a container with dynamic height
Flutter expand/collapse a container with dynamic height

Time:11-03

I'm trying to expand and collapse a container dynamically based on the data received. Currently I'm doing it like this:

       AnimatedContainer(
          duration: const Duration(milliseconds: 550),
          margin: EdgeInsets.symmetric(horizontal: 16),
          constraints: !isExpanded
              ? BoxConstraints(
                  maxHeight: MyUtils.height(221),
                  minHeight: MyUtils.height(221))
              : BoxConstraints(
                  minHeight: MyUtils.height(321),
                  maxHeight: MyUtils.height(1000)),
          decoration: BoxDecoration(
              color: containerColor,
              borderRadius: const BorderRadius.all(Radius.circular(8))),
          child: Column(children: [
            Container(
              margin: EdgeInsets.fromLTRB(8, 10, 8, 20),
              height: MyUtils.height(36),
              width: double.infinity,
              decoration: BoxDecoration(
                  color: containerColor3,
                  borderRadius: BorderRadius.all(Radius.circular(6))),
            ),
            InkWell(
              onTap: () => expand(),
              child: Text(
                'Show',
                style: TextStyle(color: Colors.white),
              ),
            )
          ]),
        ),

The function expand() is as simple as changing the bool of isExpanded. I managed to collapse/expand the Container, but the problem is that the Container expanded until maxHeight, I want to make the expanded height dynamic based on the items inside. So I tried to set only minHeight and hoping that maxHeight will follow the items, but I got an error because maxHeight is not set.

Is there any way I can achieve this?

CodePudding user response:

use this package flutter_staggered_grid_view

CodePudding user response:

Use Wrap() Widget it can solve your issue as you want -


The function expand() is as simple as changing the bool of isExpanded. I managed to collapse/expand the Container, but the problem is that the Container expanded until maxHeight, I want to make the expanded height dynamic based on the items inside. So I tried to set only minHeight and hoping that maxHeight will follow the items, but I got an error because maxHeight is not set.


You can Manage the Heights from Using Wrap Widget

CodePudding user response:

By default, Column tries to be as much as possible. You can control this behavior by specifying mainAxisSize param.

Column(
  mainAxisSize: MainAxisSize.min, // ADD THIS LINE TO YOUR COLUMN
  children: [...]
)

I recommend that you read this article https://docs.flutter.dev/development/ui/layout/constraints

  • Related