Auto expanding Container in flutter -- for all devices

Randy picture Randy · Apr 10, 2019 · Viewed 33k times · Source

I need a Container with some text in to auto expand. I have an API call, which can be anything from 5 words to 500 words. I don't want to just have 1 fixed size that's huge, but contains 10 words.

I have tried Expanded() and SizedBox.Expand(), but I might be using them wrong

Card( 
 elevation: defaultTargetPlatform ==
      TargetPlatform.android ? 5.0 : 0.0,
  child: Column(
    children: <Widget>[
      Container(
        margin: const EdgeInsets.all(0.0),
        padding: const EdgeInsets.all(2.0),
        decoration: BoxDecoration(color: Colors.black),
        width: _screenSize.width,
        height: 250,
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.black,
              width: _screenSize.width,
              height: 35,
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 15, top: 11),
                child: Text("Title".toUpperCase(),
                  style: TextStyle(
                      color: Colors.white
                  ),
                ),
              ),
            ),
            Container(
              color: Colors.white,
              width: _screenSize.width,
              height: 210,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 8, bottom: 5),
                    child: Text("Title of expanding text", style: TextStyle(
                      fontSize: 25,
                    ),
                    ),
                  ),
                  Text("Expanding text", style: TextStyle(
                      fontSize: 35,
                      fontWeight: FontWeight.w800
                  ),),
                ],
              ),
            ),
          ],
        ),
      ),
    ],
  ),
),

I just need the Container to expand, but stay small/get bigger

Answer

thebuggycoder picture thebuggycoder · Apr 10, 2019

Have you tried not specifying height at all? The Container should wrap according to the child in this case.

Otherwise, the widget has a child but no height, no width, no constraints, and no alignment, and the Container passes the constraints from the parent to the child and sizes itself to match the child.

Above is an extract from the official flutter documentation for Container.

Here is the official flutter documentation link.