flutter 版本 1.22.5
1. 在pubspec.yaml中引入插件
geolocator: ^5.1.3
2. 配置安卓
在android/app/build.gradle
dependencies {
...
// 引入support支持库的multidex库
implementation 'com.android.support:multidex:1.0.3'
//或androidx支持库的multidex库
implementation 'androidx.multidex:multidex:2.0.1'
...
}
defaultConfig {
...
multiDexEnabled true
...
}
3. 在页面中引用插件
import 'package:geolocator/geolocator.dart';
class _HomeState extends State<Home> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
void initState() {
super.initState();
getCurrentLocation();
}
getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
getAddressFromLatLng();
});
})
.catchError((e) {
});
}
getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
}
}
}
网友评论