How to populate data from Django REST API endpoint with flutter Dropdown widget

1,282

Try this:

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

States is a class containing id and name attributes and you are trying to access them via states['id'] which for Json. So you have to access them via states.id and states.name respectively.

Share:
1,282
Azeez Akinsola
Author by

Azeez Akinsola

Updated on December 09, 2022

Comments

  • Azeez Akinsola
    Azeez Akinsola over 1 year

    I have a backend build with Django REST, with some endpoints. I need to display the list of a Country states with Flutter dropdown widget. But I am finding it difficult to display the list of states in a dropdown. What am I getting wrong and how do I go about getting it to work.

    I have followed this guide on flutter doc https://flutter.io/docs/cookbook/networking/background-parsing

    but I am still not getting it to work.

    Here is the error I am getting.

    
    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
    
    
    
    

    Below is a sample of 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,
          ),
        );
      }
    }
    
    
  • Azeez Akinsola
    Azeez Akinsola about 5 years
    The error disappear when I tried that. But I am getting another error on the dropdown widget: imgur.com/a/aFPB33z
  • Shahzad Akram
    Shahzad Akram about 5 years
    Make sure your API response is not null , verify it by print(response.body) in debug mode..
  • Azeez Akinsola
    Azeez Akinsola about 5 years
    I was able to fix it by changing the states into map. I updated the code to effect the changes. Thanks @Akram