flutter - 从获取数据创建下拉列表
问题描述
我只是在学习颤振,我正在尝试从帖子数据中创建一个下拉列表。现在我只是在使用公共的 jsonplaceholder api,但是一旦我弄清楚它是如何工作的,就会把它转移到一个私有的 api 上。当我运行我的代码时,它给出了这个错误:
"There should be exactly one item with [DropdownButton]'s value: . \nEither zero or 2 or more [DropdownMenuItem]s were detected with the same value"
我尝试了几种不同的方法将数据传递到 DropdownMenuItem 字段中,但都没有成功。
这是我正在运行的代码,它非常简单:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
title: "Hospital Management",
home: MyApp(),
));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mySelection = "";
final String url = "https://jsonplaceholder.typicode.com/users";
List data = []; //edited line
Future<String> getSWData() async {
var res = await http
.get(Uri.parse(url), headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(resBody);
return "Sucess";
}
@override
void initState() {
super.initState();
this.getSWData();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Hospital Management"),
),
body: new Center(
child: new DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['name']),
value: item['id'].toString(),
);
}).toList(),
onChanged: (String? newVal) {
setState(() {
_mySelection = newVal!;
});
},
value: _mySelection,
),
),
);
}
}```
Feel free to critique any part of my code, like I said, I'm brand new to flutter and still learning the ropes.
解决方案
试试下面的代码,希望对你有帮助。
创建您的 API 调用函数和变量声明,并在控制台上检查您选择的 Id 名称
String userId;
List data = List();
String url = "https://jsonplaceholder.typicode.com/users";
//your all api call
Future fetchData() async {
var result = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
var jsonData = json.decode(result.body);
print(jsonData);
setState(() {
data = jsonData;
});
return jsonData;
}
//call your API fetchData() inside initState()
@override
void initState() {
super.initState();
fetchData();
}
创建您的下拉小部件
DropdownButtonHideUnderline(
child: DropdownButton(
value: userId,
hint: Text("Select Name",
style: TextStyle(color: Colors.black)),
items: data.map((list) {
return DropdownMenuItem(
child: Text(list['name']),
value: list['id'].toString(),
);
}).toList(),
onChanged: (value) {
setState(() {
userId = value;
print(userId);
});
},
),
),
推荐阅读
- python - 尝试在 Python 中使用 Selenium 提取文本只给出空格
- ios - 如何使电容器项目中的第三方cookies适用于ios
- ada - 为什么我的循环不变量可能不会被任何迭代保留?
- javascript - 如何按动态属性名称对对象数组进行排序?
- python - 如何使用 if 和标签文本设置密码?
- powerquery - PowerQuery 公式栏错误循环参考
- android - NullPointerException @ SavedStateHandle ViewModel w/ Hilt
- c++ - 带有指针的 C++ 分段错误和 0xfeeefeeefeeefeee 错误
- exception - 谁首先检测到异常?
- java - spring-mvc activiti 依赖实现