我知道,这个问题被问了很多次,但没有一个解决方案奏效.

在第一个下拉列表中有一个银行列表,在银行 Select 上,第一次 Select 分行后第二个下拉列表中正在为分行调用一个API,它工作正常,当银行再次被更改时,正在调用API来获取各个银行的分行,因为已经 Select 的分行有值,我试图在填充分行之前清除先前 Select 的分行的值,并使列表为空.问题来了,因为其他银行的分行面积也是相同的,但分行ID是唯一的.当分支列表为空或不具有相同的分支区域时,此时不会出现问题.

我试着用"过激"的方法比较分支,但不起作用.

这是BRANCH的模型类.

class Branch {
  final int? bankId;
  final int? branchId;
  final String? ifscCode;
  final String? descriptionEn;
  final dynamic descriptionLl;
  
  Branch({
    this.bankId,
    this.branchId,
    this.ifscCode,
    this.descriptionEn,
    this.descriptionLl,
  });

  factory Branch.fromJson(Map<String, dynamic> json) => Branch(
        bankId: json["bank_id"],
        branchId: json["branch_id"],
        ifscCode: json["ifsc_code"],
        descriptionEn: json["description_en"],
        descriptionLl: json["description_ll"],
      );
  
  @override
  String toString() {
    return descriptionEn.toString();
  }
  @override
  bool operator ==(dynamic other) {
    return other != null && branchId == other.branchId &&
        descriptionEn == other.descriptionEn;
  }
}

在获得分支的状态更改后,使上一个 Select 的分支为空

else if (state is GetBranchSuccessState) {
            
            selectedBranch = null;
            ifsc = null;
            branchList=[];
            branchList = state.data.data!;

          } 

每当 Select 与我第一次 Select 的银行相同的银行时,没有任何问题,似乎 Select 的价值正在存储中?

我的小工具

 BlocConsumer<InternalRegistrationBloc, InternalRegistrationState>(
        listener: (context, state) {
          if (state is GetBankSuccessState) {
            dismissProgress();
          } else if (state is GetBranchSuccessState) {
            dismissProgress();
          }
        },
        builder: (context, state) {
          if (state is GetBankSuccessState) {
            bankList = state.data.data!;
          } else if (state is GetBranchSuccessState) {
            selectedBranch = null;
            ifsc = null;
            branchList = [];
            branchList = state.data.data!;
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Form(
                key: _gformKey,
                child: Column(
                  children: [
                    QDropDownList(
                      title: 'Bank name',
                      dropdownList: bankList,
                      selectedItem: selectedBank,
                      isMandatory: isBankUser,
                      onChanged: (value) {
                        selectedBank = value;
                        if (selectedBank != null) {
                          bloc.add(BranchEvent(selectedBank!.bankId!));
                        }
                      },
                    ),
                    QDropDownList(
                      title: 'Branch name',
                      dropdownList: branchList,
                      selectedItem: selectedBranch,
                      isMandatory: isBankUser,
                      onChanged: (value) {
                        selectedBranch = value;
                        bloc.add(
                            SetIFSCCodeEvent(selectedBranch!.ifscCode!));
                      },
                    )
                  ],
                ),
              ),
            ],
          );
        },
      ),



 

在图像中,bank of india得到问题,因为分支列表包含与Axis Bank容器相同的分支区域名称,当我 Select Bank of rajshthan时,它没有问题,因为它没有分支列表.当 Select Axis Bank家银行时,没有发行和获得旧价值.

自定义下拉列表

import 'package:flutter/material.dart';


class QDropDownList extends StatefulWidget {
  final ValueChanged<dynamic> onChanged;
  final List<dynamic> dropdownList;
  final dynamic selectedItem;
  final bool isTitleAbove;
  final String title;
  final bool isMandatory;
  final String dropDownHint;
  final Icon arrowIcon;

  const QDropDownList(
      {super.key,
      required this.onChanged,
      required this.dropdownList,
      required this.selectedItem,
      this.isTitleAbove = true,
      this.title = 'Title',
      this.isMandatory = true,
      this.dropDownHint = 'Select',
      this.arrowIcon = const Icon(
        Icons.keyboard_arrow_down,
        size: 15,
      )});

  @override
  State<QDropDownList> createState() => _QDropDownListState();
}

