首页 > 解决方案 > 从获取数据创建下拉列表

问题描述

我只是在学习颤振,我正在尝试从帖子数据中创建一个下拉列表。现在我只是在使用公共的 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.

标签: flutter

解决方案


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

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

你的下拉菜单看起来像->在此处输入图像描述


推荐阅读