ZKK
ZKK

Reputation: 771

Dart/Flutter: automatically generate the subwidget in a class

I got the class below

class MyWidget extends StatelessWidget {

    final int num;
    MyWidget({this.num});

  @override
  Widget build(BuildContext context) {
  WidgetA(),
  WidgetA(),
  WidgetA(),
//the WigetA will repeate itself depending on the num.
}

}

If MyWidget(num = 3), then there will be 3 WigetA in MyWidget.

How to build this function inside WigetA?

Upvotes: 0

Views: 324

Answers (1)

hnnngwdlch
hnnngwdlch

Reputation: 3041

You could use ListView.builder. Here's some example code:

class MyWidgetListViewBuilder extends StatelessWidget {
  final int widgetCount;

  MyWidgetListViewBuilder(this.widgetCount);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: widgetCount,
      itemBuilder: (context, index) {
        return WidgetA();
      },
    );
  }
}

class WidgetA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('I appear as often as necessary');
  }
}

It is of course also possible to build the List<WidgetA> using a separate function:

class MyWidgetListView extends StatelessWidget {
  final int widgetCount;

  MyWidgetListView(this.widgetCount);
  
  List<WidgetA> _buildWidgetAList() {
    final widgetAList = <WidgetA>[];
    for (var i = 0; i < widgetCount; i++) {
      widgetAList.add(WidgetA());
    }
    return widgetAList;
  }

  @override
  Widget build(BuildContext context) {
    return ListView(children: _buildWidgetAList());
  }
}

This answer describes the differences between ListView and ListView.builder.

Upvotes: 2

Related Questions