简体   繁体   中英

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

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: 在此处输入图片说明

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?

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
          ),
        );
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM