Irfan Ganatra
Irfan Ganatra

Reputation: 1386

how to get key from map in flutter at required position's key in flutter

Its not easy for me to explain what I want and thats why I have created this demo to make my point clear...

I have a data mymap which key is based on random number and value is bool

in my list tile of listview builder, I want sometime value and sometime key in it's title,subtitle,trailing,leading

class HomeScreen extends StatelessWidget {



  Map<String,dynamic> mymap={
    '${Random().nextInt(255)}':false,
    '${Random().nextInt(255)}':true,
    '${Random().nextInt(255)}':true,
    '${Random().nextInt(255)}':false,
   

  };

@override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: 1,
        itemBuilder: (context,index){

          return ListTile(
            title: Text(
                //firstkey + value
            ),
            subtitle: Text(
              //secondkey +value
            ),

            leading: Text(
              //thirdkey only
            ),
            trailing: Text(
              //fourthkey's value
            ),
          );

        });
  }
}


Upvotes: 0

Views: 405

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63709

You can use List to make sure of getting sorted value.

class HomeScreen extends StatelessWidget {
  List<Map<String, bool>> mymap = [
    {'${Random().nextInt(255)}': false},
    {'${Random().nextInt(255)}': true},
    {'${Random().nextInt(255)}': true},
    {'${Random().nextInt(255)}': false},
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: 1,
          itemBuilder: (context, index) {
            return ListTile(
              title:
                  Text("${mymap.first.keys.first} ${mymap.first.values.first}"),
              subtitle: Text("${mymap[1].keys.first} ${mymap[1].values.first}"),
              leading: Text("${mymap[2].keys.first}"),
              trailing: Text("${mymap[3].values.first}"),
            );
          }),
    );
  }
}

Perhaps A model class List is better.

Upvotes: 1

mohammad esmaili
mohammad esmaili

Reputation: 1747

You can get keys like here:

List keys = myMap.keys.toList();

And get access to keys in list tile like here:

Text(keys[2].toString()), // get key from list index

Upvotes: 1

Related Questions