如何使用flutter Dropdown小部件从Django REST API端点填充数据
Posted
技术标签:
【中文标题】如何使用flutter Dropdown小部件从Django REST API端点填充数据【英文标题】:How to populate data from Django REST API endpoint with flutter Dropdown widget 【发布时间】:2019-07-10 12:34:41 【问题描述】:我有一个使用 Django REST 构建的后端,带有一些端点。我需要使用 Flutter 下拉小部件显示国家/地区的列表。但是我发现很难在下拉列表中显示状态列表。我做错了什么,我该如何让它发挥作用。
我在 Flutter 文档 https://flutter.io/docs/cookbook/networking/background-parsing 上遵循了本指南
但我仍然无法正常工作。
这是我遇到的错误。
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
下面是我的代码示例:
端点
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,
),
);
【问题讨论】:
【参考方案1】:试试这个:
items: states.map((States states)
return DropdownMenuItem<String>(
value: states.id.toString(),
child: Text(
states.name.toString,
style: TextStyle(
color: Colors.white,
),
),
);
).toList(),
States 是一个包含 id 和 name 属性的类,您正试图通过 states['id']
访问它们,这对于 Json。所以你必须分别通过states.id
和states.name
访问它们。
【讨论】:
当我尝试时错误消失了。但我在下拉小部件上遇到另一个错误:imgur.com/a/aFPB33z 确保您的 API 响应不为 null ,在调试模式下通过print(response.body)
进行验证..
我能够通过将状态更改为地图来修复它。我更新了代码以实现更改。谢谢@Akram以上是关于如何使用flutter Dropdown小部件从Django REST API端点填充数据的主要内容,如果未能解决你的问题,请参考以下文章
如何从自动完成小部件 Flutter 中使用 TextEditingController