Search code examples
androidiosflutterlistener

ListView is not getting updated while typing in TextField in flutter


Populating data in ListView while typing in TextField but Data is being populated on Done button of keyboard. The Data is coming from Google Autocomplete Api.

I tried to update list while typing but nothing working.

TextField Code

TextField(
                          textInputAction: TextInputAction.done,
                          controller: searchAddressController,
                          focusNode: searchFocus,
                          decoration: InputDecoration(
                              prefixIcon: Icon(
                                Icons.search_rounded,
                                color: Colors.black,
                              ),
                              filled: true,
                              fillColor: MyColors.locationfieldback,
                              hintText: "Add Location",
                              focusedBorder: border,
                              disabledBorder: border,
                              enabledBorder: border,
                              border: border,
                              hintStyle: TextStyle(
                                  fontSize: 16.0,
                                  fontFamily: 'regular',
                                  color: Colors.grey[500],
                                  letterSpacing: 1.5),
                              errorBorder: border,
                              focusedErrorBorder: border,
                              labelStyle: TextStyle(
                                  fontSize: 16.0,
                                  fontFamily: 'regular',
                                  color: Colors.grey[500],
                                  letterSpacing: 1.5),
                              contentPadding:
                                  EdgeInsets.fromLTRB(10, 12, 20, 12))),

ListView Code

ListView.builder(
                                padding: EdgeInsets.all(8),
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                itemCount: _placeList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return ListTile(
                                    onTap: () {
                                      onLoading(context);
                                      getLatLong(
                                          _placeList[index].placeId, index);
                                    },
                                    title: Text(
                                      '${_placeList[index].description}',
                                      textAlign: TextAlign.justify,
                                      maxLines: 3,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(fontFamily: 'semibold'),
                                    ),
                                  );
                                })

Search method and Listener

searchAddressController.addListener(() {
      _onChanged();
    });

_onChanged() {
    if (_sessionToken == null) {
      setState(() {
        _sessionToken = uuid.v4();
      });
    }
    searchLocation(searchAddressController.text);
  }

  Future<GooglePlaceAutocompleteResponse> searchLocation(String input) async {
    String baseURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json';
    String request = '$baseURL?input=$input&key=$kPLACES_API_KEY&sessiontoken=$_sessionToken';
     Dio dio = Dio();
    var response = await dio.get(request);
    try {
      if (response.statusCode == 200) {
        Log.e("ADDRESS RESPONSE", response.data);
        var responseObj = GooglePlaceAutocompleteResponse.fromJson(response.data);
        setState(() {
          _placeList = responseObj.predictions;
        });
        return responseObj;
      } else {
        throw Exception('Failed to load predictions');
      }
    } catch (e) {
      Log.e("EXCEPTION AUTOCOMPLETE", e);
    }
  }

enter image description here

Getting response while typing

enter image description here


Solution

  • searchLocation(searchAddressController.text); place this under setState. As well as, you can use async and await.

    _onChanged() {
        if (_sessionToken == null) {
          setState(() {
            _sessionToken = uuid.v4();
    
          searchLocation(searchAddressController.text);
          });
        }
      }
    

    Edited

    If you use bottomSheet, please use stateBuilder with StateSetter