如何在flutter中显示下拉列表中的名称而不是选中的值?

t1rydlwq  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(161)

这是我的代码从firebase获取项目并显示在下拉列表中。下拉值只包含拨号代码。国旗和国家名称仅用于显示,而不是用于进一步存储在firebase中

`import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:stract/utils/custom_config.dart';

class DialCodeDropdown extends StatefulWidget {
  ValueNotifier dialCodeNotifier;
  DialCodeDropdown({required this.dialCodeNotifier});

  @override
  State<DialCodeDropdown> createState() => DialCodeDropdownState();
}

class DialCodeDropdownState extends State<DialCodeDropdown> {
  String dropdownvalue = "61";

  String urlImages = "";
  List<String> dialCode = [];
  List<String> countryCode = [];

  List<Map> codeAndImage = [];

  @override
  void initState() {
    print("Inside Init State");
    fetchDialCodeFromCollections();
    // dropdownvalue = dialCode.first;
    widget.dialCodeNotifier.value = dropdownvalue;

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 20,
      child: DropdownButton<String>(
        underline: SizedBox(),
        value: dropdownvalue,
        icon: VerticalDivider(
          color: Colors.black,
        ),
        items: codeAndImage.map((Map map) {
          return DropdownMenuItem<String>(
            value: map["dialCode"].toString(),
            child: Row(
              children: [
                Image.network(
                  map["image"],
                  width: 20,
                ),
                SizedBox(
                  width: 5,
                ),
                Text(map["country"].toString()),
                SizedBox(
                  width: 5,
                ),
                Text("+ ${map["dialCode"].toString()}"),
              ],
            ),
          );
        }).toList(),
        onChanged: (String? newValue) {
          print(newValue);
          setState(() {
            dropdownvalue = newValue!;
            widget.dialCodeNotifier.value = newValue;
          });
        },
      ),
    );
  }

  Future fetchImagesFromFirestore(path) async {
    try {
      await FirebaseStorage.instance
          .ref()
          .child(path)
          .getDownloadURL()
          .then((value) {
        setState(() {
          urlImages = value;
        });
      });
      return urlImages;
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> fetchDialCodeFromCollections() async {
    var data = await FirebaseFirestore.instance
        .doc("${CustomConfig.FS_MASTER_DATA}/CountryCodes")
        .get();
    data.exists
        ? {
            data.data()!.forEach((key, value) async {
              if (value["isActive"] == true) {
                await fetchImagesFromFirestore("/Country-Flags/$key.jpg")
                    .then((Element) {
                  setState(() {
                    codeAndImage.add({
                      "dialCode": value["DialCode"].toString(),
                      "country": value["Country"],
                      "image": Element.toString()
                    });
                  });
                });
                setState(() {
                  countryCode.add(key);

                  if (dialCode.contains(value["DialCode"]) != true)
                    dialCode.add(value["DialCode"]);
                });
              }
            })
          }
        : print("no data");
  }
}

'
输出如下所示:

但我需要以下输出..

如何实现这一点?(在下拉列表中显示国家名称,而不是在选定的值中显示)
更新:
这是我从下面的答案中得到的输出

erhoui1w

erhoui1w1#

你可以用selectedItemBuilder来解决这个问题
对于selectedItemBuilder,您的代码应如下所示

selectedItemBuilder: (context) =>codeAndImage.map((Map map) {
      return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.network(
              map["image"],
              width: 20,
            ),
            SizedBox(
              width: 5,
            ),
            Text("+ ${map["dialCode"].toString()}"),
          ],
        );
    }).toList()

已编辑我使用DropdownButton2dropdownWidth创建了两种不同宽度的显示和列表。

@override
  Widget build(BuildContext context) {
    return Container(
      height: 20,
      child: DropdownButtonHideUnderline(
        child: DropdownButton2<String>(
          value: dropdownvalue,
          dropdownDecoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(4),
            boxShadow: const [
              BoxShadow(
                color: Colors.black12,
                blurRadius: 6,
                spreadRadius: 2,
                offset: Offset(0, 4),
              )
            ],
          ),
          selectedItemBuilder: (context) => codeAndImage.map((Map map) {
            return Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.network(
                  map["image"],
                  width: 20,
                ),
                SizedBox(
                  width: 5,
                ),
                Text("+ ${map["dialCode"].toString()}"),
              ],
            );
          }).toList(),
          icon: VerticalDivider(
            color: Colors.black,
          ),
          dropdownWidth: 150,
          items: codeAndImage.map((Map map) {
            return DropdownMenuItem<String>(
              value: map["dialCode"].toString(),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.network(
                    map["image"],
                    width: 20,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(map["country"].toString()),
                  SizedBox(
                    width: 5,
                  ),
                  Text("+ ${map["dialCode"].toString()}"),
                ],
              ),
            );
          }).toList(),
          onChanged: (String? newValue) {
            print(newValue);
            setState(() {
              dropdownvalue = newValue!;
              widget.dialCodeNotifier.value = newValue;
            });
          },
        ),
      ),
    );
  }

我仍然不能把宽度与列表内容。

相关问题