How to change onPressed to one time function - flutter

I am customizing flutter ecommerce mobile app from codecanyon.
How can I change the onPressed command to one time function that will work automatically for one time
onPressed: () async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Map(
latitude: latitude == null
? position.latitude
: double.parse(latitude),
longitude: longitude == null
? position.longitude
: double.parse(longitude),
from: getTranslated(context, 'ADDADDRESS'),
)));
if (mounted) setState(() {});
List<Placemark> placemark = await placemarkFromCoordinates(
double.parse(latitude), double.parse(longitude));
state = placemark[0].administrativeArea;
country = placemark[0].country;
pincode = placemark[0].postalCode;
// address = placemark[0].name;
if (mounted)
setState(() {
countryC.text = country;
stateC.text = state;
pincodeC.text = pincode;
// addressC.text = address;
});
},

#override
void initState(){
super.initState();
_openMap();
}
......
void _openMap() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Map(
latitude: latitude == null
? position.latitude
: double.parse(latitude),
longitude: longitude == null
? position.longitude
: double.parse(longitude),
from: getTranslated(context, 'ADDADDRESS'),
)));
if (mounted) setState(() {});
List<Placemark> placemark = await placemarkFromCoordinates(
double.parse(latitude), double.parse(longitude));
state = placemark[0].administrativeArea;
country = placemark[0].country;
pincode = placemark[0].postalCode;
// address = placemark[0].name;
if (mounted)
setState(() {
countryC.text = country;
stateC.text = state;
pincodeC.text = pincode;
// addressC.text = address;
});
}
.......
.....
onPressed:_openMap

Related

my flutter app is not taking location in real device at first time but work properly in emulator?

