Flutter geolocation not showing anything - flutter

I am new to flutter and trying to create a geolocation.
however, for my following code, the screen only shows 'Loading.. Please wait..' and the map is not showing.
i am just trying to show the current location using dependencies
geolocator: ^6.1.1
Using the codes from
https://codelabs.developers.google.com/codelabs/google-maps-in-flutter#3
the Google map can be shown successfully. So it is not issues related to Google Maps Platform.
// home.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool mapToggle = false;
var currentLocation;
GoogleMapController mapController;
#override
void initState() {
// TODO: implement initState
super.initState();
Geolocator.getCurrentPosition().then((currloc) {
setState(() {
currentLocation = currloc;
mapToggle = true;
});
});
}
void _onMapCreated(controller) {
setState(() {
mapController = controller;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(children: <Widget>[
Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height - 80.0,
width: double.infinity,
child: mapToggle
? GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(currentLocation.latitude,
currentLocation.longitude),
zoom: 10.0))
: Center(
child: Text(
'Loading.. Please wait..',
style: TextStyle(fontSize: 20.0),
)))
],
)
]),
);
}
}

In your AndroidManifest add permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
initialize variable
Position _currentPosition;
Copy this function and call this in initState
_getCurrentLocation() async{
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
For more info checkout their pub.dev site geolocatorunder usage,make sure you setup correctly for android and ios

As #theredcap already pointed out in his comment, you most probably don't have the necessary permissions. Always read the documentation of the plugin that you are using.
I don't see:
LocationPermission permission = await Geolocator.checkPermission();
nor do I see:
LocationPermission permission = await Geolocator.requestPermission();
in your code at all, yet the plugin docs clearly explain that part. Also, in case you are new to Android in general, take a look at: https://developer.android.com/training/location/permissions

Related

Google Map won't Load in Release Mode - Flutter

I'm trying to have a page in my app display a user's location on a google map, which works in debug mode, but when I run it in release mode it simply loads indefinitely. The strange thing is that if I click on a different page on my app and go back to the map page it will immediately show. Does anyone know what could be going on here?
I also get the following error: [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method camera#animate on channel plugins.flutter.io/google_maps_0)
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:mapapp/provider/location_provider.dart';
import 'package:provider/provider.dart';
class Map extends StatefulWidget {
const Map({Key? key}) : super(key: key);
#override
_State createState() => _State();
}
class _State extends State<Map> {
#override
void initState() {
super.initState();
Provider.of<LocationProvider>(context, listen: false).initalization();
}
//Sets map style once app is resumed to reload the map
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
dynamic controller;
controller.setMapStyle("[]");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(body: googleMapUI());
}
Widget googleMapUI() {
return Consumer<LocationProvider>(builder: (
consumerContext,
model,
child,
) {
while (model.locationPosition != null) {
return Column(
children: [
Expanded(
child: GoogleMap(
mapType: MapType.normal,
padding: const EdgeInsets.only(top: 40.0),
initialCameraPosition:
CameraPosition(target: model.locationPosition!, zoom: 18),
myLocationEnabled: true,
myLocationButtonEnabled: true,
onMapCreated: (GoogleMapController controller) async {
Provider.of<LocationProvider>(context, listen: false);
},
),
)
],
);
}
return const Center(
child: CircularProgressIndicator(),
);
});
}
}

how i can use google map to get current location or choose location?

i start with this code but all what i get white screen
how i can use google map to get current location or choose location.I am using GoogleMap package in flutter to get the required current location.
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { #override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Google Maps Demo', home: MapSample(), ); } }
class MapSample extends StatefulWidget { #override
State createState() => MapSampleState();
}
class MapSampleState extends State {
Completer _controller = Completer();
static final CameraPosition _kGooglePlex = CameraPosition( target:
LatLng(37.42796133580664, -122.085749655962), zoom: 14.4746, );
static final CameraPosition _kLake = CameraPosition( bearing:
192.8334901395799, target: LatLng(37.43296265331129,
-122.08832357078792), tilt: 59.440717697143555, zoom:
19.151926040649414);
#override Widget build(BuildContext context) { return new Scaffold(
body: GoogleMap(
mapType: MapType.hybrid, initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
floatingActionButton:
FloatingActionButton.extended(
onPressed: _goToTheLake,
label:
Text('To the lake!'),
icon: Icon(Icons.directions_boat), ),
);
}
Future _goToTheLake() async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
}
}
If you're using Url properly(no spelling/parameter mistakes) with API key and there's no error from the server which happens a lot due to restrictions. Then there are other steps you need to, ask Location permission on app loading using https://pub.dev/packages/permission_handler package like this.
Code can be something like this.
Create an app_persmission_provider file.
class AppPermissionProvider with ChangeNotifier {
PermissionStatus _locationStatus = PermissionStatus.denied;
LatLng? _locationCenter;
final location_package.Location _location =
location_package.Location();
location_package.LocationData? _locationData;
// Getter
get locationStatus => _locationStatus;
get locationCenter => _locationCenter;
get location => _location;
void getLocationStatus() async {
final status = await Permission.location.request();
_locationStatus = status;
notifyListeners();
print(_locationStatus);
}
void getLocation() async {
_locationData = await _location.getLocation();
_locationCenter = LatLng(
_locationData!.latitude as double, _locationData!.longitude as double);
notifyListeners();
}
}
Then declare the provider on the root maybe, and In my case, I'm initializing some functions onInit. By doing so, android will ask for permission for location when your page loads.
#override
void initState() {
super.initState();
appPermission = Provider.of<AppPermissionProvider>(context, listen: false);
appPermission.getLocationStatus();
appPermission.getLocation();
}
And then using consumer.
SafeArea(
child: Consumer<AppPermissionProvider>(
builder: (context, appPermissionProvider, _) => appPermission
.locationCenter ==
null
? const Center(child: CircularProgressIndicator())
:
GoogleMap( myLocationButtonEnabled:
appPermissionProvider.locationStatus ==
PermissionStatus.granted
? true
: false,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: appPermission.locationCenter,
zoom: 14,
),
onMapCreated: onMapCreated,
mapType: MapType.normal,
compassEnabled: true,
),
),
)
Here, I am checking if permission is granted, also I am only enabling myLocationButton if location permission is granted.
You can use google_maps_flutter package ,
A short example how you can use it.
For more clearity you can visit
Here or you can use geolocator.
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
LatLng _initialcameraposition = LatLng(20.5937, 78.9629);
GoogleMapController _controller;
Location _location = Location();
void _onMapCreated(GoogleMapController _cntlr)
{
_controller = _cntlr;
_location.onLocationChanged.listen((l) {
_controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.longitude),zoom: 15),
),
);
});
}

