54

I'm trying to display the contents of my HashMap values in a ListView.builder widget. Is there a way to do this? With a List I could simply use the index, but how would that work with a HashMap without making a List out of it? The keys of the map are strings and the values are maps with the data to display.

4 Answers 4

96

Its a little late but You could also try this. Map values = snapshot.data;

return new ListView.builder(
  itemCount: values.length,
  itemBuilder: (BuildContext context, int index) {
    String key = values.keys.elementAt(index);
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text("$key"),
          subtitle: new Text("${values[key]}"),
        ),
        new Divider(
          height: 2.0,
        ),
      ],
    );
  },
);

for a more detailed example check this out https://kodestat.gitbook.io/flutter/39-flutter-listviewbuilder-using-dart-maps

Sign up to request clarification or add additional context in comments.

Comments

31

Just make a list from the keys and then get the value using the index to get the map key and use it to get the map value

var keys = myMap.keys.toList();
var val = myMap[keys[idx]];

5 Comments

But I'm constantly changing the Map. I'd prefer not to create a list every time when I'm adding data.
Every time you change your map, you're calling setState() anyway, I presume? If so, you probably don't need to worry about calling keys.toList().
There is no way to access elements of a map by index. I don't think there are other map implementations that would allow that.
What is idx in this example?
The position of the element you want to access.
10

it is possible, you can do something like this

  map.forEach((key, value) {
        // here you can write your logic using "Value object",
       // make new object of your list view item and
       // add it to it's  builder list using 

       setState(() {
          _builderList.insert(0, itemObject);
       });

   });

or you can try

 final list = map.values.toList(growable: {true/false});
// play with your list

Comments

1

Just use inside the listview builder yourlistname[index ]['keyname' ], that works for me.

1 Comment

Is it ideal? I have no idea ! Does it work? Yes !! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.