Flutter Google AutoComplete with Places API (NEW) - Stack Overflow

I'm trying to implement the Places API (New) in my flutter project but I don't seem to be abl

I'm trying to implement the Places API (New) in my flutter project but I don't seem to be able to show the places.

For my HTTP request:

class GooglePlacesService {
  final String apiKey;
  final String language;

  GooglePlacesService({
    required this.apiKey,
    required this.language,
  });

  // Fetch autocomplete suggestions
  Future<List<Map<String, String>>> fetchAutocompleteSuggestions(
      String input, String country) async {
    final url =
        '=$input&key=$apiKey&language=$language&components=country:$country';
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      final predictions = data['predictions'] as List;
      return predictions.map((prediction) {
        return {
          'description': prediction['description'].toString(),
          'placeId': prediction['place_id'].toString(),
        };
      }).toList();
    } else {
      throw Exception('Failed to load autocomplete suggestions');
    }
  }

  Future<List<Map<String, String>>> fetchNearbyAutocompleteSuggestions(
    String input,
    double lat,
    double lng,
    double radius,
  ) async {
    final url =
        '=$input&key=$apiKey&language=$language&location=$lat,$lng&radius=$radius';
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      final predictions = data['predictions'] as List;
      return predictions.map((prediction) {
        return {
          'description': prediction['description'].toString(),
          'placeId': prediction['place_id'].toString(),
        };
      }).toList();
    } else {
      throw Exception('Failed to load autocomplete suggestions');
    }
  }

  // Fetch place details (placeId, location, radius)
  Future<Map<String, dynamic>> fetchPlaceDetails(String placeId) async {
    final url =
        '=$placeId&key=$apiKey&language=$language';
    final response = await http.get(Uri.parse(url));
    // print('API Response: ${response.body}'); // Debugging

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      final result = data['result'];

      if (result == null ||
          result['geometry'] == null ||
          result['geometry']['location'] == null) {
        throw Exception('Invalid place details: Missing geometry or location');
      }

      final location = result['geometry']['location'];
      final viewport = result['geometry']['viewport'];
      final radius = calculateRadius(viewport);

      return {
        'placeId': placeId,
        'location': location,
        'radius': radius,
      };
    } else {
      throw Exception('Failed to load place details: ${response.statusCode}');
    }
  }
}

For the implementation in the UI

late GooglePlacesService placesService;
TextEditingController fromController = TextEditingController();
@override
  void initState() {
    super.initState();
    placesService = GooglePlacesService(
      apiKey: ApiKey.googleApi,
      language: widget.language,
    );
    langTime = widget.langTime;

  }

Widget suggestionTextField({
    required TextEditingController controller,
    required String hitText,
    required void Function(Map<String, String>)? onSelected,
    required String? appDataLocationPointName,
  }) {
    return TypeAheadField(
      controller: controller,
      builder: (context, controller, focusNode) {
        return AppTextfield.textFormField(
          controller: controller,
          focusNode: focusNode,
          textCapitalization: TextCapitalization.sentences,
          obscureText: false,
          suffixIcon: controller.text.isNotEmpty
              ? IconButton(
                  onPressed: () {
                    controller.clear();
                    setState(() {
                      appDataLocationPointName = null;
                    });
                  },
                  icon: const Icon(
                    Icons.clear,
                    color: Colors.red,
                  ))
              : null,
          prefixIcon: const Icon(
            Icons.add_location_alt,
            color: Colors.blue,
          ),
          label: Text(hitText),
          hintText: hitText,
        );
      },
      itemBuilder: (context, suggestion) {
        final parts = suggestion['description']!.split(',');
        parts.removeLast();
        final removeLast = parts.join(',').trim();
        return ListTile(
          title: Text(removeLast),
        );
      },
      onSelected: onSelected,
      suggestionsCallback: (pattern) async {
        return await placesService.fetchAutocompleteSuggestions(
          pattern,
          widget.countryInitial,
        );
      },
    );
  }
//In the main widget builder
suggestionTextField(
                controller: fromController,
                hitText: widget.departureLocation,
                onSelected: (suggestion) async {
                  try {
                    final placeName = suggestion['description']!.split(",")[0];
                    final parts = suggestion['description']!.split(',');
                    parts.removeLast();
                    final removeLast = parts.join(',').trim();
                    fromController.text = placeName;

                    setState(() {
                      appData.searchRideFrom = removeLast;
                      appData.searchRideFromFirst = placeName;
                      isArrivalEnabled = true;
                    });
                  } catch (e) {
                    Fluttertoast.showToast(
                      timeInSecForIosWeb: 5,
                      backgroundColor: Colors.red,
                      textColor: Colors.black,
                      msg: e.toString(),
                    );
                  }
                },
                appDataLocationPointName: appData.searchRideFrom,
              ),

Can someone please check the code for me to see what's wrong. Also I have my Api from the Google console and enabled the necessary APIs, especially the Places API (New). My project is connect to my account billing information

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744912034a4600610.html

相关推荐

  • Flutter Google AutoComplete with Places API (NEW) - Stack Overflow

    I'm trying to implement the Places API (New) in my flutter project but I don't seem to be abl

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信