How can I add text per generated item in ListView of Flutter?

Question

Asked by Johan on November 14, 2021 (source).

I have this code, which is giving me a list of items.

I want to: 1 - Make the items clickable (probably by Gesture detection) 2 - Allow text + icon to be changeable and different per item. Now, I can show the same text for all items (because of this line: child: new Text("$index"),), but they need to be different so that I can actually achieve the following:

Container(
    height: 80.0,
    child: new ListView(
      scrollDirection: Axis.horizontal,
      children: new List.generate(10, (int index) {
        return new Card(
          color: Colors.blue[index * 100],
          child: new Container(
            width: 50.0,
            height: 50.0,
            child: new Text("$index"),
          ),
        );
      }),
    ),
  ),

This should be the end result: enter image description here

I'll sort out the gesture and clicking, but how can I create it in a way that I can name my items differently per generated item?

Answer

Question answered by Michael S (source).

First add a model of what you want to create, let's take category for example, the model will be like this:

class Category {
  String id;
  String name;
  String icon; // or image, anything you want
}

then, populate the data, either from a server or manually, something like the following:

final categories = <Category>[
  Category("1", "American", /** Icons.food or url to icon*/);
  Category("2", "other", /** Icons.food or url to icon*/);
];

now you have the data, display it with ListView.builder, will be something like the following:

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: categories.length,
  itemBuilder: (BuildContext context, int index) {
    return Card(
          color: Colors.blue[index * 100],
          child: new Container(
            width: 50.0,
            height: 50.0,
            child: new Text(categories[index].name), // same with icon
          ),
        );
  }
);
DART FILTER FLUTTER FLUTTER-LAYOUT
SHARE: