问题
I Implemented a flutter dropdown menu using searchable_dropdown 1.1.0 package,, I tested with my class list, and I found that the search TextField box dont work with my list of class. I want that my dropdown search box works when I search for a value in both strings/intgers in my list.
for example: I want that when I type number 1 or key 1 it should show me the item I searched for
I wonder how to fix this problem? Thanks for help
Here is my code.
import 'package:flutter/material.dart';
import 'package:searchable_dropdown/searchable_dropdown.dart';
get_list(){
List<KeyValueModel> datas = [
KeyValueModel(key: "Key 1", value: "Value 1"),
KeyValueModel(key: "Key 2", value: "Value 2"),
KeyValueModel(key: "Key 3", value: "Value 3"),
KeyValueModel(key: "Key 4", value: "Value 4"),
KeyValueModel(key: "Key 5", value: "Value 5"),
];
return datas;
}
//Create a Model class to hold key-value pair data
class KeyValueModel {
String key;
String value;
KeyValueModel({this.key, this.value});
}
class Test extends StatefulWidget {
@override
TestState createState() {
return new TestState();
}
}
class TestState extends State<Test> {
List listan = get_list();
KeyValueModel _selectedValue = KeyValueModel(key: "0", value: "value");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Key value Pair - DropdownButton'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
SearchableDropdown<KeyValueModel>(
isCaseSensitiveSearch: true,
items: listan
.map((data) => DropdownMenuItem<KeyValueModel>(
child: Text(data.key),
value: data,
)).toList(),
onChanged: (KeyValueModel value) {
setState(() => _selectedValue = value);
},
hint: Text('Select Key'),
),
SizedBox(
height: 25.0,
),
Text(_selectedValue.value),
],
),
),
);
}
}
回答1:
Here is a bit source code from the package.
...
if(widget.isCaseSensitiveSearch){
isContains = item.value.toString().contains(keyword);
}
else{
isContains = item.value.toString().toLowerCase().contains(keyword.toLowerCase());
}
...
It calls toString()
on the value
. In your case value
is type of KeyValueModel
and doesn't have an overriden toString()
method. So it returns Instance of KeyValueModel
instead of Key 1
or so.
Here is the class that returns the key
when toString()
method called.
class KeyValueModel {
String key;
String value;
KeyValueModel({this.key, this.value});
@override
String toString() {
return this.key;
}
}
来源:https://stackoverflow.com/questions/60025636/searchable-dropdown-dont-work-with-class-list