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

How to make a dynamic dropdownbutton list in Flutter ? (delete items)

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

使用setState()方法,所以每次调用这个方法时,你的DropDownButton都会重绘。

Documentation : Widget setState()

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

  • 我已经用 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(),
        ),
      ],
    );
  }
}