微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Flutter 中制作动态下拉按钮列表? 删除项目

如何解决如何在 Flutter 中制作动态下拉按钮列表? 删除项目

我对 Flutter 中的下拉按钮有疑问。为了快速起见,我在 Cloud Firestore 中有一个城市列表,用于制作下拉按钮的列表(项目)。这个城市列表是通过 StreamBuilder 获取的,因此当我更改城市名称时,它会实时更改。这里的问题是,如果我选择例如“纽约”并在 Cloud Firestore 中删除“纽约”,则下拉按钮找不到值“纽约”。我想知道下拉按钮是否有可能重建并选择有效值或其他方式来管理下拉按钮中值的删除

解决方法

使用 setState() 方法,因此每次调用此方法时,都会重绘您的 DropDownButton

Documentation : Widget setState()

enter image description here

这是您正在寻找的解决方案:

  • 我已经用 ElevatedButton() 演示了它,它在点击时会使用您的“Firestore 值”更新您的列表值,并通过 setState() 方法重新绘制 DropDownButton :

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class DropdownMenu extends StatefulWidget {
  const DropdownMenu({Key? key}) : super(key: key);

  @override
  State<DropdownMenu> createState() => _DropdownMenuState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _DropdownMenuState extends State<DropdownMenu> {
  var dropdownValue;

  String hintValue = 'Tout de Suite';
  List<String> values = [
    'Initial value 1',"Initial Value 2",'Initial value 3',"Initial Value 4",];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () {
            setState(() {
              values = [
                'New value from Firebase',"Values edited from firebase"
              ];
            });
          },child: Text("Update with current Firestore values "),),DropdownButton<String>(
          value: dropdownValue,hint: Text(
            hintValue,underline: Container(
            height: 0,onChanged: (String? newValue) {
            setState(() {
              hintValue = newValue!;
            });
          },items: values.map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,child: Text(
                value,style: TextStyle(color: Colors.black),);
          }).toList(),],);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。