我在本地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"
},
答案 0 :(得分:6)
您可以改用searchable_dropdown软件包: https://pub.dev/packages/searchable_dropdown
这是我的示例代码 searchable_dropdown dont work with class list
如果使用类列表(如我的示例),请确保输入以下内容
@override
String toString() {
return this.key;
}
答案 1 :(得分:1)
一种方法是使用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,
));
}
}
答案 2 :(得分:0)
我找到了另一个插件。
它具有很多功能(例如InputDecoration
),看起来像TextFormField()
。因此,您的用户界面将相同。
我建议您使用这个出色的插件:dropdown_search