This is how I implemented the TypeAheadField
which works fine and shows the dropdown suggestion box right after the user has clicked on the field.
TypeAheadField(
noItemsFoundBuilder: (context) => const SizedBox(
height: 50,
child: Center(child: Text("No user found!")),
),
suggestionsBoxDecoration: SuggestionsBoxDecoration(
color: Colors.deepPurple.shade50,
elevation: 4.0,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15),
bottomLeft: Radius.circular(15),
bottomRight: Radius.circular(15))),
textFieldConfiguration: TextFieldConfiguration(
controller: _allLeaveViewModel.searchController,
onChanged: (value) {
setState(() {
_allLeaveViewModel.isSearchTextNotEmpty.value =
value.isNotEmpty;
});
_allLeaveViewModel.updateList(value);
if (value.isEmpty) {
Utils.removeFocusFromSearch(context);
}
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.fromLTRB(
16.0, 12.0, 16.0, 12.0),
hintText: 'Filter by applicant',
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.5),
fontSize: 16),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(70),
borderSide: BorderSide.none,
),
suffixIcon: Obx(() {
return Visibility(
visible: _allLeaveViewModel
.isSearchTextNotEmpty.value,
child: IconButton(
icon: Icon(
Icons.cancel_outlined,
color: Colors.grey.shade700,
size: 25,
),
onPressed: () {
_allLeaveViewModel.clearSearchAndList();
},
),
);
}),
),
),
suggestionsCallback: (String pattern) {
return _allLeaveViewModel.getSuggestions(pattern);
},
itemBuilder:
(BuildContext context, String suggestion) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
children: [
const SizedBox(
width: 10,
),
Flexible(
child: Text(
suggestion,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16),
))
],
),
);
},
onSuggestionSelected: (suggestion) {
setState(() {
_allLeaveViewModel.isSearchTextNotEmpty.value =
suggestion.isNotEmpty;
});
_allLeaveViewModel.searchController.text =
suggestion;
_allLeaveViewModel.updateList(suggestion);
},
),
But now what I want is to show the dropdown suggestion box only after the user has typed at least 2 characters in the TypeAheadField
. can anyone please help me?
2
Answers
First option:
updating suggestionsCallback gives you in general more customization options as you have access to
String pattern
In the code above, we check the length of the
pattern
(the user’s input) in thesuggestionsCallback
. If the length is greater than or equal to 2, we call_allLeaveViewModel.getSuggestions(pattern)
to fetch the suggestions as before. If the length is less than 2, we return an empty list, effectively hiding the suggestions.Second option:
using
minCharsForSuggestions: 2,
There’s a property minCharsForSuggestions of the ThypeAheadField which you set to 2 and it would work as you want.