Search code examples
flutterdartlistviewkey

How to pass keys to ListViewBuilder?


I have a class containing elements

MyClass(key: ValueKey("1")),

I would like to display them on the screen in the amount I need. I tried to do this through ListViewBuilder , but I don't quite understand how I can specify the keys inside the ListView that distinguish my class elements

ListView.builder(
             itemCount: 5,
             itemBuilder: (context, index) {
              return MyClass(key: ValueKey(""));

Solution

  • itemBuilder builds element of list one by one. index is number of element is building right now (beginning from 0).

    this should work for you

    ListView.builder(
                 itemCount: 5,
                 itemBuilder: (context, index) {
                  return MyClass(key: ValueKey(index.toString()));
    

    or if you start from 1

     ListView.builder(
                     itemCount: 5,
                     itemBuilder: (context, index) {
                      return MyClass(key: ValueKey((index+1).toString()));