How to set the text of the field in flutter_typehead TypeAheadField widget? How to set the text of the field in flutter_typehead TypeAheadField widget? dart dart

How to set the text of the field in flutter_typehead TypeAheadField widget?


Ok, I found the solution which was actually on the same github link I provided, but since the example was not about the exact same component (TypeAheadFormField instead of TypeAheadField) and the example was only a piece of code that was lacking context, I had to look at the source to understand.

Here's how to proceed. This actually works both for TypeAheadFormField and TypeAheadField. You have to create a TextEditingController that you pass to the constructor of the TypeAheadField widget. Then you set the text property of that TextEditingController in your onSuggestionSelected callback method. The TypeAheadField widget will use that value to redraw itself, I guess that's how it works.

Here's the code that works:

class _MyHomePageState extends State<MyHomePage> {  final TextEditingController _typeAheadController = TextEditingController();  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text(widget.title),      ),      body: Center(        child: Column(          mainAxisAlignment: MainAxisAlignment.start,          children: <Widget>[            TypeAheadField(              textFieldConfiguration: TextFieldConfiguration(                autofocus: true,                style: DefaultTextStyle.of(context).style.copyWith(                  fontStyle: FontStyle.italic                ),                decoration: InputDecoration(                  border: OutlineInputBorder()                ),                controller: this._typeAheadController              ),              suggestionsCallback: (pattern) async {                Completer<List<String>> completer = new Completer();                completer.complete(<String>["cobalt", "copper"]);                return completer.future;              },              itemBuilder: (context, suggestion){                return ListTile(                  title: Text(suggestion)                );              },              onSuggestionSelected: (suggestion) {                this._typeAheadController.text = suggestion;              }            )          ],        ),      )    );  }}


define a local varible in in your state class of TextEditingController and name it typeAheadController,then add this parameter to your typehead widget :

textFieldConfiguration: TextFieldConfiguration(                            controller:  typeAheadController,                            decoration: ....),

you can modify the field text in your callback (event) using

typeAheadController.text = "your text"