flutter could not find com.google.android.gms.vision.barcode when using flutter_barcode_scanner

I have this error when using flutter_barcode_scanner :
Local module descriptor class for com.google.android.gms.vision.barcode not found.
Error loading optional module com.google.android.gms.vision.barcode: com.google.android.gms.dynamite.DynamiteModule$LoadingException: No acceptable module found. Local version is 0 and remote version is 0.
Local module descriptor class for com.google.android.gms.vision.dynamite.barcode not found.
D/ViewRootImpl#9677bb1BarcodeCaptureActivity: ViewPostIme pointer 0
could any one help me please!
how to reproduce :
1- I just run the example provided with package
2- select scan barcode
3- the app ask for permission -> accept giving the permission
4- the scanner keep scan and did not catch the barcode
5- the error appear in android studio in the run tab
main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _scanBarcode = 'Unknown';
#override
void initState() {
super.initState();
}
Future<void> startBarcodeScanStream() async {
FlutterBarcodeScanner.getBarcodeStreamReceiver(
'#ff6666', 'Cancel', true, ScanMode.BARCODE)!
.listen((barcode) => print(barcode));
}
Future<void> scanQR() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> scanBarcodeNormal() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Barcode scan')),
body: Builder(builder: (BuildContext context) {
return Container(
alignment: Alignment.center,
child: Flex(
direction: Axis.vertical,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => scanBarcodeNormal(),
child: Text('Start barcode scan')),
ElevatedButton(
onPressed: () => scanQR(),
child: Text('Start QR scan')),
ElevatedButton(
onPressed: () => startBarcodeScanStream(),
child: Text('Start barcode scan stream')),
Text('Scan result : $_scanBarcode\n',
style: TextStyle(fontSize: 20))
]));
})));
}
}
Please make sure you have added these permissions in your app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application ...>
...
</application>
I faced the same problem
Try to run on another mobile

Flutter how to get latitude, longitude using geolocator package?

Flutter how to get latitude, longitude using geolocator package?
Already gave permissions both android and ios, downloaded package using pubspec.yaml. I don't understand why can't print longitude and latitude to console? tried write print(position), print(position.longitude()), print(position.latitue()).
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
print('Printing text before getCurrentLocation()');
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
color: Colors.red,
onPressed: () {
getLocation();
},
child: Text('Get Location'),
),
),
);
}
} ```
It should be position.latitude or position.longitude. You've used position.longitude() & position.latitude(), which is incorrect.
Also, you need to add async-await for onPressed callback. I'm assuming that you've added permissions in manifest & granted the necessary permissions as well.
Method
void getLocation() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position.latitude);
print(position.longitude);
}
Widget
RaisedButton(
color: Colors.red,
onPressed: () async {
await getLocation();
},
child: Text('Get Location'),
),

Get user location using flutter

I'm using the geolocator plugin to access the user's location but it seems like it does not work, cause when I run my code I get the error on message.
I have done all the geolocation configuration, but I have the problem.
Adding the Geolocator plugin(pubspec.yaml)
dependencies:
flutter:
sdk: flutter
geolocator: ^5.1.3
For android, head on over to your AndroidManifest.xml and add either of these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Source code for getting address
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_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.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}
The problem I get when I run my code is here.
Try flutter clean on terminal and then run the app again, You can also use location plugin instead of Geolocator, to get the user's location