【发布时间】:2020-01-21 05:22:57
【问题描述】:
我正在尝试创建一个应用程序来显示路线和位置指针,同时执行此错误。
HomePage.dart:
class _MapState extends State<Map> {
///////////body of statements///////////
void _addMarker(LatLng location){
setState(() {
_markers.add(Marker(markerId: MarkerId(location.toString()),
position: location,
icon: BitmapDescriptor.defaultMarker,
));
});
}
void createRoute(String encodedPoly){
setState(() {
_polyLines.add(Polyline(polylineId: PolylineId(_lastPosition.toString()),
width: 10,
points: _convertToLatLng(googleMapsServices.decodePoly(encodedPoly)),
color: black,
));
});
}
}
这是放置在 HomePage.dart 中的继承类:
class sendReq extends _MapState{
void sendRequest(String intendedLocation)async{
super.initState();
List<Placemark> placemark = await Geolocator().placemarkFromAddress(intendedLocation);
double latitude = placemark[0].position.latitude;
double longitude = placemark[0].position.longitude;
LatLng destination = LatLng(latitude,longitude);
print("The intended location is $intendedLocation with the LatLang of $destination");
_addMarker(destination);
String route = await googleMapsServices.getRouteCoordinates(_lastPosition, destination);
createRoute(route);
}
}
这是 location.dart 页面:
onSubmitted: (value){
sr.sendRequest(value);
},
在位置输入上运行此代码时,会出现以下错误:
E/flutter (12680): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called in constructor: sendReq#c5316(lifecycle state: created, no widget, not mounted)
E/flutter (12680): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.
【问题讨论】:
-
你为什么在
sendRequest方法中调用super.initState()? -
在构建完成之前不要调用 setState。如果你需要在构建完成后做一些事情,你可以在 initState 方法中使用 WidgetsBinding.addPostFrameCallback()