json flutter google maps nearby search API type“_Map< String,dynamic>"不是类型”String“的子类型

q35jwt9p  于 12个月前  发布在  Flutter
关注(0)|答案(1)|浏览(168)

我正在使用谷歌新的附近搜索API来生成一个标记我周围的地方的列表,我得到这个错误
类型“_Map<String,dynamic>”不是类型“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"
            }
        }
    ]
}

字符串
我已经使用dart 2 json插件将其转换为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');
    }
  }}


这是post调用curl -X POST -d '{“includedTypes”:[“restaurant”],“maxResultCount”:10,“locationRestriction”:{“circle”:{“center”:{“latitude”:37.7937,“longitude”:-122.3965},“radius”:500.0 }' \ -H 'Content-Type:application/json' -H“X-Goog-Api-Key:API_KEY”\ -H“X-Goog-FieldMask:places.displayName”\places.googleapis.com/v1/places:searchNearby
在这里,我想我得到了响应,并将其转换为一个map<string,dynamic>列表,以将其用作标记,我不确定,尽管正如我所说的,我仍然是新的

wfveoks0

wfveoks01#

您的返回类型有问题。
如果你使用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;
  }
}

字符串

相关问题