【问题标题】:Creating a dropdown from get data从获取数据创建下拉列表
【发布时间】: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


【解决方案1】:

我刚刚找到了我的代码不起作用的原因。所以对于未来的任何人,我都启用了空安全,所以我尝试将我的选择持有者(上面称为_mySelection)初始化为一个空字符串,但在数据库中没有找到。通过使用String? _mySelection,我可以允许该值为null,因此在首次加载列表时没有错误,然后您可以从列表中选择一个选项。

【讨论】:

    【解决方案2】:

    试试下面的代码希望对你有帮助。

    创建您的 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);
                });
              },
            ),
          ),
    

    你的下拉菜单看起来像 ->

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2018-01-18
      • 2018-02-23
      • 1970-01-01
      相关资源
      最近更新 更多