title: Flutter - Enabling Location and Animate Camera to current location
body: <p>My aim is written above in the title.</p>
  
  <p>When I tried using my app with already location-enabled, The given function worked perfectly fine.
  But when I tried with location-disable, It asked me to turn on location, so I turned it on but the function did not work.</p>
  
  <p>I am calling my function from initState().</p>
  
  <pre><code>  firstLocation() async {
      await location.getLocation().then((LocationData locationData){
          //Sets the changing location in the Map Controller
          LatLng latLng = new LatLng(locationData.latitude, locationData.longitude);
          CameraUpdate cameraUpdate = CameraUpdate.newLatLngZoom(latLng, 15);
          mapController.animateCamera(cameraUpdate);
      });
    }
  </code></pre>
  
  <pre><code>@override
    void initState() {
      super.initState();
      firstLocation();
    }
  </code></pre>
  
  <p>If you want see the whole class code : </p>
  
  <pre><code>class UserMapState extends State&lt;UserMap&gt; {
  
    GoogleMapController mapController;
    // Location location = new Location();
  
    Map&lt;PolylineId, Polyline&gt; _mapPolylines = {};
    int _polylineIdCounter = 1;
  
    final List&lt;LatLng&gt; points = &lt;LatLng&gt;[];
  
    Set&lt;Marker&gt; _markers = {};
  
    LatLng _lastMapPosition; // CLASS MEMBER, MAP OF MARKS
    bool driver_status = false;
    bool pick_request = false;
  
    GeoFirePoint _driverCurrentLocation;        
  
    Geoflutterfire geo = Geoflutterfire();
  
    var firestore = Firestore.instance;
  
    BitmapDescriptor myIcon;
    BorderRadiusGeometry radius;
  
    var location = new Location();
  
  //   getDeviceLocation() async {
  //     LocationData currentLocation;
  //     try {
  //       currentLocation = await location.getLocation();
  
  //       print("locationLatitude: ${currentLocation.latitude}");
  //       print("locationLongitude: ${currentLocation.longitude}"); 
  //       setState(() {
  //        this.latitude_current = currentLocation.latitude;
  //        this.longitude_current = currentLocation.longitude;  
  //       });
  //  //rebuild the widget after getting the current location of the user
  //     } on Exception {
  //       currentLocation = null;
  //     }
  //   }
  
    getRoute() {
      firestore
        .collection(widget.institute)
        .document(widget.bus)
        .collection('Route')
        .orderBy('serial')
        .snapshots()
        .listen(
          (snap)  =&gt; snap.documents.forEach((doc){
            print(doc.data['LatLng'].latitude.toString());
            points.add(LatLng(doc.data['LatLng'].latitude, doc.data['LatLng'].longitude));                   
          }),
        );
    }
  
    firstLocation() async {
      location.getLocation().then((LocationData locationData){
          //Sets the changing location in the Map Controller
          LatLng latLng = new LatLng(locationData.latitude, locationData.longitude);
          CameraUpdate cameraUpdate = CameraUpdate.newLatLngZoom(latLng, 15);
          mapController.animateCamera(cameraUpdate);
      });
    }
  
    pickupRequest(bool value) async {
      var pos = await location.getLocation();
      GeoFirePoint point  = geo.point(latitude: pos.latitude, longitude: pos.longitude);
      firestore.collection(widget.institute).document(widget.bus).collection('Users').document(widget.uid).setData({
        'position': point.data,
        'pickup': value,
      });
    }
  
    @override
    void initState() {
      super.initState();
      getRoute();
      firstLocation();
      BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(48, 48)), 'assets/bus_icon.png')
          .then((onValue) {
            myIcon = onValue;
      });
      radius = BorderRadius.only(
        topLeft: Radius.circular(12.0),
        topRight: Radius.circular(12.0),
      );
    }
  
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text("Nomad"),
        ),
        drawer: DrawerWidget(name: widget.name, userID: widget.userID, institute: widget.institute,),
        body: SlidingUpPanel(
          panel: StreamBuilder(
            stream: firestore.collection(widget.institute.toString()).document(widget.bus.toString()).collection("Driver").snapshots(),
            builder: (context, snap) {
              if(snap.hasData) {
                List&lt;DocumentSnapshot&gt; snapshot = snap.data.documents;
                if(snapshot[0]['session'] == 1)
                {
                  _lastMapPosition = LatLng(snapshot[0]['location']['geopoint'].latitude, snapshot[0]['location']['geopoint'].longitude);
                  print(snapshot[0]['location']['geopoint'].latitude.toString());
                  this._driverCurrentLocation = geo.point(latitude: snapshot[0]['location']['geopoint'].latitude, longitude: snapshot[0]['location']['geopoint'].longitude);
                  print(_driverCurrentLocation.data['geopoint'].latitude.toString() + " " + _driverCurrentLocation.data['geopoint'].longitude.toString());
                  this.driver_status = true;
                  _getDriverMarker(_driverCurrentLocation.data['geopoint'].latitude, _driverCurrentLocation.data['geopoint'].longitude);
  
                  return Container(
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: &lt;Widget&gt;[
                          Center(
                            child: Text(
                              "Driver Name : " + snapshot[0]['name'] + "\n" + "Contact Driver : " + snapshot[0]['contact'],
                              textAlign: TextAlign.center,
                              style: TextStyle(color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.w300)
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                } else {
                  this.driver_status = false;
                  _getDriverMarker(0.0, 0.0);
                  return Container(
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: &lt;Widget&gt;[
                          Center(
                            child: Text(
                              "Driver Name : " + snapshot[0]['name'] + "\n" + "Contact Driver : " + snapshot[0]['contact'],
                              textAlign: TextAlign.center,
                              style: TextStyle(color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.w300)
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                }
              } else {
                return Container(
                    child: Center(child: CircularProgressIndicator(),),
                );
              }
            },
          ),
          collapsed: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: radius,
            ),
            child: Center(
              child: driver_status == true ?
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: &lt;Widget&gt;[
                  Text(
                    "Driver Online",
                    style: TextStyle(color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.w300),
                  ),
                  StreamBuilder(
                    stream: firestore.collection(widget.institute).document(widget.bus).collection('Users').document(widget.uid).snapshots(),
                    builder: (context, snap) {
                      if(snap.hasData) {
                        if(snap.data['pickup'] == false) {
                          return MaterialButton(
                            child: Text(
                              "Pickup", 
                              textAlign: TextAlign.center,
                              style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w300)
                            ),
                            color: Colors.blueAccent,
                            onPressed: () {
                              _addPickupMarker();
                            },
                          );
                        } else {
                          return MaterialButton(
                            child: Text(
                              "I am Riding", 
                              textAlign: TextAlign.center,
                              style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w300)
                            ),
                            color: Colors.blueAccent,
                            onPressed: () {
                              _removePickupMarker();
                            },
                          );
                        }
                      } else {
                        return CircularProgressIndicator(backgroundColor: Colors.blueAccent,);
                      }
                    },
                  ),
                ],
              ) :
               Text(
                "Driver Offline",
                style: TextStyle(color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.w300),
              ),
            ),
          ),
          body: Stack(
            children: &lt;Widget&gt;[
              GoogleMap(
                initialCameraPosition: CameraPosition(
                  target: LatLng(26.9124, 75.7873),
                  zoom: 12
                ),
                rotateGesturesEnabled: true,
                compassEnabled: true,
                onMapCreated: _onMapCreated,
                myLocationEnabled: true,
                myLocationButtonEnabled: true,
                mapType: MapType.normal,
                polylines: Set&lt;Polyline&gt;.of(_mapPolylines.values),
                markers: _markers,
              ),
            ],
          ),
          backdropEnabled: true,
          borderRadius: radius,
        )
      );
    }
  
    void _add() {
      final String polylineIdVal = 'polyline_id_$_polylineIdCounter';
      _polylineIdCounter++;
      final PolylineId polylineId = PolylineId(polylineIdVal);
  
      final Polyline polyline = Polyline(
        polylineId: polylineId,
        consumeTapEvents: true,
        color: Colors.grey,
        width: 10,
        points: points,
      );
  
      setState(() {
        _mapPolylines[polylineId] = polyline;
      });
    }
  
    _getDriverMarker(lat, long) async{
      if(driver_status == true) {
        SchedulerBinding.instance.addPostFrameCallback((_) =&gt; setState(() {
            this._markers.clear();
            this._markers.add(Marker(
              markerId: MarkerId(_lastMapPosition.toString()),
              icon: myIcon,
              position: LatLng(lat, long),
            )); 
        }));
      } else {
        SchedulerBinding.instance.addPostFrameCallback((_) =&gt; setState(() {
            this._markers.clear();  
        }));
      }
    }
  
    void _addPickupMarker() {
      SchedulerBinding.instance.addPostFrameCallback((_) =&gt; setState(() {
        // this._markers.add(Marker(
        //   markerId: MarkerId('1'),
        //   icon: BitmapDescriptor.defaultMarker,
        //   position: LatLng(latitude_current, longitude_current),
        // ));
          this.pick_request = true;
          pickupRequest(true); 
      }));
    }
  
    void _removePickupMarker() {
      SchedulerBinding.instance.addPostFrameCallback((_) =&gt; setState(() {
        // this._markers.remove(Marker(
        //     markerId: MarkerId('1'),
        //     icon: BitmapDescriptor.defaultMarker,
        //     position: LatLng(latitude_current, longitude_current),
        // ));
          this.pick_request = false;
          pickupRequest(false); 
      }));
    }
  
    _onMapCreated(GoogleMapController controller) {
      _add();
      setState(() {
        mapController = controller;
      });
    }
  
  }
  </code></pre>