如何在 Flutter DropDown 按钮中进行搜索

问题描述 投票:0回答:6

我有一个本地 json 格式的国家/地区名称列表。我可以加载本地 json 并分配给 DropDown 按钮。例如,json 文件中有 193 个国家/地区。如下所示。如果我想选择美国,用户必须一直向下滚动。如何输入国家/地区名称,例如;如果我用户输入 U 或 u,下拉列表可以进行快速过滤并列出所有以 U 开头的国家,例如美国。 如何在 Flutter DropDownbutton 项目中搜索

{
    "country": [
        {
            "countryCode": "AD",
            "countryName": "Andorra",
            "currencyCode": "EUR",
            "isoNumeric": "020"
        },
        {
            "countryCode": "AE",
            "countryName": "United Arab Emirates",
            "currencyCode": "AED",
            "isoNumeric": "784"
        },
        {
            "countryCode": "AF",
            "countryName": "Afghanistan",
            "currencyCode": "AFN",
            "isoNumeric": "004"
        },
        //...
    ]
}
dart flutter filtering dropdown
6个回答
9
投票

您可以使用 searchable_dropdown 包代替: https://pub.dev/packages/searchable_dropdown

这是我的示例代码 searchable_dropdown 不适用于班级列表

如果您使用像我的示例这样的类列表,请确保输入以下内容

  @override
  String toString() {
    return this.key;
  }

5
投票

一种方法是使用

TextEditingController
来过滤您的
ListView
,如下所示:

class YourPage extends StatefulWidget {
  @override
  State createState() => YourPageState();
}

class YourPageState extends State<YourPage> {
  List<Country> countries = new List<Country>();
  TextEditingController controller = new TextEditingController();
  String filter;

  @override
  void initState() {
    super.initState();
    //fill countries with objects
    controller.addListener(() {
      setState(() {
        filter = controller.text;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
        color: Colors.transparent,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            new Padding(
                padding: new EdgeInsets.only(top: 8.0, left: 16.0, right: 16.0),
                child: new TextField(
                  style: new TextStyle(fontSize: 18.0, color: Colors.black),
                  decoration: InputDecoration(
                    prefixIcon: new Icon(Icons.search),
                    suffixIcon: new IconButton(
                      icon: new Icon(Icons.close),
                      onPressed: () {
                        controller.clear();
                        FocusScope.of(context).requestFocus(new FocusNode());
                      },
                    ),
                    hintText: "Search...",
                  ),
                  controller: controller,
                )),
            new Expanded(
              child: new Padding(
                  padding: new EdgeInsets.only(top: 8.0),
                  child: _buildListView()),
            )
          ],
        ));
  }

  Widget _buildListView() {
    return ListView.builder(
        itemCount: countries.length,
        itemBuilder: (BuildContext context, int index) {
          if (filter == null || filter == "") {
            return _buildRow(countries[index]);
          } else {
            if (countries[index].countryName
                .toLowerCase()
                .contains(filter.toLowerCase())) {
              return _buildRow(countries[index]);
            } else {
              return new Container();
            }
          }
        });
  }

  Widget _buildRow(Country c) {
    return new ListTile(
        title: new Text(
          c.countryName,
        ),
        subtitle: new Text(
          c.countryCode,
        ));
  }
}

1
投票

您可以使用 dropdown_search 包,如下所示。

import 'package:dropdown_search/dropdown_search.dart';

DropdownSearch<String>(
    popupProps: PopupProps.menu(
        showSearchBox: true,
        showSelectedItems: true,
        disabledItemFn: (String s) => s.startsWith('I'),
    ),
    items: ["Brazil", "Italia (Disabled)", "Tunisia", 'Canada'],
    dropdownDecoratorProps: DropDownDecoratorProps(
        dropdownSearchDecoration: InputDecoration(
            labelText: "Menu mode",
            hintText: "country in menu mode",
        ),
    ),
    onChanged: print,
    selectedItem: "Brazil",
)

确保您已在

showSearchBox
下设置
popupProps
属性。文档中尚未提及此属性。有关更多属性,请参阅 PopupProps 源代码


0
投票

使用textfield_search:^0.8.0 插件 view sample

            TextFieldSearch(
            decoration: InputDecoration(
              hintText: "Search",
              prefixIcon: Icon(
                Icons.search,
                color: Colors.black45,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8.0),
                borderSide: BorderSide.none,
              ),
              filled: true,
              fillColor: Colors.grey[200],
            ),
            initialList: constants.VEHICLELIST,
            label: "label",
            controller: selectedVehicle),

0
投票

我认为这有点旧了,因为现在仅使用附带的材料包并利用 DropDownMenu 小部件就可以了。 您可以使用

enableFilter: True
属性来启用手动搜索。 如果您以某种方式单击小部件并且它不允许您输入搜索内容,那么添加属性
requestFocusOnTap: true
特别有帮助,尤其是在 ListViews / ListTiles / Scrollables Cards

DropdownMenu<CountryEntity>(
        controller: countryController,
        label: const Text('Country'),
        width: 300,
        dropdownMenuEntries: countryEntities,
        enableFilter: true,
        menuStyle: const MenuStyle(
            alignment: Alignment.bottomLeft,
            maximumSize:
                MaterialStatePropertyAll(Size.fromHeight(Sizes.p124)),),
        requestFocusOnTap: true,
        onSelected: (country) {
          setState(() {
            selectedCountryId = country;
          });
        },
      );

0
投票

尝试使用dropdown_search它是我迄今为止发现的最好的下拉搜索

© www.soinside.com 2019 - 2024. All rights reserved.