如何解决颤振中的“失败的断言:第 22 行 pos 16:'target != null' : is not true”

时间:2021-01-28 06:25:58

标签: flutter google-maps-flutter

我正在我的 flutter 项目中实现谷歌地图,但我收到此错误 失败的断言:第 22 行 pos 16: 'target != null': is not true 作为 2 的红色错误屏幕在我的移动设备上运行几秒钟,然后地图就实现了。

如何解决?

代码如下:

body: GoogleMap(
        polylines: _polyLines,
        markers: _markers,
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: latLng,
          zoom: 14,
        ),
        onCameraMove: onCameraMove,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
      ),

3 个答案:

答案 0 :(得分:1)

<块引用>

先回答

所以我在这里做什么,首先我使用 geolocator: ^6.1.13 插件获取当前位置并将其保存到一个变量中,直到获取当前位置显示空容器,然后将当前位置传递给 target谷歌地图中的价值

class SelectionScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _selectionScreen();
  }
}

class _selectionScreen extends State<SelectionScreen> {
  @override
  initState() {
    loading = false;
    getCurrentLocation();
    super.initState();
  }
 bool loading;
  var start_currentPostion;

  getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    setState(() {
      double latitude = position.latitude;
      double longitude = position.longitude;
      start_currentPostion = LatLng(latitude, longitude);
      loading = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        body: loading ? GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(
            target: start_currentPostion,
            zoom: 14,
          ),
          onMapCreated: (GoogleMapController controller) {},
          myLocationEnabled: true,
        ) : Container());
  }
}
<块引用>

第二个回答

因此在您的 GoogleMapPage 中,您只需要添加一个布尔值并根据位置进行更新

bool getLocationLoading;

将此值添加到您的 initState() 中并将其设置为 false,然后再次将此布尔变量调用到您的 getLocation() 方法并将其设置为 true

  @override
  void initState() {
    super.initState();
    getLocation();
    getLocationLoading = false;   // set false
  }

  getLocation() async {
    var location = new Location();
    location.onLocationChanged.listen((currentLocation) {
      print(currentLocation.latitude);
      print(currentLocation.longitude);
      setState(() {
        latLng =  LatLng(currentLocation.latitude, currentLocation.longitude);
      });

      print("getLocation:$latLng");
      _onAddMarkerButtonPressed();
      getLocationLoading = true;   // set true

    });

  }

然后只需将您的 GoogleMap 添加到您的身体部位

body: getLocationLoading ? GoogleMap(
  polylines: _polyLines,
  markers: _markers,
  mapType: MapType.normal,
  initialCameraPosition: CameraPosition(
  target: latLng,
  zoom: 14,
  ),
  onCameraMove: onCameraMove,
  onMapCreated: (GoogleMapController controller) {
  _controller.complete(controller);
  },
  myLocationEnabled: true,
  ), : Container());

答案 1 :(得分:0)

