1

In my API call I store the keys and the values from a map inside a list. I want to access these keys and values in my ListView and display them in Text in my widget. How can I do that?

Api request

Future<List<Presence>> getPresencesByAthleteId(
      int depId, int teamId, int? id, context)  async {
        try {
          final response = await http.get(
              Uri.parse(
                  '$uri/get-presences-by-athlete-id?depId=$depId&teamId=$teamId&id=$id'),
              headers: {
                'Authorization': 'Basic ...',
                'Content-Type': 'application/json',
                'Accept': 'application/json'
              });
          print('Response status: ${response.statusCode}');
          print('Response body: ${response.body}');
    
          if (response.statusCode == 200) {
            if (response.body.isNotEmpty) {
              print('response.body.isNotEmpty');
              Map map = json.decode(response.body);
              List<Presence>? presencesList = [];
              map.forEach((key, value) {
                presencesList.add(Presence(
                    date: map.entries.first.key, count: map.entries.first.value));
                print('$key,$value');
              });
              return presencesList.toList();
            } else if (response.body.isEmpty) {
              print('response.body.isEmpty');
            }
          }
        } catch (e) {
          logger.e(e.toString());
        }
        return getPresencesByAthleteId(depId, teamId, id, context);
      }

My ListView

child: FutureBuilder<List<Presence>>(
                                                                                    future: getPresencesByAthleteId(_athlete[i].department!.id, widget._team.teamKey!.teamId, _athlete[i].id, context),
                                                                                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                                                                                      if (snapshot.hasData) {
                                                                                        return ListView.builder(
                                                                                            shrinkWrap: true,
                                                                                            primary: true,
                                                                                            physics: const ClampingScrollPhysics(),
                                                                                            scrollDirection: Axis.horizontal,
                                                                                            cacheExtent: 34,
                                                                                            itemCount: snapshot.data.length,
                                                                                            itemBuilder: (BuildContext context, int index) {
                                                                                              return ListTile(
                                                                                                title: Column(
                                                                                                  mainAxisSize: MainAxisSize.min,
                                                                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                                                                  children: [
                                                                                                    Row(
                                                                                                      children: [
                                                                                                        Text('${(index + 1).toString()}.'),
                                                                                                        const SizedBox(
                                                                                                          width: 5,
                                                                                                        ),
                                                                                                        Text(snapshot.data[index].toString()),
                                                                                                        const SizedBox(
                                                                                                          width: 20,
                                                                                                        ),
                                                                                                        Text(
                                                                                                          '{presencesList[index]',
                                                                                                          style: const TextStyle(color: Colors.blue),
                                                                                                        )
                                                                                                      ],
                                                                                                    )
                                                                                                  ],
                                                                                                ),
                                                                                              );
                                                                                            });
                                                                                      } else if (snapshot.hasError) {
                                                                                        logger.e('${snapshot.error}');
                                                                                      }
                                                                                      return const Center(
                                                                                        heightFactor: 20,
                                                                                        child: CircularProgressIndicator.adaptive(),
                                                                                      );
                                                                                    })

My Presence model

class Presence {
  String date;
  int count;

  Presence({required this.date, required this.count});
  factory Presence.fromJson(Map<String, dynamic> json) => Presence(
        date: json['date'],
        count: json['count'] as int,
      );

  Map<String, dynamic> toJson() => {
        "date": date,
        "count": count,
      };
}

The api from Postman that is the map that I store in my list

{
"10-11-2022":1,
"9-11-2022":4,
"7-11-2022":1
}

1 Answer 1

1

Instead of

Text(snapshot.data[index].toString()),

You can simply do

Text(snapshot.data[index].date),

or

Text(snapshot.data[index].count.toString()),
Sign up to request clarification or add additional context in comments.

Comments

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.