这是我为获取当前位置并添加一些标记而编写的代码
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class Map extends StatefulWidget {
@override
_NewMapState createState() => _NewMapState();
}
Future setMapStyle(GoogleMapController controller, BuildContext context) async {
String value = await DefaultAssetBundle.of(context)
.loadString('assets/maps/map_style.json');
await controller.setMapStyle(value);
}
class _NewMapState extends State<Map> {
GoogleMapController _controller;
Position position;
Widget _child;
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
BitmapDescriptor pinLocationIcon;
@override
void initState() {
_child = SpinKitRipple(
itemBuilder: (BuildContext context, int index) {
return DecoratedBox(
decoration: BoxDecoration(
color: index.isEven ? Colors.grey : Color(0xffffb838),
),
);
},
);
getCurrentLocation();
populateClients();
setCustomMapPin();
super.initState();
}
void getCurrentLocation() async {
Position res = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() {
position = res;
_child = mapWidget();
});
}
populateClients() async {
FirebaseFirestore.instance.collection('points').get().then((docs) {
if (docs.docs.isNotEmpty) {
for (int i = 0; i < docs.docs.length; ++i) {
initMarker(docs.docs[i].data(), docs.docs[i].id);
}
}
});
}
void initMarker(tomb, tombId) {
var markerIdVal = tombId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: LatLng(tomb['location'].latitude, tomb['location'].longitude),
icon: pinLocationIcon,
infoWindow: InfoWindow(title: 'Shop', snippet: tombId),
onTap: () {
_settingModalBottomSheet(context,markerIdVal);
},
);
setState(() {
markers[markerId] = marker;
});
}
........ here is adding markers and map
该代码提供了所需的输出,但控制台打印并调用了异常
在 null 上调用了 getter 'latitude'。接收方:null 尝试呼叫:纬度
我尝试了很多但找不到任何正当理由的问题可能是什么
完全错误
Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building Map(dirty, state: _NewMapState#22070):
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude
The relevant error-causing widget was
Map
lib\Pages\home.dart:46
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _NewMapState.mapWidget
package:map/Pages/test.dart:106
#2 _NewMapState.build
package:map/Pages/test.dart:97
#3 StatefulElement.build
package:flutter/…/widgets/framework.dart:4744
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4627
...