Flutter - 应该只有一项具有 [DropdownButton] 的值......提供者出错

Flutter - There should be exactly one item with [DropdownButton]'s value... error with provider

我有一个下拉菜单。 我的目标是让用户选择下拉菜单的值。 在此之后,该值应显示为下拉菜单上方的列表。 我正在使用 Provider 将选择的值存储在列表中。 但是当我让列表监听提供者模型的变化时,我得到了下拉菜单的错误。我不知道为什么我在重建过程中会出错...

Provider.of<InspectionFormModel>(context, listen: true).removeAbleObjects!=null?ListView(
                      shrinkWrap: true,
                      key: ObjectKey(Provider.of<InspectionFormModel>(context, listen: false).removeAbleObjects),
                      children: Provider.of<InspectionFormModel>(context, listen: false).removeAbleObjects!=null?Provider.of<InspectionFormModel>(context, listen: false).removeAbleObjects!.map((e) => e).toList():[Container()]
                    ):Visibility(child: Container(),visible: false,),
                    CustomDropdown(items: [DropDownObject("text",1),DropDownObject("textsoundso",2)], hintText: inspectionObject, provider: "inspection",value:"device",),

我的下拉按钮:

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';


class CustomDropdown extends StatefulWidget {
  final List<DropDownObject> items;
  //final List<dynamic>? objects;
  final String hintText;
  final String? provider;
  final String? value;
  final bool useId;

  const CustomDropdown({Key? key,
    this.useId=false,
    this.value,
    this.provider,
    this.hintText="",
    required this.items}) : super(key: key);

  @override
  State<CustomDropdown> createState() => _CustomDropdownState();
}

class _CustomDropdownState extends State<CustomDropdown> {


  @override
  void initState() {
    developer.log("init dropdown");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    DropDownObject? selectedValue=null;
  


    return Padding(
      padding: EdgeInsets.only(right: 15),
        // child: DropdownButtonHideUnderline(
          child: DropdownButtonFormField2<DropDownObject>( 

            validator: (value) {
              if (value == null ) {
                return 'Bitte wählen Sie einen Wert aus.';
              }
              return null;
            },
            buttonHeight: 50,
            decoration: InputDecoration(
              // errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red),borderRadius: BorderRadius.circular(10)),
                enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent)
                )
            ),//InputDecoration.collapsed(hintText: ""),//
            hint: Padding(padding: EdgeInsets.only(left: 10),child: Text(widget.hintText, style: AppTextStyle().formText,)),
            isExpanded: true,
            dropdownDecoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: AppColors().grey,
              ),
            ),
            buttonDecoration: BoxDecoration(
              color: AppColors().formFieldColor,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: AppColors().grey,
              ),
            ),
            items: widget.items.map((item) =>
                DropdownMenuItem<DropDownObject>(
                  value: item,
                  child: Row(children:[
                    Expanded(child: Text(item.text, textAlign: TextAlign.left,))
                  ],)
                )).toList(),
            // value:selectedValue,
            onChanged: (value) {
              setState(() {
                selectedValue=value;
                //selectedValue = value;
                //widget.useId?widget.provider??FormProviderSelection().writeValueToProviderObject(context, widget.provider!,widget.value!,selectedValue!):
                FormProviderSelection().writeValueToProviderObject(context, widget.provider!,widget.value!,value!);//widget.provider??
              });
            },
            icon: const Icon(Icons.arrow_drop_down_rounded),
            iconEnabledColor: AppColors().grey,
            iconDisabledColor: Colors.white54,
            dropdownMaxHeight: 200,
            dropdownElevation: 8,
          ),
        // ),
    );
  }
}

更新2022-01-22

class DropDownObject{
  String text;
  int? dropDownObjectId;

  DropDownObject(this.text, [this.dropDownObjectId]);
}

也许你有两个或更多相同的DropDownObject。或者你有 null DropDownObject.

检查这部分代码。

items: widget.items.map((item) =>
                DropdownMenuItem<DropDownObject>(
                  value: item,
                  child: Row(children:[
                    Expanded(child: Text(item.text, textAlign: TextAlign.left,))
                  ],)
                )).toList(),

尝试添加过滤器:

widget.items
.where((e) => e != null) //removes null items
.toSet() // removes duplicate items
.map

也在你的模型中实现 == 和 hashcode class:

class DropDownObject{
  String text;
  int? dropDownObjectId;

  DropDownObject(this.text, [this.dropDownObjectId]);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is DropDownObject && runtimeType == other.runtimeType && text == other.text;

  @override
  int get hashCode => text.hashCode;


}