`地理编码` Flutter:`locationFromAddress` 抛出“意外的空值”

问题描述 投票:0回答:1
/// Searches for an address and moves the map
Future<void> _searchAddress() async {
    String query = _searchController.text.trim();
    if (query.isEmpty) {
      debugPrint("Search query is empty.");
      return;
    }

    try {
      debugPrint("Calling locationFromAddress for: $query");
      List<Location> locations = await locationFromAddress(query);
      debugPrint("locationFromAddress response: $locations");
      if (locations.isEmpty) {
        throw Exception("No locations found for the query.");
      }
    } catch (e) {
      debugPrint("locationFromAddress error: $e"); // Outputs "locationFromAddress error: Unexpected null value."
    }
  }
}

如果有帮助的话,这是全屏:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geocoding/geocoding.dart';

class FindAddressScreen extends StatefulWidget {
  const FindAddressScreen({super.key});

  @override
  State<FindAddressScreen> createState() => _FindAddressScreenState();
}

class _FindAddressScreenState extends State<FindAddressScreen> {
  LatLng _selectedLocation =
      LatLng(37.7749, -122.4194);
  final TextEditingController _searchController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Select Address'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context, _selectedLocation);
            },
            child: Text("Conferma"),
          )
        ],
      ),
      body: Stack(
        children: [
          GoogleMap(
            initialCameraPosition: CameraPosition(
              target: _selectedLocation,
              zoom: 14,
            ),
            onMapCreated: (controller) {

            },
            onLongPress: _updateLocation,
            markers: {
              Marker(
                markerId: MarkerId("selected-location"),
                position: _selectedLocation,
              )
            },
          ),
          Positioned(
            top: 10,
            left: 10,
            right: 10,
            child: Card(
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _searchController,
                      decoration: InputDecoration(
                        hintText: "Search address",
                        contentPadding: EdgeInsets.symmetric(
                          vertical: 10,
                          horizontal: 15,
                        ),
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.search),
                    onPressed: _searchAddress,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  /// Updates the selected location
  Future<void> _updateLocation(LatLng position) async {
    setState(() {
      _selectedLocation = position;
    });
  }

  /// Searches for an address and moves the map
  Future<void> _searchAddress() async {
    String query = _searchController.text.trim();
    if (query.isEmpty) {
      debugPrint("Search query is empty.");
      return;
    }

    try {
      debugPrint("Calling locationFromAddress for: $query");
      List<Location> locations = await locationFromAddress(query);
      debugPrint("locationFromAddress response: $locations");
      if (locations.isEmpty) {
        throw Exception("No locations found for the query.");
      }
    } catch (e) {
      debugPrint("locationFromAddress error: $e");
    }
  }
}

我正在 Chrome 中使用

flutter run
运行应用程序。

我已为我的项目启用了地理编码 API,并将我的 API 密钥放入

index.html
中,它具有适当的默认限制(
Geocoding API
已启用)。

使用直接 http 调用搜索地址确实有效:

import 'package:http/http.dart' as http;
import 'dart:convert';

// ...

  Future<void> _searchAddress() async {
    String query = _searchController.text.trim();
    if (query.isEmpty) {
      debugPrint("Search query is empty.");
      return;
    }

    final apiKey = "YOUR_API_KEY"; // Replace with your API key
    final url = Uri.parse(
      "https://maps.googleapis.com/maps/api/geocode/json?address=${Uri.encodeComponent(query)}&key=$apiKey");

    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['results'] != null && data['results'].isNotEmpty) {
          final location = data['results'][0]['geometry']['location'];
          LatLng target = LatLng(location['lat'], location['lng']);
          _moveCamera(target);
          _updateLocation(target);
          debugPrint("Address found: $location");
        } else {
          throw Exception("No results found.");
        }
      } else {
        throw Exception("Failed to fetch geocoding data.");
      }
    } catch (e) {
      debugPrint("Google Maps search error: $e");
    }
  }
}

我应该检查什么?

google_maps_flutter 2.10.0 地理编码3.0.0 http 1.2.2

Chrome 131.0.6778.86。 颤动 3.24.4。 飞镖 3.5.4。 VS 代码 1.95.3。 macOS 15.0、MacBook Air M1 8GB。

google-maps google-cloud-platform google-geocoding-api
1个回答
0
投票

事实证明,该包不适用于网络。

“web”和“Chrome”一词没有出现在 docspub.dev 的自述文件中,尽管文档说“此插件使用 iOS 和 Android 平台提供的免费地理编码服务。这意味着它们的使用受到限制。”,这意味着“当前的地理编码插件仅适用于 iOS 和 Android。”,可以在这个提案中阅读。

© www.soinside.com 2019 - 2024. All rights reserved.