-
Notifications
You must be signed in to change notification settings - Fork 348
How to use
mehdi sohrabi edited this page Aug 26, 2020
·
4 revisions
See the best practices here : Example app
The plugin registers a static callback
for getting updates even when app is terminated.
To use other plugins like path_proveider
in this callback
follow the steps in (link)
To update UI you I use Isolate.
More info on Isolate : Isolates and Event Loops - Flutter in Focus
- Initialize plugin:
static const String _isolateName = "LocatorIsolate";
ReceivePort port = ReceivePort();
@override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(port.sendPort, _isolateName);
port.listen((dynamic data) {
// do something with data
});
initPlatformState();
}
Future<void> initPlatformState() async {
await BackgroundLocator.initialize();
}
- Create the callback function, Also the notification callback if you need it:
static void callback(LocationDto locationDto) async {
final SendPort send = IsolateNameServer.lookupPortByName(_isolateName);
send?.send(locationDto);
}
//Optional
static void notificationCallback() {
print('User clicked on the notification');
}
- Start the location service :
Note: Before starting the plugin make sure to have the necessary permissions. See example code for more detail.
//Somewhere in your code
startLocationService();
void startLocationService(){
BackgroundLocator.registerLocationUpdate(LocationCallbackHandler.callback,
initCallback: LocationCallbackHandler.initCallback,
initDataCallback: data,
disposeCallback: LocationCallbackHandler.disposeCallback,
autoStop: false,
iosSettings: IOSSettings(
accuracy: LocationAccuracy.NAVIGATION, distanceFilter: 0),
androidSettings: AndroidSettings(
accuracy: LocationAccuracy.NAVIGATION,
interval: 5,
distanceFilter: 0,
androidNotificationSettings: AndroidNotificationSettings(
notificationChannelName: 'Location tracking',
notificationTitle: 'Start Location Tracking',
notificationMsg: 'Track location in background',
notificationBigMsg:
'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
notificationIcon: '',
notificationIconColor: Colors.grey,
notificationTapCallback:
LocationCallbackHandler.notificationCallback)));
}
More detail on LocationSettings
- Unregister the service when you are done:
IsolateNameServer.removePortNameMapping(_isolateName);
BackgroundLocator.unRegisterLocationUpdate();