This code is working fine in emulator but it doesn't work properly in real device . This code for taking user location but when i open 1st time app it only ask permission for location and doesn't getlocation if restart my application then it take location.
#override
void initState() {
// TODO: implement initState
super.initState();
showAddress(context);
didChangeDependencies();
}
Future showAddress(BuildContext context) async {
await locationService();
}
void getYourAddress() {
homeServices.addAddress(
context: context,
address: address,
latitude: lat!,
logitude: long!,
locality: locality,
);
}
double? lat;
double? long;
String address = '';
String locality = '';
//For convert lat long to address
getAddress(lat, long) async {
List<geocoding.Placemark> placemarks =
await geocoding.placemarkFromCoordinates(lat, long);
if (mounted) {
setState(() {
address =
"${placemarks[0].street!} ${placemarks[0].subLocality!} ${placemarks[0].locality!} ${placemarks[0].postalCode!} ${placemarks[0].country!} ";
if (placemarks[0].locality == '') {
locality = placemarks[0].street!;
} else {
locality = placemarks[0].locality!;
}
});
}
for (int i = 0; i < placemarks.length; i++) {
print("INDEX $i ${placemarks[i]}");
}
getYourAddress();
}
Future locationService() async {
Location location = Location();
bool serviceEnabled;
PermissionStatus permissionLocation;
LocationData locData;
serviceEnabled = await location.serviceEnabled();
if (serviceEnabled == false) {
serviceEnabled = await location.requestService();
if (serviceEnabled == true) {
permissionLocation = await location.hasPermission();
if (permissionLocation == PermissionStatus.denied) {
permissionLocation = await location.requestPermission();
if (permissionLocation != PermissionStatus.granted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
}
} else if (serviceEnabled == true) {
permissionLocation = await location.hasPermission();
if (permissionLocation == PermissionStatus.denied) {
permissionLocation = await location.requestPermission();
if (permissionLocation != PermissionStatus.granted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else if (permissionLocation == PermissionStatus.granted) {
await getLocation();
}
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const IntroScreen(),
),
);
}
}
// Problem occuring at this point in emulator it work fine but not work in real device.
getLocation() async {
try {
LocationData locData;
Location location = Location();
locData = await location.getLocation();
if (mounted) {
setState(() {
lat = locData.latitude!;
long = locData.longitude!;
});
await getAddress(lat, long);
}
} catch (e) {
getLocation();
}
}
This code is working fine in emulator but it doesn't work properly in real device . This code for taking user location but when i open 1st time app it only ask permission for location and doesn't getlocation if restart my application then it take location.
I am expecting this app to ask user for location permission and store data imidiately to database. But it doesn't doing it on first time after i restart app then it take location . Please help me to solve this problem.
I am use Using Location and Gecoding widget of flutter. when i try ti= check logs of my app in real device it show that asynchronous suspension.

Flutter walk & draw polylines following current location

Using flutter_polyline_points: ^1.0.0 & google_maps_flutter: ^2.2.1
So what I am trying to achieve is to draw polylines on Google Map at flutter following current WALKING user location [using Geolocator]. The code below works, except when I stay out of the road, polylines are not drawn after my location [the location of blue dot at google maps] but they stick to the main road and won't cross it's boundaries...
(https://i.stack.imgur.com/FHV2d.jpg)
CountDown func is counting down to 0 and then showing map/location/timer etc [start walk]
_CountDown() async {
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(oneSec, (timer) {
_startTimer == 0
? setState(
() {
timer.cancel();
_getCurrentLocation();
Future.delayed(const Duration(seconds: 5), () {
stopWatchTimer.onStartTimer();
_updateMapAndValues();
});
},
)
: setState(
() => _startTimer--,
);
});
}
_getCurrentLocation() is getting current position and sets late _currectPosition to later zoom on it with map.
_getCurrentLocation() async {
await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
forceAndroidLocationManager: true)
.then((Position position) async {
setState(() {
_currentPosition = position;
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: 18.0,
),
),
);
});
}).catchError((e) {
print(e);
});
}
After that I am stopping the timer/updating the map.
First I am getting current position to check if location changed, then I am creating polyline between old _currentposition and new position (later calc distance and coins but that's not that importand).
_updateMapAndValues() async {
bool petla = true;
while (petla) {
await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
forceAndroidLocationManager: true)
.then((Position position) async {
await Future.delayed(const Duration(milliseconds: 500));
if (_currentPosition.latitude != position.latitude &&
_currentPosition.longitude != position.longitude) {
_createPolylines(_currentPosition, position);
await _calculateDistance();
setState(() {
_currentPosition = position;
int result = distance * 1000 ~/ 50;
print('DYSTANS ILE COINOW : $result');
if (result > 0) {
while (coins < result) {
setState(
() => coins++,
);
}
}
});
}
});
}
}
The _createPolylines function. I thought it will work adding travelMode:walking but it does not. Still (mostly) following the roads and when I am moving at the edges (screen) it just draw straight line.
late PolylinePoints polylinePoints;
List<LatLng> polylineCoords = [];
Map<PolylineId, Polyline> polylines = {};
_createPolylines(Position start, Position end) async {
polylinePoints = PolylinePoints();
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
'AIzaSyDDyBb0N9_jthBS99PRJcT6CjFV2TI9J5E',
PointLatLng(start.latitude, start.longitude),
PointLatLng(end.latitude, end.longitude),
travelMode: TravelMode.walking,
avoidHighways: true,
);
if (result.points.isNotEmpty) {
result.points.forEach((element) {
polylineCoords.add(LatLng(element.latitude, element.longitude));
print('--------WYSWIETLAM: $polylineCoords');
});
}
PolylineId id = const PolylineId('poly');
Polyline polyline = Polyline(
polylineId: id,
color: Colors.red,
points: polylineCoords,
width: 5,
);
polylines[id] = polyline;
}

Flutter field has not been initialized

