onLocationChanged function
Listen to the current location.
import 'package:location2/location2.dart';
Future<void> _listenLocation() async {
_locationSubscription = onLocationChanged(inBackground: _inBackground)
.handleError((dynamic err) {
if (err is PlatformException) {
setState(() {
_error = err.code;
});
}
_locationSubscription?.cancel();
setState(() {
_locationSubscription = null;
});
}).listen((LocationData currentLocation) async {
setState(() {
_error = null;
_location = currentLocation;
});
//for Android
await updateBackgroundNotification(
onTapBringToFront: true,
subtitle: 'Location: ${currentLocation.latitude}, '
'${currentLocation.longitude}',
);
});
}
Future<void> _stopListen() async {
await _locationSubscription?.cancel();
}
Implementation
Stream<LocationData> onLocationChanged({bool inBackground = false}) {
return _platform
.onLocationChanged(inBackground: inBackground)
.where((event) => event != null)
.cast<LocationData>();
}