【问题标题】:How to create TextformField with Dropdown button to show list of icons and text in flutter如何使用下拉按钮创建 TextformField 以在颤动中显示图标和文本列表
【发布时间】:2021-05-25 08:53:26
【问题描述】:

我是 Flutter 的新手,我想在 Flutter 的 TextformField 中创建一个图标和文本的下拉列表。就像银行图标和它的名字一样。请查看屏幕截图并建议我任何代码。先感谢您。请帮忙。

【问题讨论】:

    标签: flutter dart dropdown textformfield


    【解决方案1】:

    可能使用 DropdownButton 类,https://api.flutter.dev/flutter/material/DropdownButton-class.html

    在文档页面上,您可以看到不包含图标的示例代码。

    您可以通过将 items 参数更改为让 Row 包装图标和文本小部件来向下拉项目添加图标。

    见:https://dartpad.dev/b742bde3465a616f8787c434415c9e3e?null_safety=true

     items: <String>['One', 'Two', 'Free', 'Four']
              .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Row(
                children: [
                  Icon(Icons.close),
                  Text(value),
                ],
              ),
            );
          }).toList(),
    

    【讨论】:

    • 感谢@Joran Dob 的回复,这对我有所帮助,但这不是完整的解决方案。谢谢x
    【解决方案2】:
    ...
    //custom object
    class Item{
      String name; //set the item name
      Icon icon; //set corresponding icon
    }
    Item selectedItem;
    List<Item> itemList = []; //create a list of the items, you need to add items into it first
    
    DropdownButton<Item>(
                    isExpanded: true,
                    hint: new Text("Select Item"),
                    value: selectedItem ,
                    icon: Icon(Icons.arrow_drop_down_circle),
                    iconSize: 24,
                    elevation: 16,
                    style: TextStyle(color: Colors.blueAccent),
                    underline: Container(
                      height: 2,
                      color: Colors.blue,
                    ),
                    onChanged: (Item newValue) {
                      setState(() {
                        selectedItem = newValue;
                      });
                    },
                    items: itemList.map<DropdownMenuItem<Item>>((Item value) {
                      return DropdownMenuItem<Item>(
                        value: value,
                        child: Row(
                          //set alignment here
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Icon(value.icon), //in here you can display the icon
                            Text(value.name), //name of the item
                          ],
                      );
                    }).toList(),
                  )
    

    【讨论】:

    • 感谢您的回复,此示例提供了正确的解决方案,但我有一个问题,我在分配“value: selectedItem”时出错,我不知道哪个类型的变量是 selectedItem。请告诉我“selectedItem”是哪个类型变量?
    • 抱歉回复晚了,selectedItem应该是一个Item类对象。我已经编辑了上面的例子。
    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多