无法通过 Flutter 中的 API 调用呈现 DropdownMenu 中的数据

2023-12-08

我正在尝试在我的项目中创建一个下拉菜单,其中需要在列表中显示的数据源自 API 调用,其响应如下所示。但是,我收到以下错误消息,并且我不知道如何解决此问题:

There should be exactly one item with [DropdownButton]'s value: . 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
package:flutter/…/material/dropdown.dart:1
Failed assertion: line 894 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

我打算使用的 JSON 响应(我需要显示name在我的下拉列表中):

[
    {
        "id": 3,
        "name": "Fruits and Vegetables",
        "active": true
    },
    {
        "id": 4,
        "name": "Grocery and Staples",
        "active": true
    }
]

这是我的代码:

class AddProductsPageState extends State<AddProductsPage> {
  final GlobalKey<FormState> _key = GlobalKey<FormState>();
  String dropDownValue = '';
  List<dynamic> list = [];
  bool isLoading = true;

  @override
  void initState() {
    // TODO: implement initState
    Provider.of<CategoryProvider>(context, listen: false)
        .getCategories()
        .then((_) {
      setState(() {
        isLoading = false;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    final provider = Provider.of<CategoryProvider>(context).categoryList;
    list = provider;

    print('LIST $list');

    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        automaticallyImplyLeading: false,
        elevation: 0,
        centerTitle: true,
        leading: InkWell(
          onTap: () => Navigator.of(context).pop(),
          child: Padding(
            padding: EdgeInsets.only(
                left: width * 0.005,
                top: height * 0.003,
                right: width * 0.005,
                bottom: height * 0.003),
            child: Container(
              width: width * 0.1,
              height: height * 0.1,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                  boxShadow: const [
                    BoxShadow(
                      color: Colors.grey,
                      blurRadius: 10,
                      offset: Offset(1, 2),
                    )
                  ]),
              child: const Icon(Icons.arrow_back_ios, color: Colors.green),
            ),
          ),
        ),
        title: const Text(
          'Add Products',
          style: TextStyle(
              color: Color.fromARGB(255, 36, 71, 100),
              fontWeight: FontWeight.bold,
              fontSize: 25),
        ),
      ),
      body: isLoading
          ? const Center(
              child: CircularProgressIndicator(
                color: Colors.green,
              ),
            )
          : Container(
              width: double.infinity,
              height: double.infinity,
              // color: Colors.red,
              padding: EdgeInsets.all(width * 0.04),
              child: Form(
                key: _key,
                child: ListView(
                  children: [
                    const Text(
                      'Select Category',
                      style: TextStyle(
                          color: Color.fromARGB(255, 36, 71, 100),
                          fontWeight: FontWeight.bold,
                          fontSize: 15),
                    ),
                    DropdownButton(        //This is where the error is pointed at
                        value: dropDownValue ?? null,
                        items: provider.map((e) {
                          return DropdownMenuItem(
                            value: e,
                            child: Text(e['name']),
                          );
                        }).toList(),
                        onChanged: (value) {
                          setState(() {
                            dropDownValue = value.toString();
                          });
                        })
                  ],
                ),
              ),
            ),
    );
  }
}

任何帮助,将不胜感激


尝试下面的代码我想你的问题已经解决了。

您的 JSON 字符串、id 和列表声明

 String jsonString =
      '[ { "id": 3, "name": "Fruits and Vegetables", "active": true },{ "id": 4, "name": "Grocery and Staples", "active": true }]';
  String id;
  List data = [];

API函数:

 Future fetchJSONData() async {
    var jsonData = json.decode(jsonString);
    setState(() {
      data = jsonData;
    });
    return jsonData;
  }

调用你的APIfetchJSONData() inside initState()

  @override
  void initState() {
    super.initState();
    fetchJSONData();
  }

您的小部件:

Container(
        width: 200,
        child: InputDecorator(
          decoration: InputDecoration(
            border: OutlineInputBorder(),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton(
              isDense: true,
              isExpanded: true,
              value: id,
              hint: Text("Select Data", style: TextStyle(color: Colors.black)),
              items: data.map((list) {
                return DropdownMenuItem(
                  child: Text(list['name']),
                  value: list['id'].toString(),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  id = value as String;
                });
              },
            ),
          ),
        ),
      ),

Your DropdownButton Widget-> image

Your DropdownButton Data-> image

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法通过 Flutter 中的 API 调用呈现 DropdownMenu 中的数据 的相关文章