flutterdart

How to wrap a list of widgets with Flexible


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.
    ),
    ...
  ],
)

Solution

  • You can do,

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

    Or direct

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