0

I am having a json response that looks like this below

[
  {
        "email": "[email protected]",
        "about": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborumnumquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem.",
        "name": "kamchatka",
        "picture": "https://media.istockphoto.com/photos/fashion-beauty-african-american-beautiful-woman-profile-portrait-picture-id1197851431?k=20&m=1197851431&s=612x612&w=0&h=g3tb57yHvOHiFT3F35STNKNCQB0W1e9vKqFocnvnehE=",
        "index": 1,
        "imageFetchType": "networkImage"
  },
  {
        "email": "[email protected]",
        "about": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborumnumquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem.",
        "name": "Valjakutse",
        "picture": "https://images.unsplash.com/photo-1561406636-b80293969660?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8YmxhY2slMjBsYWR5fGVufDB8fDB8fA%3D%3D&w=1000&q=80",
        "index": 2,
        "imageFetchType": "imageNetwork"
  }
  
]

Want i want to achieve is populating a ListView Builder without using a class but instead using a List of HashMap<String, dynamic>

Below is how i am mapping the string response into List<HashMap<String, dynamic>> using async Future


Future<List<HashMap<String, dynamic>>>
  _fetchUsersUsingListOfStringDynamicHashMap() async {
    try {
      final response = await http.get(
          Uri.parse(
              "https://api.json-generator.com/templates/Eh5AlPjYVv6C/data"),
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer tltsp6dmnbif01jy9xfo9ssn4620u89xhuwcm5t3",
          });

      final List<HashMap<String, dynamic>> responseList;

      if (response.statusCode == 200) {
        responseList = json
            .decode(response.body)
            .map<HashMap<String, dynamic>>(
                (e) => HashMap<String, dynamic>.from(e))
            .toList();
      } else if (response.statusCode == 401) {
        responseList = [];
      } else {
        responseList = [];
      }

      return responseList;
    } catch (e) {
      if (kDebugMode) {
        Logger().wtf("FetchUsersUsingListOfStringObjectHashMapException $e");
      }

      rethrow;
    }
  }

And below is my FutureBuilder inside a SizedBox


SizedBox(
        child: FutureBuilder(
            future: _fetchUsersUsingListOfStringDynamicHashMap(),
            builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
              if (asyncSnapshot.data == null) {
                return const Center(child: CircularProgressIndicator());
              } else {
                return RefreshIndicator(
                  // background color
                    backgroundColor: Colors.white,
                    // refresh circular progress indicator color
                    color: Colors.green,
                    onRefresh: () async {
                      setState(() {
                        _fetchUsersUsingListOfStringDynamicHashMap();
                      });
                    },
                    child: ListView.builder(
                      itemCount: asyncSnapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          contentPadding: const EdgeInsets.all(10),
                          title: Text(asyncSnapshot.data[index]."email" ?? ''),
                          subtitle: Text(
                              asyncSnapshot.data[index]."name" ?? ''),
                        );
                      },
                    ));
              }
            }),
      ),

I am stuck in certain piece of code below where there is a ListView.Builder i am getting an Expected an identifier. error

return ListTile(
                          contentPadding: const EdgeInsets.all(10),
                          title: Text(asyncSnapshot.data[index]."email" ?? ''),
                          subtitle: Text(
                              asyncSnapshot.data[index]."name" ?? ''),
                        );

I have tried the following below

return ListTile(
                          contentPadding: const EdgeInsets.all(10),
                          title: Text(asyncSnapshot.data["email"] ?? ''),
                          subtitle: Text(
                              asyncSnapshot.data["name"] ?? ''),
                        );

But i am getting the error type 'String' is not a subtype of type 'int' of index' how can i be able to use the keys from the hashmap to set title as email and subtitle as name when i am using ListTile

1 Answer 1

1

Try:

 asyncSnapshot.data[index]["name"]

And

 asyncSnapshot.data[index]["email"]
Sign up to request clarification or add additional context in comments.

1 Comment

Please accept it if it answers your question.

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.