3

it does not even show the request for permission to access the users location

enter image description here

i am working on a sort of a delivery application but for good upon request just like uber, the code below is to access the users location upon loading .The problem is the code does not show any errors but does not show google maps after loading it just shows white background.

 import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:isntadelivery/Signin.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';


import 'package:permission_handler/permission_handler.dart' as Thendelo;

import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
// import 'package';

class Homepage extends StatefulWidget {
  Homepage({Key key}) : super(key: key);

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {
 GoogleMapController _controller;

    GoogleMapController mapController;
  
      
  Position position;
  Widget _child;

  Future<void> getpermission() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.location);

    if (permission == PermissionStatus.denied) {
      await PermissionHandler()
          .requestPermissions([PermissionGroup.locationAlways]);
    }

    var geolocater = new Geolocator();
    GeolocationStatus geolocationStatus =
        await geolocater.checkGeolocationPermissionStatus();
    switch (geolocationStatus) {
      case GeolocationStatus.denied:
        showToast('denied');
        break;
      case GeolocationStatus.disabled:
        showToast('disabled');
        break;
      case GeolocationStatus.restricted:
        showToast('restricted');
        break;
      case GeolocationStatus.unknown:
        showToast('unknown');
        break;
      case GeolocationStatus.granted:
        showToast('Access granted');
        _getCurrentLocation();
    }
  }

  Set<Marker> _createMarker() {
    return <Marker>[
      Marker(
          markerId: MarkerId('home'),
          position: LatLng(position.latitude, position.longitude),
          icon: BitmapDescriptor.defaultMarker,
          infoWindow: InfoWindow(title: 'Current Location'))
    ].toSet();
  }

  void showToast(message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        // timeInSecFor Ios: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  void _setStyle(GoogleMapController controller) async {
    String value = await DefaultAssetBundle.of(context)
        .loadString('assets/map_style.json');
    controller.setMapStyle(value);
  }

  Widget _mapWidget() {
    return GoogleMap(
      mapType: MapType.normal,
      markers: _createMarker(),
      initialCameraPosition: CameraPosition(
        target: LatLng(position.latitude, position.longitude),
        zoom: 12.0,
      ),
      onMapCreated: (GoogleMapController controller) {
        _controller = controller;
        //  _controller.complete(controller);
        _setStyle(controller);
      },
    );
  }
  //map style variable

  void _getCurrentLocation() async {
    Position res = await Geolocator().getCurrentPosition();
    setState(() {
      position = res;
      _child = _mapWidget();
    });
  }

  // singoutmethod
  signOutGoogle() async {
    await googleSignIn.signOut();
    print("User Sign Out");
  }

  // firebase authorisation
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  final GoogleSignIn googleSignIn = GoogleSignIn();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: _child,
      drawer: Drawer(
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: new Text('Thabelo Mutshinyani'),
              accountEmail: new Text('mutshinyanit@gmail.com'),
              currentAccountPicture: new CircleAvatar(),
            ),
            ListTile(
              leading: Icon(Icons.person_outline),
              title: Text('Update Profile'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.payment),
              title: Text('payment details'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.settings),
              title: Text('Settings'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(Icons.exit_to_app),
              title: Text('LogOut'),
              onTap: () {
                signOutGoogle().whenComplete(() {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) {
                        return Signin();
                      },
                    ),
                  );
                });
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

3 Answers3

3

I think, based on your code, you should add the desiredAccuracy inside your _getCurrentLocation(). Like this:

  void _getCurrentLocation() async {
    Position res = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    setState(() {
      position = res;
      _child = _mapWidget();
    });
  }

And, to run the _getCurrentLocation() function at the beginning of the app, you should wrap it inside the initState method.

Inside your StatefulWidget class, add:

  @override
  void initState() {
    _getCurrentLocation();
    super.initState();
  }

And then add the Location permission inside the device or emulator you're using. Add this line of codes inside the AndroidManifest.xml file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Example

And my tips, cold restart your app (stop debug and debug it again from the beginning).

hisam
  • 1,566
  • 1
  • 7
  • 21
1

For IOS If you using this plugin, you also need to add permission in info plist like this, just copy and paste it.

<key>NSLocationWhenInUseUsageDescription</key>
        <string>This app needs location when in use</string>
        <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>Always and when in use!</string>
        <key>NSLocationUsageDescription</key>
        <string>Older devices need location.</string>
        <key>NSLocationAlwaysUsageDescription</key>
        <string>Can I have location always?</string>

For android

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Quick learner
  • 10,632
  • 4
  • 45
  • 55
0
@override
  void initState() {
    _getCurrentLocation();
    super.initState();
  }