-
Notifications
You must be signed in to change notification settings - Fork 365
How to use
mehdi sohrabi edited this page Apr 11, 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(
callback,
//optional
androidNotificationCallback: notificationCallback,
settings: LocationSettings(
//Scroll down to see the different options
notificationTitle: "Start Location Tracking example",
notificationMsg: "Track location in background exapmle",
wakeLockTime: 20,
autoStop: false,
interval: 1
),
);
}
More detail on LocationSettings
- Unregister the service when you are done:
@override
void dispose() {
IsolateNameServer.removePortNameMapping(_isolateName);
BackgroundLocator.unRegisterLocationUpdate();
super.dispose();
}