class _QDropDownListState extends State<QDropDownList> {
  dynamic selectedItem;

  @override
  void initState() {
    super.initState();
    selectedItem = widget.selectedItem;
  }

  @override
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        widget.isTitleAbove
            ? Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: RichText(
                  text: TextSpan(
                      text: widget.title,
                      style: Theme.of(context).inputDecorationTheme.labelStyle,
                      children: [
                        TextSpan(
                            text: widget.isMandatory ? ' *' : '',
                            style: Theme.of(context)
                                .inputDecorationTheme
                                .labelStyle
                                ?.copyWith(color: Colors.red))
                      ]),
                ),
              )
            : const SizedBox(),
        Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: SizedBox(
              width: MediaQuery.of(context).size.width,
              child: DropdownButtonFormField<dynamic>(
                value: selectedItem,
                icon: widget.arrowIcon,
                isDense: true,
                isExpanded: false,
                style: Theme.of(context).dropdownMenuTheme.textStyle,
                hint: Text(widget.dropDownHint,
                    style: Theme.of(context).dropdownMenuTheme.textStyle),
                // ignore: prefer_is_empty
                items:widget.dropdownList.length>0? widget.dropdownList.map((data) {
                  return DropdownMenuItem<dynamic>(
                    value: data,
                    child: Text(
                      data.toString(),
                      style: Theme.of(context).dropdownMenuTheme.textStyle,
                    ),
                  );
                }).toList():[],
                onChanged: (dynamic value) {
                  setState(() {
                    selectedItem = value;
                    widget.onChanged(value);
                    debugPrint('Drop down change ---> $selectedItem');
                  });
                },
                validator: (value) {
                  if (widget.isMandatory) {
                    return value == null ? 'Field required' : null;
                  } else {
                    return null;
                  }
                },
              ),
            )),
      ],
    );
  }
}

enter image description here

推荐答案

问题出在QDropDownList人身上.小部件的值是selectedValue,但它的状态值是单独的selectedValue.这辆车只设在initState号.这意味着稍后当您将selectedValue设置为null时,它的状态不会改变,因为只有在initState中第一次初始化时才会发生这种情况.我的建议是将其从状态中完全删除,并依赖于小部件的selectedState.所以总而言之:

删除以下各行:

  dynamic selectedItem;

  @override
  void initState() {
    super.initState();
    selectedItem = widget.selectedItem;
  }

更改:

value: selectedItem,

value: widget.selectedItem,

并最终改变

            onChanged: (dynamic value) {
              setState(() {
                selectedItem = value;
                widget.onChanged(value);
                debugPrint('Drop down change ---> $selectedItem');
              });
            },

            onChanged: (dynamic value) {
              setState(() {
                widget.onChanged(value);
                debugPrint('Drop down change ---> $selectedItem');
              });
            },

Note that you don't need 至 set a selected state here because the widgets onChanged will take care of that

Flutter相关问答推荐

Flutter -如何从布局填充(对称水平)中排除小部件?

无法在主屏幕视图中设置当前日期容器'

如何使用底部导航栏修复此导航问题

我有一个问题:类型';()=>;Null';不是类型转换中类型';(Int)=>;void';的子类型

Flutter 图标记移动

如何处理平台游戏的对象冲突?

Flutter 构建 Web 分段故障 - 无法启动事件处理程序线程

使用 Flutter 显示/隐藏带有下拉抽屉动画的小部件

自定义类提供程序 Riverpod Flutter 中的可变变量

Flutter:注册 UI 出现 UI 问题(将注册框提升到顶部并向电话号码 pin 码添加一个框)

在 Dart 中按土耳其语字母顺序对字符串进行排序

用户文档 ID 与 Firestore 中的用户 ID 相同

Flutter 3.10 - 'window' 已弃用,不应使用

如何停止折线图的抖动

Flutter - 根据从第一个 DropdownButtonForm 中 Select 的内容在第二个 DropdownButton 上显示选项

如何在 cupertino switch flutter 中添加文本

通过点击缩略图加载全屏图像

在不丢失游戏状态的情况下从 Flame 游戏导航到 Flutter 小部件

Flutter中如何连续获取TextField的文本是否为空?

带有 Dismissible 和 Provider (NotifyListener) 的笨拙动画