[英]How to populate data from Django REST API endpoint with flutter Dropdown widget
I have a backend build with Django REST, with some endpoints.我有一个带有 Django REST 的后端构建,带有一些端点。 I need to display the list of a Country states with Flutter dropdown widget.我需要使用 Flutter 下拉小部件显示国家/地区列表。 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我已经在 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模型.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服务.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 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,
),
);
}
}
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. States 是一个包含 id 和 name 属性的类,您正在尝试通过states['id']
访问它们,这对于 Json。 So you have to access them via states.id
and states.name
respectively.所以你必须分别通过states.id
和states.name
访问它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.