flutter google 地图附近搜索 api 类型“_Map<String, dynamic>”不是“String”类型的子类型

问题描述 投票:0回答:1

我正在使用 Google 新的附近搜索 API 生成我周围地点的标记列表,但我收到此错误

类型“_Map”不是“String”类型的子类型

我是 flutter 新手,但我设法得到了响应,我认为在调用 api 后从 json 进行转换时发生了错误

这是我得到的 json 体

{
    "places": [
        {
            "id": "ChIJH1SlB1OgHBURC9Io_36xG2Y",
            "formattedAddress": "XV9F+7MW, Amman, Jordan",
            "location": {
                "latitude": 31.968225099999998,
                "longitude": 35.874212299999996
            },
            "displayName": {
                "text": "Sido AlKurdi Mosque",
                "languageCode": "en"
            },
            "photos": [
                {
                   
                    
                },
                
            ]
        },
        {
            "id": "ChIJtXIJhK2hHBURntIqDaJGrNg",
            "formattedAddress": "Al Imam Muslim 22, Amman, Jordan",
            "location": {
                "latitude": 31.9706942,
                "longitude": 35.882999399999996
            },
            "displayName": {
                "text": "مسجد بر الوالدين (ضاحية الحسين)",
                "languageCode": "ar"
            }
        }
    ]
}

我已经使用 dart2json 插件将其转换为 JSON

这是我的仓库


abstract class HttpRepository {
  Future<Response?> googleNearbySearch({
    required Map<String, dynamic> payload,
  });
}}

这是回购协议的实现


    class HttpRepositoryImpl extends GetConnect implements HttpRepository {
      @override
      Future<Response?> googleNearbySearch({
        required Map<String, dynamic> payload,
      }) async {
        var response = await post(
          ApiUrls.googleNearbySearch,
          headers: googleMapsHeaders,
          payload,
        );
        if (response.isOk) {
         
          return response;
        } else if (response.unauthorized) {
          CustomToast.unAuthorized();
        } else if (response.hasError) {
       
          CustomToast.backEndError(message: "something went wrong");
        }
        return null;
      }
    }

这是我的控制器,我正在使用 getx 和 get_connect 来处理我的 API 调用,代码不完整,因为我删除了其中的一些片段

因为太长了,如果有人想帮助我并发现缺少代码,我可以稍后提供

 class NearbyMosquesController extends GetxController {
  final HttpRepository httpRepository;
  final CacheUtils cacheUtils;

  NearbyMosquesController(
      {required this.httpRepository, required this.cacheUtils});

  List<NewNearbyMosques> mapModelList = <NewNearbyMosques>[].obs;

  var markers = RxSet<Marker>();

  var isDoneLoading = false.obs;

 Rx<NewNearbyMosques?> nearbyMosquesModel = Rx<NewNearbyMosques?>(null);

 String apiKey = "********************";

 googleNearbySearch() async {
    try {
      isDoneLoading(true);
      final payload = json.encode({
        "includedTypes": ["mosque"],
        "maxResultCount": 10,
        "locationRestriction": {
          "circle": {
            "center": {"latitude": 37.7937, "longitude": 32.3965},
            "radius": 10000.0
          }
        }
      });
      late Rx<Response?> googleNearbySearchResponse = Rx<Response?>(null);

      Position position = await determinePosition();
      googleNearbySearchResponse.value =
          await httpRepository.googleNearbySearch(
        
        payload: json.decode(payload),
      );
      var result = jsonDecode(googleNearbySearchResponse.value!.body);
    
      // Set<Marker> newMarkers = createMarkers();
      if (googleNearbySearchResponse.value == null) {
        return null;
      }
      mapModelList.addAll(RxList<Map<String, dynamic>>.from(result)
          .map((e) => NewNearbyMosques.fromJson(e))
          .toList());
      nearbyMosquesModel.value = NewNearbyMosques.fromJson(
        googleNearbySearchResponse.value!.body,
      );
    } catch (e) {
      createMarkersFromList();
      debugPrint(
          'this is another error in the catch   ${e.toString()}\n\n\n\n\n\n\n\n\n\n\n');
      CustomToast.backEndError(
        message: 'error while calling google',
      );
    } finally {
      isDoneLoading(false);
      createMarkersFromList();
      CustomToast.backEndError(
        message: 'in the finally',
      );
    }
  }

  createMarkersFromList() {
    mapModelList.forEach((element) {
      var places = element.places;
      
      if (places != null) {
       
         for (int i = 0; i < places.length; i++) {
       

        markers.add(
          Marker(
            markerId: MarkerId(
              places[i].id.toString(),
            ),
            icon: BitmapDescriptor.defaultMarkerWithHue(
              BitmapDescriptor.hueAzure,
            ),
            position: LatLng(
              places[i].location!.latitude!,
              places[i].location!.longitude!,
            ),
            infoWindow: InfoWindow(
              title: places[i].displayName.toString(),
              snippet: places[i].formattedAddress.toString(),
            ),
            onTap: () {},
          ),
        );
         }
      }
    });
  }

 @override
  Future<void> onInit() async {
    try {
    
      getCurrentLocation();
      await googleNearbySearch();
     
      await determinePosition();

      super.onInit();
    } catch (e) {
      print('Initialization error: $e');
    }
  }}

这是后调用的卷曲 curl -X POST -d '{ "includedTypes": ["restaurant"], "maxResultCount": 10, "locationRestriction": { "circle": { "center": { "latitude": 37.7937, "longitude": - 122.3965},“半径”:500.0 } } }' \ -H '内容类型:application/json' -H“X-Goog-Api-Key:API_KEY” \ -H“X-Goog-FieldMask:places.displayName “ \places.googleapis.com/v1/places:searchNearby

在这里我想我得到了响应并将其转换为地图列表以将其用作标记我不确定,尽管正如我所说我还是新人

json flutter google-maps google-places-api flutter-getx
1个回答
0
投票

您的退货类型有问题。

如果您使用过http:^1.1.2

那么你需要使用

class HttpRepositoryImpl extends GetConnect implements HttpRepository {
  @override
  Future<Response?> googleNearbySearch({
    required Map<String, dynamic> payload,
  }) async {
    var response = await post(
      ApiUrls.googleNearbySearch,
      headers: googleMapsHeaders,
      payload,
    );
    if (response.isOk) {
     
      return jsonDecode(response);          <-----------  jsonDecode
    } else if (response.unauthorized) {
      CustomToast.unAuthorized();
    } else if (response.hasError) {
   
      CustomToast.backEndError(message: "something went wrong");
    }
    return null;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.