skip to Main Content

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

2

Answers


  1. You can do,

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

    Or direct

    children:widgets.map((w)=>Flexible(child:w)).toList(),
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search