Search code examples
androidflutterlistviewwidgetrow

Flutter: Fill ListView.builder from existing list with 2 widgets per row


I tried so far and fail so hard by making than my ListView.builder show 2 widgets per row by taking the data from a List<MyCustomWidget> customs.

my List is like:

Class CustomWidgetData extends changeNotifier {
  List<CustomWidget> customs = [
    CustomWidget(
      icon: Icons.add,
      iconColor: Colors.green,
    ),
  ];
}

my ListView.builder is like:

class CustomWidgetListBuilder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<CustomWidgetData>(
      builder: (context, customWidgetData, child) {
        return Expanded(
          child: ListView.builder(
            itemBuilder: (context, index){
              final customWidget = customWidgetData.customs[index];
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                Expanded(
                  child: CustomWidget(
                    icon:customWidget.icon,
                    iconColor: customWidget.iconColor,
                  ),//CustomWidget
                ),//Expanded
                ],
              );//Row
            },
            itemCount: customWidgetData.customs.lenght,
          ), //ListView.builder
        ); //Expanded
      },
    );//Consumer
  }
}

How I want it to look

How it looks

In the first image i'm only added other Expanded->CustomWidget inside the Row of my ListView.builder but it repeat all the list and I want smth like:

1|2
3|4
5|6
...

Solution

  • Listview is not best suited for this use case. There is another widget called GridView which generates grids like what you wanted.

    GridView.builder(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 200,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20),
            itemCount: customWidgetData.customs.length,
            itemBuilder: (BuildContext context,int index) {
              return Container();
              
            }),