@Subham Narkhede ,不,我收到这样的错误:======== 小部件库捕获的异常====================== ================================== 构建 GoogleMapPage(dirty, state: _GoogleMapPageState#43023) 时抛出了以下断言: “package:google_maps_flutter/src/camera.dart”:断言失败:第 22 行 pos 16:“target != null”:不正确。

相关的导致错误的小部件是: GoogleMapPage file:///G:/New%20folder/Shortedcubesolutions%20Softwares/Flutter%20SDK%20windows%201.20.4/Project/thehelpdesk/lib/components/home/home.dart:24:5 抛出异常时,这是堆栈: #2 新的 CameraPosition(包:google_maps_flutter/src/camera.dart:22:16) #3 _GoogleMapPageState.build (package:thehelpdesk/components/home/google_map.dart:152:32) #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15) #6 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11) ... ========================== ,并且 getLocation() 一次又一次地调用,当前位置纬度和经度的值正在我的控制台中打印多次

答案 2 :(得分:-1)

这是我的代码: google_map.dart

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:thehelpdesk/components/home/map_request.dart';
import 'package:thehelpdesk/widgets/appbar.dart';

import 'dart:async';

class GoogleMapPage extends StatefulWidget {
  @override
  _GoogleMapPageState createState() => _GoogleMapPageState();
}

class _GoogleMapPageState extends State<GoogleMapPage> {

  Completer<GoogleMapController> _controller = Completer();
  final Set<Marker> _markers = {};
  static LatLng latLng;

  LocationData currentLocation;
  bool loading = true;

  GoogleMapsServices _googleMapsServices = GoogleMapsServices();

  final Set<Polyline> _polyLines = {};
  Set<Polyline> get polyLines => _polyLines;

  void _onAddMarkerButtonPressed() {
    setState(() {
      _markers.add(Marker(
        markerId: MarkerId("111"),
        position: latLng,
        icon: BitmapDescriptor.defaultMarker,
      ));
    });
  }

  getLocation() async {
    var location = new Location();
    location.onLocationChanged.listen((currentLocation) {
      print(currentLocation.latitude);
      print(currentLocation.longitude);
      setState(() {
        latLng =  LatLng(currentLocation.latitude, currentLocation.longitude);
      });

      print("getLocation:$latLng");
      _onAddMarkerButtonPressed();
      loading = false;

    });

  }

  void onCameraMove(CameraPosition position) {
    latLng = position.target;
  }

  @override
  void initState() {
    // setState(() {
    //   getLocation();
    // });
    super.initState();
    if(this.mounted) {
      setState(() {
        getLocation();
      });
    }
  }

  void sendRequest() async {
    LatLng destination = LatLng(20.2961, 85.8245);
    String route = await _googleMapsServices.getRouteCoordinates(
        latLng, destination);
    createRoute(route);
    _addMarker(destination,"Bhubaneswar");
  }

  void createRoute(String encondedPoly) {
    _polyLines.add(Polyline(
        polylineId: PolylineId(latLng.toString()),
        width: 4,
        points: _convertToLatLng(_decodePoly(encondedPoly)),
        color: Colors.red));
  }

  void _addMarker(LatLng location, String address) {
    _markers.add(Marker(
        markerId: MarkerId("112"),
        position: location,
        infoWindow: InfoWindow(title: address, snippet: "go here"),
        icon: BitmapDescriptor.defaultMarker));
  }

  List<LatLng> _convertToLatLng(List points) {
    List<LatLng> result = <LatLng>[];
    for (int i = 0; i < points.length; i++) {
      if (i % 2 != 0) {
        result.add(LatLng(points[i - 1], points[i]));
      }
    }
    return result;
  }

  List _decodePoly(String poly) {
    var list = poly.codeUnits;
    var lList = new List();
    int index = 0;
    int len = poly.length;
    int c = 0;
    do {
      var shift = 0;
      int result = 0;

      do {
        c = list[index] - 63;
        result |= (c & 0x1F) << (shift * 5);
        index++;
        shift++;
      } while (c >= 32);
      if (result & 1 == 1) {
        result = ~result;
      }
      var result1 = (result >> 1) * 0.00001;
      lList.add(result1);
    } while (index < len);

    for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2];

    print(lList.toString());

    return lList;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: aapBarSection('Google Map', Colors.blueAccent[700], context),
      body: GoogleMap(
        polylines: _polyLines,
        markers: _markers,
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: latLng,
          zoom: 14,
        ),
        onCameraMove: onCameraMove,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          sendRequest();
        },
        label: Text('Destination'),
        icon: Icon(Icons.directions),
      ),
    );
  }
}

ma​​p_request.dart

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

const apiKey = "My API Key";

class GoogleMapsServices{
  Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async{
    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=$apiKey";
    http.Response response = await http.get(url);
    Map values = jsonDecode(response.body);
    print("====================>>>>>>>>$values");

    return values["routes"][0]["overview_polyline"]["points"];
  }
}