Search code examples
flutterdartflutter-layout

How to create a general Custom Flutter Widget that renders as many Children Widgets as provided?


I want to render as many children as I provide to my Custom Method. So, let's say, I want to create my own Custom Widget that accepts a dynamic number of children to render. In other words, we can also say that I want to create a custom Row component that renders as many children as I provide. Here is an example of what I am trying to achieve is:

I want that in my main.dart, I render this kind of Custom Widget, which renders a number of children Widgets inside it. My idea is to create some kind of widget like that returns an array of childrens like this:

                 NeoText(
                   text: "⚽️Goals: 2",
                 ),
                 NeoText(
                   text: "🅰️Assists: 6",
                 ),
                 NeoText(
                   text: "🧤Saves: 26",
                 ),
               ],
             ),
           ),

I want to make the ScoreRow Widget a Custom Widget that accepts multiple children inside it and renders as many children as provided like in the below example. Is it possible to do something like that? Or is there any concept I need to cover?

import 'widgets/neo_text.dart';

class ScoreRow extends StatelessWidget {
  final Widget? children;

  const ScoreRow({super.key, required this.children});

  @override
  Widget build(BuildContext context) {
    return (
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [children!],
          // add the children here
      )
    );
     
  }
}

Solution

  • You can do that by passing list of widgets in the children parameter.

    import 'widgets/neo_text.dart';
    
    class ScoreRow extends StatelessWidget {
      final List<Widget> children;
    
      const ScoreRow({super.key, required this.children});
    
      @override
      Widget build(BuildContext context) {
        return (
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: children,
          )
        );
         
      }
    }