Home > Blockchain >  Pass typed Text Value to API call Flutter
Pass typed Text Value to API call Flutter

Time:03-15

I am using TypeAheadFormField to show Text suggestions when a user types, for example, user types 'Lon' and my API will return 'London' as a suggestion.

My API call needs the letters typed to make the call and autosuggest results close to the users typed value.

My API URL requires those letters types to be part of the String for the RestAPI Call (i.e. ...&q=london&apikey=x)

Is there a way to pass the typed textValue recognised by the TypeAheadFormField to the suggestionsCallback: method to then use in the call?

TextAhead registers the typed Text to show results but I'm unsure how to make it a var, for example.

TypeAheadFormField<Item?>(
  textFieldConfiguration: TextFieldConfiguration(
    autofocus: true,
    style: DefaultTextStyle.of(context).style.copyWith(
      fontStyle: FontStyle.italic
    ),
    decoration: InputDecoration(
      border: OutlineInputBorder()
    )
  ),
  suggestionsCallback: 

 *API is called here* MapItemsExample.getUserSuggestions,
 
  itemBuilder: (context, Item? suggestion) {
...

Call

  static FutureOr<Iterable<auto.Item>> getUserSuggestions(String query) async {
    

    final url = Uri.parse('https_call');
    final response = await http.get(url);

    if (response.statusCode == 200) {
      Map<String, dynamic> userss = json.decode(response.body);
      List<dynamic> users = userss["items"];

      return users.map((json) => auto.Item.fromJson(json)).where((user) {
        final nameLower = user.title!.toLowerCase();
        final queryLower = query.toLowerCase();
        return nameLower.contains(queryLower);
      }).toList();
    } else {
      throw Exception();
    }
  }

Thank you

Update

I have changed the URL call to this

          suggestionsCallback: (pattern) async {
            final url = Uri.parse('https://autosuggest.search.hereapi.com/v1/autosuggest?at=lat,long&q=$query&apiKey=my_key');
            final response = await http.get(url);

There are no errors now except the query parameter.

How do I make the $query in the URL call the Text of whichever letters have been entered by the user, as they type? Thanks

CodePudding user response:

Here I provide an example. In this example you read users when you type and this is got from server. Then, user selects one of them its values save in TextEditController

 this._typeAheadController.text = suggestion;
 // you can save in user here
 this._user = suggestion;

You can validate or anything else in flutter_typeahead

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController _typeAheadController = TextEditingController();
dynamic _user;

//...

Form(
  key: this._formKey,
  child: Padding(
    padding: EdgeInsets.all(32.0),
    child: Column(
      children: <Widget>[       
        TypeAheadFormField(
          textFieldConfiguration: TextFieldConfiguration(
            controller: this._typeAheadController,
            decoration: InputDecoration(
              labelText: 'User'
            )
          ),          
          suggestionsCallback: (pattern) {
            final url = Uri.parse('https_call', { 'q': query,   'apikey': 'xxxxx', });
            final response = await http.get(url);

           if (response.statusCode == 200) {
             Map<String, dynamic> userss = json.decode(response.body);
             List<dynamic> users = userss["items"];

             return users.map((json) => auto.Item.fromJson(json)).where((user) {
             final nameLower = user.title!.toLowerCase();
             final queryLower = query.toLowerCase();
             return nameLower.contains(queryLower);
             }).toList();
            } else {
             throw Exception();
           }
          },
          itemBuilder: (context, suggestion) {
            return ListTile(
              title: Text(suggestion),
            );
          },        
          onSuggestionSelected: (suggestion) {
            this._typeAheadController.text = suggestion;
            // you can save in user here
            this._user = suggestion;
          },         
        ),
        SizedBox(height: 10.0,),
        RaisedButton(
          child: Text('Submit'),
          onPressed: () {
            if (this._formKey.currentState.validate()) {
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text('User is is ${this._user}')
              ));
            }
          },
        )
      ],
    ),
  ),
)
  • Related