Utilizing a FutureBuilder for fetching JSON data in a Flutter DropDownButton

I have been developing an app using Flutter and I am currently working on implementing a Dropdown Button that will display values received from a JSON response via an API built with Django.

Here is the JSON response:

[{"name": "FC1", "username": "admin"}, {"name": "FC2", "username": "admin"}]

This is the Object class being used:

class FoodCourt {
  final String name;
  FoodCourt(this.name);
}

This is the method for retrieving the data:

Future<List<FoodCourt>> _getFoodCourt() async {
 var data = await http
     .get("http://timetable-api-manipal.herokuapp.com/getfoodcourt");
 var jsonData = json.decode(data.body);

 List<FoodCourt> fcs = [];

 for (var u in jsonData) {
   FoodCourt fc = FoodCourt(u["name"]);
   fcs.add(fc);
 }
 print(fcs);
 return fcs;
} 

Here is the implementation of the FutureBuilder Widget:

FutureBuilder(
          future: _getFoodCourt(),
          builder: (context, snapshot) {
            return DropdownButton<String>(
                hint: Text("Select"),
                value: selectedFc,
                onChanged: (newValue) {
                  setState(() {
                    selectedFc = newValue;
                  });
                },
                items: snapshot.data.map((fc) {
                  return DropdownMenuItem<String>(
                    child: Text(fc.name),
                    value: fc.name,
                  );
                }));
          }),

The error message displayed reads as follows:

I/flutter (31862): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════

I/flutter (31862): The following assertion was thrown building FutureBuilder<List<FoodCourt>>(dirty, state:
I/flutter (31862): _FutureBuilderState<List<FoodCourt>>#3c097):
I/flutter (31862): type 'MappedListIterable<FoodCourt, 
DropdownMenuItem<FoodCourt>>' is not a subtype of type
I/flutter (31862): 'List<DropdownMenuItem<FoodCourt>>'

I have attempted various solutions to this issue but to no avail. It would be greatly appreciated if someone could provide a sample code for a successful resolution!

Answer №1

Make sure to follow two essential steps before proceeding, as outlined in @saed's response

items: snapshot.data.map((fc) =>
       DropdownMenuItem<String>(
        child: Text(fc.name),
        value: fc.name,
      )
    ).toList();

The second step involves specifying the type within the FutureBuilder like this:

FutureBuilder<List<FoodCourt>>(..... Your code

Answer №2

It seems your content is not in a list format. You can update it using the following code:

items: snapshot.data.map((fc) =>
       DropdownMenuItem<String>(
        child: Text(fc.name),
        value: fc.name,
      )
    ).toList();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

Omitting Null Values when sending data to JSON using the JsonResult in an MVC application

I have a sample of Json data below. Although the object is more intricate in reality, this snippet showcases my query. I am interested in reducing the size of the Json response that is being generated. Currently, it is created using the standard JsonResu ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

Create a collection of JSON objects and save them to a text file

I need help filling an empty file named data.json with a JSON array using Python. Here is the script I have written: import json myArray = [] first = {} second = {} third = {} first["id"] = 1 first["name"] = "Foo" second["id"] = 2 second["name"] = "Joh ...

Sending JSON data in a POST request using Java's HttpUrlConnection

After spending time developing a Java code to convert the cURL request below into Java using URL and HttpUrlConnection, I've hit a roadblock. The original cURL is: curl -i 'http://url.com' -X POST -H "Content-Type: application/json" ...

The JsonParser functionality on android is malfunctioning

Looking at my JSONObject on this link, I realized that my JSON parser is not functioning correctly. It seems like the issue lies within the parser itself as there are no null errors coming from my list. Here is a snippet of my parser: class exTourPars ...

Working with Swift to safely extract values from a dictionary using guard statements

A JSON call retrieves a dictionary, shown below. It is possible for either of the two values or even the entire "secondLevel" dictionary to be missing. { "theMain" : { "secondLevel" : { "value1" : "5.3", "value2" : "bbb" } ...

The dashboards list could not be loaded due to an error in decoding the JSON format within Apache Superset

I encountered an issue while fetching dashboards in Superset. The error message states: ERROR:root:Expecting ',' delimiter: line 1 column 106 (char 105) I observed this error while monitoring the pod. On the front-end, only the following messa ...

While going through multiple JSON links, I encountered a JSON decode error

I'm facing an issue with a JSON data structure that contains information on various "videos". Each "video" in the JSON includes a link to another JSON file containing "messages". My goal is to loop through the links to the "message" JSON files and in ...

Unconventional issues involving ajax and fundamental data submission

Upon submitting the ajax request, I need to send three data parameters to process.conversation.php: method, s_state, and c_id. The values for s_state and c_id are retrieved from two input fields. After testing with alert(s_state) and alert(c_id), both vari ...

Retrieve the inner object contained within a JSON file

I have encountered an issue while trying to parse a specific json format on android. The json structure is as follows: {"header": { "param": "param" }, "body": { "param": "1", "param2": "2", "param3": [ ...

Implementing array values into a jQuery graph syntax

After json encoding from php, I have an array that contains information on different categories: [{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":" ...

When attempting to decode the JSON response.body, an issue arises as it is not functioning as expected

I need assistance... I attempted the following code: * try { final response = http.get(url); // This is where the error occurs final extractedData = json.decode(response.body); } catch (error) { throw error; ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Is the API call being executed while sending JSON as a parameter?

Currently, I am in the process of working with an API known as "Active Collab" and my goal is to create a custom report. API::get('/users/3/time-records/filtered-by-date') Query Parameters: { "from": "2014-12-01", "to": "2014-12-31" } ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...

Code written in Javascript runs before any CSS files are downloaded and processed

While researching async scripting in web applications, I stumbled upon an interesting article. Essentially, it suggests that JavaScript scripts are not executed until all stylesheet CSS files are downloaded and parsed. Intrigued by this concept, I decided ...