Flutter Stateful Constructor Const 问题

Flutter Stateful Constructor Const Problem

我正在关注 udemy 上的教程,我发现了这个奇怪的错误,我已经阅读了一些文档,但我仍然没有找到正确的答案来让构造函数具有初始值。 她是我的代号

class MapScreen extends StatefulWidget {

      final PlaceLocation initialLocation;
      final bool isSelecting;
      const MapScreen({Key? key, this.initialLocation = PlaceLocation( //here there is an error "The default value of an optional parameter must be constant. (Documentation)"
        latittude:  37.422,
        longitude: -122.084,
        address: "Example stree no 1",
      ), this.isSelecting = false}) : super(key: key);
    
      @override
      _MapScreenState createState() => _MapScreenState();
    }

但是,如果我删除那些常量,就会出现新的错误

    class MapScreen extends StatefulWidget {
      final PlaceLocation initialLocation;
      final bool isSelecting;
      MapScreen({Key? key, this.initialLocation = PlaceLocation( //The default value of an optional parameter must be constant. (Documentation)
        latittude:  37.422,
        longitude: -122.084,
        address: "Jl. Imambonjol",
      ), this.isSelecting = false}) : super(key: key);
    
      @override
      _MapScreenState createState() => _MapScreenState();
    }

我也尝试按照说明修改我的代码,如下所示:

class MapScreen extends StatefulWidget {
  final PlaceLocation initialLocation;
  final bool isSelecting;

  MapScreen({
    this.initialLocation =
        const PlaceLocation(latitude: 37.422, longitude: -122.084),
    this.isSelecting = false,
  });

  @override
  _MapScreenState createState() => _MapScreenState();
}

但是还是报错

我已经修复了你的错误,下面附上解决方法代码和控制台截图:

// Fake model:
class PlaceLocation {
  final double latittude;
  final double longitude;
  final String address;

  // Make this constructor const to solve your problem:
  const PlaceLocation(
      {required this.latittude,
      required this.longitude,
      required this.address});
}

class MapScreen extends StatefulWidget {
  final PlaceLocation initialLocation;
  final bool isSelecting;

  // Also don't forget to put const before PlaceLocation() in this constructor:
  const MapScreen(
      {Key? key,
      this.initialLocation = const PlaceLocation(
        latittude: 37.422,
        longitude: -122.084,
        address: "Example stree no 1",
      ),
      this.isSelecting = false})
      : super(key: key);

  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  @override
  Widget build(BuildContext context) {
    // Console test to check default values:
    print("lattitude: " +
        MapScreen().initialLocation.latittude.toString() +
        "\nlongitude: " +
        MapScreen().initialLocation.longitude.toString() +
        "\naddress: " +
        MapScreen().initialLocation.address.toString());

    return Scaffold(body: Container());
  }
}

你所要做的就是让你的模型 (PlaceLocation) 构造函数 const.