Home > Back-end >  How to wrap a list of widgets with Flexible
How to wrap a list of widgets with Flexible

Time:12-01

I have a StatelessWidget defined as:

class FlexElement extends StatelessWidget {
  final List<Widget> widgets;
  final bool isVisible;

  const FlexElement({
    Key? key,
    required this.widgets,
    required this.isVisible,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Visibility(
      visible: isVisible,
      child: Container(
        child: Row(
          children: <Widget>[...widgets],
        ),
      ),
    );
  }
}

I would like to wrap each widget with a Flexible, so it doesn't overflow. (Row(children: Flexible([...widgets])). But since it is a list of widgets, I can only assign to multiple children and not to a single child. How would I solve this?

This is the result i would like:

Row(
  children: [
    Flexible(
      child: Widget1(), // <-- Wrapped in Flexible.
    ),
    Flexible(
      child: Widget2(), // <-- Wrapped in Flexible.
    ),
    ...
  ],
)

CodePudding user response:

You can do,

children: <Widget>[...widgets.map((w)=>Flexible(child:w))],

Or direct

children:widgets.map((w)=>Flexible(child:w)).toList(),

CodePudding user response:

This is what I always do:

Row(
  children: [
    Flexible(
      flex: 20,
      fit: FlexFit.tight,
      child: Widget1(), // <-- Wrapped in Flexible.
    ),
    Flexible(
      flex: 30,
      fit: FlexFit.tight,
      child: Widget2(), // <-- Wrapped in Flexible.
    ),
    ...
  ],
)

I put the flex values to total 100 so I think of each as a percentage of the width of the Row.

  • Related