Search code examples
flutterdartsnapshotflutter-futurebuilder

How to access only the values from a Map


I have the following data json data.

    {
      "0": "traceroute to www.google.com ( 142.250.180.36 ), 30 hops max", 
      "1": "Hop   Address              Host Name                                     Time      ", 
      "2": "1     0.0.0.0        _gateway                                      3.03ms    ", 
      "3": "2     0.0.0.0          0.0.0.0                                  5.28ms    ", 
      "4": "3     0.0.0.0         0.0.0.0                                7.63ms    ", 
      "5": "4     0.0.0.0        00.0.0.0                                  9.65ms    ", 
      "6": "5     172.19.14.121        172.19.14.121                                 10.55ms   ", 
      "7": "6     58.181.114.10        58.181.114.10                                 29.9ms    ", 
      "8": "7     10.253.4.74          10.253.4.74                                   31.0ms    ", 
      "9": "8     10.253.4.26          10.253.4.26                                   148.22ms  ", 
      "10": "9     74.125.146.188       74.125.146.188                                43.09ms   ", 
      "11": "10    ******************** ********************************************* 5179.56ms ", 
      "12": "11    142.251.51.56        142.251.51.56                                 45.78ms   ", 
      "13": "12    108.170.247.23       108.170.247.23                                43.23ms   ", 
      "14": "13    209.85.240.55        209.85.240.55                                 48.81ms   ", 
      "15": "14    209.85.241.249       209.85.241.249                                42.3ms    ", 
      "16": "15    ***************** ***************************************** 5024.85ms ", 
      "17": "16    142.250.180.36       mct01s14-in-f4.1e100.net                      44.03ms   ", 
      "18": "Reached destination"
    }

I want to display the values against the keys in future builder. My flutter code is as follows:

    Container(
                  child: FutureBuilder<Map<String, dynamic>>(
                    future: fetchData(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return Expanded(
                          child: ListView.builder(
                              physics: AlwaysScrollableScrollPhysics(),
                              shrinkWrap: false,
                              itemCount: snapshot.data!.length,
                              itemBuilder: (BuildContext context, int index) {
                                return Container(
                                  height: 50,
                                  color: Colors.white,
                                  child: Center(
                                    child: Text(snapshot.data!.entries
                                        .elementAt(index)
                                        .toString()),
                                  ),
                                );
                              }),
                        );
                      } else if (snapshot.hasError) {
                        return Text("${snapshot.error}");
                      }
                      // By default show a loading spinner.
                      return CircularProgressIndicator();
                    },
                  ),
                ),

and my fetchData function is;

    Future<Map<String, dynamic>> fetchData() async {
        print("Fetch data is called");
        Map<String, String> header = {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          "Access-Control-Allow-Headers": "Access-Control-Allow-Origin, Accept",
          'Authorization': '<Your token>'
        };
    
        final response = await http.get(Uri.parse('http://192.168.100.9:7001/'),
            headers: header);
        if (response.statusCode == 200) {
          var jsonResponse = json.decode(response.body);
          return jsonResponse;
        } else {
          throw Exception('Unexpected error occured!');
        }
      }

I am not finding any way to access the values against my json keys iterate over them in listview builder. The only way I found is

    snapshot.data!.entries
                                            .elementAt(index)
                                            .toString())

But that is printing "MapEntry(key: value)" where I just want value. What should be in the text widget?


Solution

  • Use can use .values to read only the values.

    snapshot.data!.values.elementAt(index)
    

    In a Dart Map<K,V> you have access to keys, values and entries all three are Iterable<T> but the value of T differs for each.

    1. Keys are Iterable<K>
    2. Values are Iterable<V>
    3. Entries are Iterable<MapEntry<K,V>>

    With that being said, if you want to continue using .entries you could also update the Text widget to use snapshot.data!.entries.elementAt(index).value

    Additional Read:

    For more info on Dart Map visit the docs

    To know more about the MapEntry class visit this doc