无法通过 Flutter 中的 API 调用在 DropdownMenu 中渲染数据

酷哈克7

我正在尝试在我的项目中创建一个下拉菜单,其中需要在列表中显示的数据来自 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();
                          });
                        })
                  ],
                ),
              ),
            ),
    );
  }
}

任何帮助,将不胜感激

拉文德拉·S·帕蒂尔

试试下面的代码,我认为你的问题已经解决了。

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

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

接口函数:

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

fetchJSONData()在里面调用你的 APIinitState()

  @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;
                });
              },
            ),
          ),
        ),
      ),

你的 DropdownButton 小部件->图片

您的下拉按钮数据->图片

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用API调用在Android中填充AutoCompleteTextView?

如何使用文本字段数据并通过flutter中的api调用进行计算?

通过API调用在Go中使用JSON数据

如何通过API调用在Android Studio中实现autocompletetextview?

通过ajax调用在XML文件中输出注释

异步API调用在单独的函数中

无法调用在javascript中的对象内部定义的方法

api调用在Shiny中变空时显示错误消息?

如何检查Retrofit API调用在Android中是否成功

如何在上下文中的Flutter中结合DropdownMenu和AppLocalization?

REST API调用在Lambda函数中失败

无法从React中的API渲染数据,未显示任何错误

如何通过dynatree中的ajax调用在URL中附加锚点?

JDK for Abstract Window Toolkit中的本机API调用在哪里

尝试解析JSON数据时通过递归调用在Android中获取StackOverFlowError

无法调用在类中定义的方法

Ajax调用在ASP MVC中无法正常运行

jQuery Ajax调用在IE中不起作用,JSON响应无法通过

如何通过mongo .find调用在Node.js中执行此回调调用

我无法在 flutter 中对特定 url 进行 REST api 调用

无法从 api 调用中获取 Json 数据

使用 `curl` 的 API 调用在 Swift 中不起作用

Azure API 调用在控制台应用程序中工作而不是在 MVC 中工作

Flutter 中 DropDownMenu 按钮中的 OnTap 函数

如何通过 api 调用在 react js 中添加多语言支持?

Hasura:通过 API 调用在运行时(动态)更改 Hasura 中的权限/架构

如何通过在flutter中调用API来动态添加行元素?

Vue.js 从 API 调用中渲染新数据

如何从 reactjs 中的 api 调用渲染单个数据