i have a bool that i set to true if the account datas is right but my bool is set to late and it doesnt works
My Model:
bool _result = false;
Future login(String username, String password) async {
var url = "http://192.168.178.75/flutterconn/login.php";
var response = await http.post(Uri.parse(url), body: {
"username": username,
"password": password,
});
var data = await json.decode(response.body);
if (data == "success") {
setResult(true);
Fluttertoast.showToast(msg: "Erfolgreich Eingeloggt",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.CENTER,fontSize: 16.0);
}else {
Fluttertoast.showToast(msg: "Nicht Eingeloggt",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.CENTER,fontSize: 16.0);
}
//print(_result);
notifyListeners();
}
Future setResult(bool rs) async{
_result = await rs;
notifyListeners();
}
bool getResult(){
return _result;
}
My onPressed Method:
context.read<LoginModel>().login(
usernameController.text, passwordController.text);
print(context.read<LoginModel>().getResult());
if (context.read<LoginModel>().getResult()) {
context.read<FoodSelectionModel>().loadGalleryLinks();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FoodSelectionScreen()),
);
}
My Error:
The following LateError was thrown while handling a gesture:
LateInitializationError: Field '_result#21188420' has not been initialized.
The Bool is turned to late to true how can i set it faster.
i tried with putting async on my onPressed method and await it works thank you guys.
onPressed: () async {
await context.read<LoginModel>().login(
usernameController.text, passwordController.text);
print(context.read<LoginModel>().getResult());
if (context.read<LoginModel>().getResult()) {
context.read<FoodSelectionModel>().loadGalleryLinks();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FoodSelectionScreen()),
);
}

Shared preference save location address from geolocator

i was able to get current location using geolocator, but i want to cache and restore the string address without using lastKnownLocation in geolocator. im using shared preferences but cannot make it work. i used shared preference several times on my other codes, but with geolocator its kind of complicated. and im super new to flutter/dart
code:
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
String _locationCache;
String key = "location_cache";
#override
void initState() {
super.initState();
_getCurrentLocation();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("current location = " + _currentAddress),
Text("last location = " + __locationCache) // HERE GET STORED DATA ISNT WORKING
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress = "${place.country}";
});
saveAddress();
} catch (e) {
print(e);
}
}
Future<bool> saveAddress() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return await prefs.setString(key, _currentAddress);
}
Future<String> retrieveAddress() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
return prefs.getString(key) ?? "";
}
loadAddress() {
retrieveAddress().then((value) {
setState(() {
_locationCache = value;
});
});
}
}
heres the working code without _locationCache:
Thank you for your time
If I understood you correctly, what you want to accomplish is to store the last address you caught and retrieve it if you don't have gps active.
To do so you could use SharedPreferences or SQLite, just check the documentation on how to use them.
found the solution. just replace loadAddress() function with
void save() {
String address = _currentAddress;
saveAddress(address);
}
void _updateName(String address) {
setState(() {
this.locationCache = address;
});
}
and then put retrieveAddress().then(updateName) inside initState()

Google Places AutoComplete not Displaying Addresses when Searching

I am currently working on an app that uses google places autocomplete to find addresses around the world. I have implemented it in the following way:
Position currentPosition;
var placeId, address;
double lat, lng;
getCurrentLocation(){
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position){
setState(() {
currentPosition = position;
});
}).catchError((e){
print(e);
});
}
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
PlacesDetailsResponse detail = await _places.getDetailsByPlaceId(p.placeId);
placeId = p.placeId;
lat = detail.result.geometry.location.lat;
lng = detail.result.geometry.location.lng;
address = await Geocoder.local.findAddressesFromQuery(p.description);
}
}
onPressed: () async {
print(currentPosition.latitude);
print(currentPosition.longitude);
Prediction prediction = await PlacesAutocomplete.show(
context: context,
apiKey: googleApiKey,
location: Location(currentPosition.latitude, currentPosition.longitude),
radius: 100000000,
mode: Mode.overlay,
language: "en",
);
However, whenever I type something into the search bar, I do not receive any autocompleted results and I am not sure why (image attached). If it makes any difference, I am using the iOS simulator. I haven't yet tested on Android. Any help would be much appreciated.