Tips for fetching data from a Django REST API endpoint and displaying it in a Flutter Dropdown widget

I am currently working on a project that involves using Django REST for the backend with Flutter dropdown widget to display a list of Country states. However, I am facing challenges in getting the list of states to appear in the dropdown menu. Can anyone provide guidance on where I may be going wrong and how to resolve this issue?

While trying to troubleshoot the problem, I came across a guide on the Flutter documentation website:

Despite following the guide, I am still unable to get it to work properly.

Below are the errors I encountered:


Compiler message:
lib/src/ui/musicrelease/song_upload_page.dart:458:26: Error: The method
'[]' isn't defined for the class '#lib1::States'.
Try correcting the name to the name
of an existing method, or defining a method named '[]'.
            value: states['id'].toString(),
                         ^^
lib/src/ui/musicrelease/song_upload_page.dart:460:21: Error: The method '[]' isn't definedfor the class '#lib1::States'.
Try correcting the name to the name of an existing method, or defining a method named '[]'.
              states['name'],
                    ^^lib/src/ui/musicrelease/song_upload_page.dart:492:16: Error: Getter not found: 'data'.
        items: data.map((dropDownStringItem) {
               ^^^^
lib/src/ui/musicrelease/song_upload_page.dart:492:16: Error: The getter 'data' isn't defined for the class '#lib1::SongUploadPageState'.
Try correcting the name to the name of an existing getter, or defining a getter or field named 'data'.        items: data.map((dropDownStringItem) {
               ^^^^
Compiler failed on C:\Users\AZEEZ\IdeaProjects\vibespotcodebase\vibespot\lib/main.dartGradle task 'assembleDebug'... Done                         60.1s
Gradle task assembleDebug failedwith exit code 1



Here is an excerpt from my code:

Endpoint

http://localhost/api/state/

model.dart

 import 'dart:convert';

List<States> parseStates(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<States>((json) => States.fromJson(json)).toList();
}

class States {
  String id;
  String name;
  String countryId;

  States({
    this.id,
    this.name,
    this.countryId,
  });

  factory States.fromJson(Map<String, dynamic> json) => new States(
        id: json["id"],
        name: json["name"],
        countryId: json["country_id"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "country_id": countryId,
      };
}

services.dart

import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:vibespot/src/models/dashboard/state_model.dart';


Future<List<States>> fetchStates() async {
  final response = await http.get('http://localhost:8000/api/state/');
final responsebody = parseStates(response.body);
setState(() {
      states = responsebody;

    });
  return parseStates(response.body);
}

ui.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:vibespot/src/models/dashboard/state_model.dart';
import 'package:vibespot/src/services/dashboard/state_local_services.dart';
import 'dart:io';

class SongUploadPage extends StatefulWidget {
  @override
  SongUploadPageState createState() => SongUploadPageState();
}

class SongUploadPageState extends State<SongUploadPage> {
  var _currentItemSelected ;
  String _mySelection;
  List<States> states = [];

 @override
  void initState() {
    super.initState();
    fetchStates();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Track",
            style: TextStyle(
              fontSize: 25,
              color: Colors.orange.shade700,
            )),
      ),

      body: Center(
        child: ListView(
            shrinkWrap: true,
            padding: EdgeInsets.only(left: 20.0, right: 20.0),
            children: <Widget>[
              stateList(),
              SizedBox(height: 20.0),
              submitReleaseBotton(),
            ]),
      ),
    );
  }

  Widget stateList() {
    return Container(
      // color: Colors.black,
      child: DropdownButtonFormField<String>(
        decoration: InputDecoration(
          hintText: 'Select State',
          filled: true,
          fillColor: Colors.white,
          hintStyle: TextStyle(color: Colors.black),
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
          // labelText: 'Number of tracks'
        ),
        items: states.map((States map) {
          return DropdownMenuItem<String>(
            value: map.id.toString(),
            child: Text(
              map.name,
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          );
        }).toList(),
        onChanged: (String newValueSelected) {
          setState(() {
            this._currentItemSelected = newValueSelected;
          });
        },
        value: _currentItemSelected,
      ),
    );
  }
}

Answer №1

Here is a suggestion for you to try:

items: states.map((States states) {
  return DropdownMenuItem<String>(
    value: states.id.toString(),
    child: Text(
      states.name.toString,
      style: TextStyle(
        color: Colors.white,
      ),
    ),
  );
}).toList(),

The "States" class includes attributes for id and name, so make sure you are accessing them correctly using states.id and states.name. Avoid trying to access them with square brackets like in states['id'], as this syntax is used for Json objects.

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

Assign a unique value to every line in a JSON string within the Vue.js hierarchy of components

I created a Vue component that initializes an empty list and an object like this: data: function(){ return { list: [], newThing: { body: '', }, }; }, The list is then populated with JSON data fetched ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

Python Tutorial: Decoding JSON Objects with Unicode Encoding

I recently stored a JSON object in a file using the repr function like so: f = open('file', 'w') f.write(repr(my_json)) f.close() After saving, I noticed that the JSON data now has leading 'u' characters denoting unicode enc ...

Displaying a single row in an Android ListView by iterating through json_encode with PHP

I am looking to extract JSON data from a PHP file that has been looped and then insert it into an array list (ListView) within my Android activity. However, I am encountering an issue where only one row from the JSON is being displayed in the ListView, spe ...

Performing a wildcard search to replace deep child values and merging them back into the original JSON using JQ

Can someone help me with a JSON manipulation issue similar to the one discussed in this post about Unix jq parsing wildcards? I want to change the value of "c": "text1" to "c": "newtext", while also merging the modif ...

AngularJS request has exceeded the time limit

Although this question may have been asked before, I couldn't find a solution. It's currently 10:30pm and I really need help from you guys! The issue I'm facing involves two json server methods - one to update data and the other to get new ...

Encountering a JSON error when trying to create a chef-vault instance

I've been attempting to create a chef-vault on a Windows workstation, but I keep encountering the following error: ERROR: JSON::ParserError: {username: root, password: mypassword} is not valid JSON! $PS C:\Users\09242766> knife vault create ...

What is the best method for extracting list data from SharePoint Online and saving it as a csv or json file?

Having successfully accessed a list in SharePoint Online using Python, I am now looking to save the list data into a file (either csv or json) in order to manipulate and organize some metadata for a migration process I have all the necessary access creden ...

Importing Json in Angular 8: A detailed guide

I recently came across information that you can now directly import JSON in TypeScript 2.9 and made changes to my tsconfig.json file accordingly: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", " ...

Transmitting JSON data to a Flask template

I struggled to figure out how to retrieve JSON data from my search results, but I've managed to solve that issue. Now, the challenge is updating my jinja template with the data I fetched. Despite attempting various methods, my lack of experience with ...

The JSONObject contains a value, however it may sometimes return a null value

[ { "valve": "4679", "selling": "5516", "bal": "9075.4", "o id": "37", "invested": "11122", //<<<<<<<- this value returns null "aProfit": "1012", //<<<<<<<- this value returns null ...

Ways to prevent API requests from being repeatedly made within a specified time frame

Currently, I am utilizing Rest API in conjunction with node js. My specific requirement involves the need to implement a blocking mechanism for repeated requests received within a defined time frame of 15 minutes (as tokens expire after this period). The ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...

"Utilize URL parameters to specify a date range when working with Django Rest

In my JSON structure, I have data entries with timestamps and names: [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12- ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Angular 2 now has the ability to detect keydown events triggered from any part of the page

Is there a way to enable keyboard control for a view? I attempted using document.keydown, but it wasn't successful. How can I make the document accept keyboard input? A solution that worked for me was implementing this in my component class: @HostLi ...

Getting access to UBER's authorize API is a straightforward process that involves following a few steps to retrieve

I have been attempting to retrieve the code from JSON using a specific URL in Postman, unfortunately, I have not been successful in obtaining the code in JSON format. Click here for Uber login Furthermore, when I access this URL in my browser, I am redir ...

What is the best way to retrieve my data/json from req.body in Express?

Recently, I started working with node.js and encountered an issue while trying to access JSON data on my node.js server through a post request. The goal is to send this data to an API and then pass it back to my front-end JavaScript file. Despite being abl ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Improving the Efficiency of Database Queries in Ruby on Rails

Currently, my team and I are collaborating on a Rails side project that involves loading a substantial amount of seed data. This data is stored in a JSON document with nearly 3200 JSON objects, each having the same three field names. After parsing and see ...