I am new to Flutter and trying to implement an Autocomplete widget. I have taken the example from the Flutter docs, attempting to modify it only to pass in a list for the options rather than declaring it in the widget. The autocomplete functionality does not seem to be working correctly. It will identify spans of a matching string, but it only does this beyond the first letter. For example, given a list of [‘Luke’, ‘James’, ‘Mike’, ‘Bill’, ‘Ron’, ‘Doug’], when typing "L" I will only get a match of "Bill" (and no "Luke"), but both "Luke" and "Doug" will be returned if i type in "u".
Here is the code I am using:
import 'package:flutter/material.dart';
List<String> options = ['Luke', 'James', 'Mike', 'Bill', 'Ron', 'Doug'];
void main() => runApp(const AutocompleteExampleApp());
class AutocompleteExampleApp extends StatelessWidget {
const AutocompleteExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Autocomplete Basic'),
),
body: Center(
child: AutocompleteBasicExample(optionsList: options),
),
),
);
}
}
class AutocompleteBasicExample extends StatelessWidget {
AutocompleteBasicExample({required this.optionsList});
final List<String> optionsList;
@override
Widget build(BuildContext context) {
return Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<String>.empty();
}
return optionsList.where((String option) {
if (textEditingValue.text.contains(option)) {}
return option.contains(textEditingValue.text.toLowerCase());
});
},
onSelected: (String selection) {
print('You just selected $selection');
},
);
}
}
Here is an example of what I see on the simulator when typing "L":
and here is the result when I type "u":
I have tried using print statements etc. to see what the value of textEditingValue.text is as I’m typing and it seems like that is working ok and should match, yet it does not.
Thanks so much for any assistance or guidance.
2
Answers
In your code in optionsBuilder:
Omit the following line:
The program should work fine…
You forgot to apply lower case on the options.
Just update
with
and it should be working.