How to enable location record by default as soon as the application starts or when the user logs in?
Your Environment
- Plugin version:Currrent
- Platform: iOS or Android
- OS version:Android
- Device manufacturer / model:Samsung galaxy s21 Ulta
- Flutter info (
flutter doctor): - Plugin config:
PASTE_YOUR_CODE_HERE
import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import '../utils/ad_helper.dart'; import '../widgets/menu_widget.dart'; import '../models/pickup_model.dart'; import '../provider/posts_provider.dart'; import '../CardPost.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../api.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import '../login.dart'; import 'dart:async'; import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg; class RedSocial extends StatefulWidget {
@override _RedSocialState createState() => _RedSocialState(); }
class _RedSocialState extends State
late bool _isMoving; late bool _enabled; late String _motionActivity; late String _odometer; late String _content;
ScrollController scrollController = new ScrollController(); final ordenesProvider = new PickupProvider();
GlobalKey
static final AdRequest request = AdRequest();
int maxFailedLoadAttempts = 3; int life = 0; late BannerAd _bannerAd; bool _isBannerAdReady = false;
InterstitialAd? _interstitialAd; int _numInterstitialLoadAttempts = 0;
RewardedAd? _rewardedAd; int _numRewardedLoadAttempts = 0;
RewardedInterstitialAd? _rewardedInterstitialAd;
int _numRewardedInterstitialLoadAttempts = 0;
@override void initState() {
super.initState();
_initPlatformState();
//_loadBannerAd();
//_createInterstitialAd();
_content = " Enable the switch to begin tracking.";
_isMoving = false;
_enabled = true;
_content = '';
_motionActivity = 'UNKNOWN';
_odometer = '0';
_onClickEnable(_enabled);
_initPlatformState();
scrollController.addListener(() {
// print(' ${scrollController.position.pixels}, ${scrollController.position.maxScrollExtent} ');
if ( (scrollController.position.pixels + 500) >= scrollController.position.maxScrollExtent ) {
// add5();
fetchData();
}
});
}
//Future
// 1. Listen to events (See docs for all 12 available events).
bg.BackgroundGeolocation.onLocation(_onLocation, _onLocationError);
bg.BackgroundGeolocation.onMotionChange(_onMotionChange);
bg.BackgroundGeolocation.onActivityChange(_onActivityChange);
bg.BackgroundGeolocation.onProviderChange(_onProviderChange);
bg.BackgroundGeolocation.onConnectivityChange(_onConnectivityChange);
bg.BackgroundGeolocation.onHttp(_onHttp);
//bg.BackgroundGeolocation.onAuthorization(_onAuthorization);
// 2. Configure the plugin
bg.BackgroundGeolocation.ready(bg.Config(
reset: true,
debug: false, //habilitar efectos de sonido y notificaciones locales
logLevel: bg.Config.LOG_LEVEL_VERBOSE,
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
distanceFilter: 10.0,
backgroundPermissionRationale: bg.PermissionRationale(
title:
"Allow {applicationName} to access this device's location even when the app is closed or not in use.",
message:
"This app collects location data to enable recording your trips to work and calculate distance-travelled.",
positiveAction: 'Change to "{backgroundPermissionOptionLabel}"',
negativeAction: 'Cancel'),
url: API_URL +"device/locations2",
extras: {
//"imei": imei,
"userId": userId
},
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true))
.then((bg.State state) {
print("[ready] ${state.toMap()}");
setState(() {
_enabled = state.enabled;
_isMoving = state.isMoving!;
});
}).catchError((error) {
print('[ready] ERROR: $error');
});
}
void _onClickEnable(enabled) { if (enabled) { // Reset odometer. bg.BackgroundGeolocation.start().then((bg.State state) { print('[start] success $state'); setState(() { _enabled = state.enabled; _isMoving = state.isMoving!; }); }).catchError((error) { print('[start] ERROR: $error'); }); } else { bg.BackgroundGeolocation.stop().then((bg.State state) { print('[stop] success: $state');
setState(() {
_enabled = state.enabled;
_isMoving = state.isMoving!;
});
});
}
}
// Manually toggle the tracking state: moving vs stationary void _onClickChangePace() { setState(() { _isMoving = !_isMoving; }); print("[onClickChangePace] -> $_isMoving");
bg.BackgroundGeolocation.changePace(_isMoving).then((bool isMoving) {
print('[changePace] success $isMoving');
}).catchError((e) {
print('[changePace] ERROR: ' + e.code.toString());
});
}
// Manually fetch the current position. void _onClickGetCurrentPosition() { bg.BackgroundGeolocation.getCurrentPosition( persist: true, // <-- do persist this location desiredAccuracy: 0, // <-- desire best possible accuracy timeout: 30, // <-- wait 30s before giving up. samples: 3 // <-- sample 3 location before selecting best. ) .then((bg.Location location) { print('[getCurrentPosition] - $location'); }).catchError((error) { print('[getCurrentPosition] ERROR: $error'); }); }
void _onLocation(bg.Location location) { print('[location] - $location');
String odometerKM = (location.odometer / 1000.0).toStringAsFixed(1);
setState(() {
_content = encoder.convert(location.toMap());
_odometer = odometerKM;
});
}
void _onLocationError(bg.LocationError error) { print('[location] ERROR - $error'); }
void _onMotionChange(bg.Location location) { print('[motionchange] - $location'); }
void _onActivityChange(bg.ActivityChangeEvent event) { print('[activitychange] - $event'); setState(() { _motionActivity = event.activity; }); }
void _onHttp(bg.HttpEvent event) async { print('[${bg.Event.HTTP}] - $event'); }
void _onAuthorization(bg.AuthorizationEvent event) async { print('[${bg.Event.AUTHORIZATION}] = $event');
bg.BackgroundGeolocation.setConfig(
bg.Config(url: API_URL +'device/locations2'));
//bg.Config(url: 'http://18.221.225.29:8083/device/locations2'));
//bg.Config(url: 'http://144.91.97.233:8083/device/locations2'));
}
void _onProviderChange(bg.ProviderChangeEvent event) { print('$event');
setState(() {
_content = encoder.convert(event.toMap());
});
}
void _onConnectivityChange(bg.ConnectivityChangeEvent event) { print('$event'); }
// Showing ads from here void _showInterstitialAd() { if (_interstitialAd == null) { print('Warning: attempt to show interstitial before loaded.'); return; } _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback( onAdShowedFullScreenContent: (InterstitialAd ad) => print('ad onAdShowedFullScreenContent.'), onAdDismissedFullScreenContent: (InterstitialAd ad) { print('$ad onAdDismissedFullScreenContent.'); ad.dispose(); _createInterstitialAd(); }, onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) { print('$ad onAdFailedToShowFullScreenContent: $error'); ad.dispose(); _createInterstitialAd(); }, ); _interstitialAd!.show(); _interstitialAd = null; }
void _createInterstitialAd() { InterstitialAd.load( adUnitId: AdHelper.interstitialAdUnitId, request: request, adLoadCallback: InterstitialAdLoadCallback( onAdLoaded: (InterstitialAd ad) { print('$ad loaded'); _interstitialAd = ad; _numInterstitialLoadAttempts = 0; _interstitialAd!.setImmersiveMode(true); }, onAdFailedToLoad: (LoadAdError error) { print('InterstitialAd failed to load: $error.'); _numInterstitialLoadAttempts += 1; _interstitialAd = null; if (_numInterstitialLoadAttempts < maxFailedLoadAttempts) { _createInterstitialAd(); } }, )); }
void _loadBannerAd() { bannerAd = BannerAd( adUnitId: AdHelper.bannerAdUnitId, request: AdRequest(), size: AdSize.banner, listener: BannerAdListener( onAdLoaded: () { setState(() { _isBannerAdReady = true; }); }, onAdFailedToLoad: (ad, err) { _isBannerAdReady = false; ad.dispose(); }, ), );
_bannerAd.load();
}
@override void dispose() {
//BlocProvider.of<MiUbicacionBloc>(context).cancelarSeguimiento();
//locationBloc.stopFollowingUser();
//super.dispose();
//scrollController.dispose();
}
@override Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
Navigator.of(context).pushReplacementNamed('/red_social');
return false; // Evita que la aplicación se cierre al presionar "flecha atrás"
},
child : Scaffold(
key: _scaffoldKey,
drawer: MenuWidget(),
appBar: AppBar(
centerTitle: true,
title: Text('Lista de publicaciones'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add, color: Colors.white),
onPressed: () {
if (_isBannerAdReady) {
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: _bannerAd.size.width.toDouble(),
height: _bannerAd.size.height.toDouble(),
child: AdWidget(ad: _bannerAd),
),
);
}
_showInterstitialAd();
Navigator.pop(context); // pop current page
//sincronizar(context);
Navigator.pushNamed(context, "/crear_post"); // push it back in
},
tooltip: "Cerrar sesion",
)
],
),
body: _crearListado(),
//floatingActionButton: _crearBoton( context ),
),
);
}
Widget _crearListado() {
return FutureBuilder(
future: ordenesProvider.cargarOrdenes(),
builder:
(BuildContext context, AsyncSnapshot<List
),
);
//);
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
}
Future fetchData() async {
if ( isLoading ) return;
isLoading = true;
setState(() {});
await Future.delayed( const Duration( seconds: 3 ));
add5();
isLoading = false;
setState(() {});
if ( scrollController.position.pixels + 100 <= scrollController.position.maxScrollExtent ) return;
scrollController.animateTo(
scrollController.position.pixels + 120,
duration: const Duration( milliseconds: 300 ),
curve: Curves.fastOutSlowIn
);
}
Future fetchDataOLD() async {
if ( isLoading ) return;
isLoading = true;
setState(() {});
await Future.delayed( const Duration( seconds: 3 ));
//add5();
isLoading = false;
}
void add5() { final lastId = imagesIds.last; imagesIds.addAll( [1,2,3].map((e) => lastId + e ) ); setState(() {}); }
Future
final lastId = imagesIds.last;
imagesIds.clear();
imagesIds.add(lastId + 1);
add5();
}
Widget _crearItem(BuildContext context, PickupModel orden) { return CardOrden(orden); }
void logout() async { var prefs = await SharedPreferences.getInstance();
var token = prefs.getString("token") ?? "";
var usuario = prefs.getString("usuario") ?? "";
if(token.isEmpty == true){
//Navigator.pushNamed(context, '/login');
print('Redireccionando a loginpage');
}else{
print('Token encontrado');
}
}
Widget _crearLoading() {
if (isLoading) {
return Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children:
Expected Behavior
That when the user authenticates from the login.dart page and enters the home.dart page, it begins to register the locations automatically.
Actual Behavior
It does not register any location when entering this page home.dart and when I leave that page and go for example to the page other_page.dart this returns a dispose error.
Steps to Reproduce
- The application login page calls login.dart and it doesn't have your plugin code. This is only to authenticate the user and after authenticating if it should start automatically recording locations
- After the user is logged in, he is redirected to the home.dart page. This page has the code of your plugin to register locations with all functions like _initPlatformState and so on. Previously put the code of this page home.dart. However, after the user enters this "home" page, it does not record the location automatically. I put this function "_onClickEnable(_enabled);" inside the initState and I set this variable _enable to true. Why doesn't it automatically record the location after entering the user or authenticating?
- As the above code from the home.dart page shows, I have disabled the super.dispose(); in the dispose method because otherwise when entering this page it generates an error. However, when leaving this home.dart page and going to the other_page.dart page, I get the following error:
throw FlutterError.fromParts(
[ ErrorSummary('${state.runtimeType}.dispose failed to call super.dispose.'), ErrorDescription( 'dispose() implementations must always call their superclass dispose() method, to ensure ' 'that all the resources used by the widget are fully released.', ), How can I correct this? - Should I put all the plugin code like the _initPlatformState method and so on in all the pages of my app to record the location automatically?
Context
Debug logs
Logs
As the above code from the home.dart page shows, I have disabled the super.dispose(); in the dispose method because otherwise when entering this page it generates an error. However, when leaving this home.dart page and going to the other_page.dart page, I get the following error: throw FlutterError.fromParts(
- see methods
.start()and.changePacein api docs. - See wiki here at GitHub repo “Philosophy of Operation”.
-
Yes i read this methods and Philosophy of operation, but this not resolve my question of use Super.dispose in dispose function in my home_page.dart file. Now i im getting this error: Se produjo una excepción. FlutterError (setState() called after dispose(): _RedSocialState#4bbf7(lifecycle state: defunct, not mounted) This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree. This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)
-
Second this also doesn't answer if I should include all the _initPlatformState methods, start the service etc in each page of my application. Please can you answer me if I should include all these functions and start the service in each page that I call in my application?
Super.dispose in dispose
The plug-in has nothing to do with Flutter widgets. I know nothing about this. This is your own application code.
Second this also doesn't answer if I should include all the _initPlatformState methods,
What do mean “include”? “Include” from what? Yes, one should initialize plug-ins in a Flutter Stateful widget’s initState method.
start the service etc in each page of my application.
are you observing the logs from the plug-in while developing and using debug: true so you can hear what the plug-in is doing? I have a feeling you’re not. This is a very complex plug-in. You need to observe the plug-in logs to understand what it’s doing. I have a feeling you’re just blindly copy/pasting code from the /example. That’s not how you do it! There’s the simplest possible example of the plug-in usage in the readme.
No, you don’t need to “start the service in each page” (unless you previously told the plug-in to .stop()).
All fixed!