使用Flutter定位包获取地理位置

  class GetUserLocation extends StatefulWidget {

  GetUserLocation({Key? key, required this.title}) : super(key: key);

  final String title;

  @override

  _GetUserLocationState createState() => _GetUserLocationState();

  }

  class _GetUserLocationState extends State {

  LocationData? currentLocation;

  String address = "";

  @override

  Widget build(BuildContext context) {

  return Scaffold(

  appBar: AppBar(),

  body: Center(

  child: Padding(

  padding: EdgeInsets.all(16.0),

  child: Column(

  mainAxisAlignment: MainAxisAlignment.center,

  children: [

  if (currentLocation != null)

  Text(

  "Location: ${currentLocation?.latitude}, ${currentLocation?.longitude}"),

  if (currentLocation != null) Text("Address: $address"),

  MaterialButton(

  onPressed: () {

  _getLocation().then((value) {

  LocationData? location = value;

  _getAddress(location?.latitude, location?.longitude)

  .then((value) {

  setState(() {

  currentLocation = location;

  address = value;

  });

  });

  });

  },

  color: Colors.purple,

  child: Text(

  "Get Location",

  style: TextStyle(color: Colors.white),

  ),

  ),

  ],

  ),

  ),

  ),

  );

  }

  Future _getLocation() async {

  Location location = new Location();

  LocationData _locationData;

  bool _serviceEnabled;

  PermissionStatus _permissionGranted;

  _serviceEnabled = await location.serviceEnabled();

  if (!_serviceEnabled) {

  _serviceEnabled = await location.requestService();

  if (!_serviceEnabled) {

  return null;

  }

  }

  _permissionGranted = await location.hasPermission();

  if (_permissionGranted == PermissionStatus.denied) {

  _permissionGranted = await location.requestPermission();

  if (_permissionGranted != PermissionStatus.granted) {

  return null;

  }

  }

  _locationData = await location.getLocation();

  return _locationData;

  }

  Future _getAddress(double? lat, double? lang) async {

  if (lat == null || lang == null) return "";

  GeoCode geoCode = GeoCode();

  Address address =

  await geoCode.reverseGeocoding(latitude: lat, longitude: lang);

  return "${address.streetAddress}, ${address.city}, ${address.countryName}, ${address.postal}";

  }

  }