【问题标题】:Flutter Unhandled Exception: setState() called in constructor:Flutter Unhandled Exception: setState() 在构造函数中调用:
【发布时间】: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()

标签: flutter dart


【解决方案1】:

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

像这样.....

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

希望你能明白...

【讨论】:

  • 它的工作,但语法是:WidgetsBinding.instance.addPostFrameCallback((_) { //do your stuff here(); });
猜你喜欢
  • 2021-12-19
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多