Flutter未处理的异常:构造函数中调用了setState():

时间:2020-01-21 05:22:57

标签: flutter dart

我正在尝试创建一个应用程序,以在执行此错误时显示路线和位置指针。

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.

1 个答案:

答案 0 :(得分:1)

您不应在构建完成之前致电setState(), 使用WidgetsBinding.addPostFrameCallback()

像这样.....

@override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
       //executes after build is done
    })
  }

希望您有主意...