【发布时间】:2021-10-13 09:40:58
【问题描述】:
我只是在学习颤振,我正在尝试从帖子数据中创建一个下拉列表。现在我只是在使用公共 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 数据,请参考我的回答 here]
-
您好,感谢您回复我。我查看了您的答案,您的代码看起来与我的代码几乎相同,但它仍然无法正常工作。我进行了一些更改以匹配它,但它没有工作。关于为什么这可能不起作用的任何其他想法?
-
你好@Alex Childs 请检查我的回答希望你的问题得到解决
标签: flutter