Nic*_*ick 10 filtering dart dropdown flutter
我在本地 json 中有一个国家名称列表。我可以加载我的本地 json 并分配给DropDown button。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"
},
Run Code Online (Sandbox Code Playgroud)
You can use searchable_dropdown package instead: https://pub.dev/packages/searchable_dropdown
And here is my example code searchable_dropdown dont work with class list
Make sure that you put the following if you use a class list like my example
@override
String toString() {
return this.key;
}
Run Code Online (Sandbox Code Playgroud)
一种方法是使用 aTextEditingController来过滤您的内容,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,
));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17560 次 |
| 最近记录: |