Home > front end >  flutter box constraints not propagating to child as expected
flutter box constraints not propagating to child as expected

Time:01-19

I have learned that to make a Text wrap, you have to wrap it inside a Flexible() and set softWrap: true.

I have a ListView() with items generated by the following code:

return Container(
  constraints: const BoxConstraints(maxWidth: 300), 
  child: Row(mainAxisSize: MainAxisSize.min, children: [
    Checkbox(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
    GestureDetector(
        onTap: () {},
        child: Container(
          color: Colors.white,
          child: Row(mainAxisSize: MainAxisSize.min, children: [
            Icon(getCustomIcon(name: f.icon), size: 20, color: Colors.black),
            const SizedBox(width: 6),
            Flexible(
                child: Text(f.name,
                    softWrap: true, style: TextStyle(fontSize: 14))),
            const SizedBox(width: 6),
          ]),
        ))
  ]),
);

The Container should have a maximum width of 300 (see the outer BoxConstraints), but the innermost Text() node does not wrap and overflows. Somewhere in here the box constraints get lost, but I don't understand where.

Note: I removed UI non-relevant code like onTap/onChange/...

CodePudding user response:

try : Wrap your Container with either Row() or Center().

CodePudding user response:

After some more testing around I was able to solve the problem myself.

The problem is wrapping a row inside a row (even with other containers in-between) removes the constraints.

The solution is to put a Flexible/Expanded as the child of the parent row:

// innerRow is unconstrained
Row( children: [
  ...otherElements,
  Row() // innerRow
]);

// innerRow is constrained
Row( children: [
  ...otherElements,
  Flexible( // Flexible or Expanded tells the child to fill in the remaining space.
    child: Row() // innerRow
  ) 
]);
  • Related