解决未处理的异常:类型 'String' 不是 'index' 的类型 'int' 的子类型

Solving Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

我正在研究转弯导航。

Future getReverseGeocodingGivenLatLngUsingMapbox(LatLng latLng) async {
  String query = '${latLng.longitude},${latLng.latitude}';
  String url = '$baseUrl/$query.json?access_token=$accessToken';
  url = Uri.parse(url).toString();
  print(url);
  try {
    _dio.options.contentType = Headers.jsonContentType;
    final responseData = await _dio.get(url);
    return responseData.data;
  } catch (e) {
    final errorMessage = DioExceptions.fromDioError(e as DioError).toString();
    debugPrint(errorMessage);
  }
}

下面使用上面的函数

    Future<Map> getParsedReverseGeocoding(LatLng latLng) async {
      var response = await getReverseGeocodingGivenLatLngUsingMapbox(latLng);
      Map feature = response['features'][0];
      Map revGeocode = {
        'name': feature['text'],
        'address': feature['place_name'].split('${feature['text']}, ')[1],
        'place': feature['place_name'],
        'location': latLng
      };
      return revGeocode;
    }

下面使用getParsedReverseGeocoding()函数

void initializeLocationAndSave() async {
    // Ensure all permissions are collected for Locations
    Location _location = Location();
    bool? _serviceEnabled;
    PermissionStatus? _permissionGranted;

    _serviceEnabled = await _location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await _location.requestService();
    }

    _permissionGranted = await _location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await _location.requestPermission();
    }

    // Get the current user location
    LocationData _locationData = await _location.getLocation();
    LatLng currentLocation =
    LatLng(_locationData.latitude!, _locationData.longitude!);

    // Get the current user address
    String currentAddress =
       (await getParsedReverseGeocoding(currentLocation))['place'];  // getting error over here

    // Store the user location in sharedPreferences
    sharedPreferences.setDouble('latitude', _locationData.latitude!);
    sharedPreferences.setDouble('longitude', _locationData.longitude!);
    sharedPreferences.setString('current-address', currentAddress);

    Navigator.pushAndRemoveUntil(context,
        MaterialPageRoute(builder: (_) => const Home()), (route) => false);
  }

但是,我在检索 'place' 字段时出现以下错误。

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

一些对您有帮助的事情:

  • 您似乎缺少 jsonDecode 并且:
Future getReverseGeocodingGivenLatLngUsingMapbox(LatLng latLng) async {
  String query = '${latLng.longitude},${latLng.latitude}';
  String url = '$baseUrl/$query.json?access_token=$accessToken';
  url = Uri.parse(url).toString();
  print(url);
  try {
    _dio.options.contentType = Headers.jsonContentType;
    final responseData = await _dio.get(url);
    final result = jsonDecode(responseData.data);
    return result;
  } catch (e) {
    final errorMessage = DioExceptions.fromDioError(e as DioError).toString();
    debugPrint(errorMessage);
  }
}
  • 建议在Dart中使用强类型,我猜应该是:
Future<List<dynamic>> getReverseGeocodingGivenLatLngUsingMapbox(LatLng latLng) async {...
}
  • 问题可能出在第二种方法中:
Future<Map> getParsedReverseGeocoding(LatLng latLng) async {
    var response = await getReverseGeocodingGivenLatLngUsingMapbox(latLng);

    // This response is likely a List and you don't have key 'features' of type String/index, i.e. you have a index which is supposed to be an int.
    // Map feature = response['features'][0];
    // Maybe this will work: 
    Map feature = response[0];

    Map revGeocode = {
        'name': feature['text'],
        'address': feature['place_name'].split('${feature['text']}, ')[1],
        'place': feature['place_name'],
        'location': latLng
    };
    return revGeocode;
}
  • 级联调用会使您的代码更难阅读和调试:
final revGeocode = await getParsedReverseGeocoding(currentLocation);
final currentAddress = revGeocode['place'];

// now you can hover revGeocode and see what's inside using your IDE

简而言之:通过尽可能多地输入代码来使用对你有利的 Dart 类型系统。