简体   繁体   中英

Accessing route parameters in Dart and flutter

I am sending 2 parameters restaurantDetails.rest_latitude and restaurantDetails.rest_longitude to a class to get the map details

BarMapWidget(restaurantDetails.rest_latitude, restaurantDetails.rest_longitude),

In the class I have a stateful widget

class BarMapWidget extends StatefulWidget {

  String restLatitude;
  String restLongitude;

  BarMapWidget(this.restLatitude, this.restLongitude, {Key? key}) : super(key: key);

  @override

  _BarMapWidgetState createState() => _BarMapWidgetState();

}

I am passing a string so I know I have to make it a double

Here is the extended class,

class _BarMapWidgetState extends State<BarMapWidget> {


// Destination Longitude
final double _destLatitude = restLatitude;
final double _destLongitude = restLongitude;

void initState() {
    // Add destination marker

    _addMarker(
      LatLng(_destLatitude, _destLongitude),
      "destination",
      // BitmapDescriptor.defaultMarkerWithHue(90),
      BitmapDescriptor.defaultMarker
    );
    super.initState();
  }

Which give me a Undefined name 'restLatitude'. and Undefined name 'restLongitude'.

How can I access the variable in BarMapWidget?

Your restLatitude and restLongitude on widget level, try using widget.variableName . Also, those aren't matching datatype.

If you need double convert BarMapWidget variable to double.

To initialize on state level you can trick with using late or use initState ;

class BarMapWidget extends StatefulWidget {
  final double restLatitude;
  final double restLongitude;

  const BarMapWidget(this.restLatitude, this.restLongitude, {Key? key})
      : super(key: key);

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

class _BarMapWidgetState extends State<BarMapWidget> {
// Destination Longitude
  late final double _destLatitude = widget.restLatitude;
  late final double _destLongitude = widget.restLongitude;

Just add in

widget.restLatitude

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM