1

I am trying to plot the user on a google map using the Geolocater plugin for flutter but whenever I try to select the screen with the map on it and get the users location via a method that is called on initState, it will not refresh the screen after I got the location. Here is the a simple example.


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

    mainBody() {
      if (position != null) {
        return Map();
      } else {
       _getCurrentPosition();
       return Loading();
    }
    }

3 Answers 3

2

For properly reproducing the issue you are facing I suggest you to share the full code of the page.

Try working with the logic shown below

    _getCurrentPosition() async{
      // await till you get actual Position 
         this.position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.best);
         setState(() { });
      }

Then let's write the code for the main design

@override
  void initState() {
    _getCurrentPosition();
    super.initState();
  }
// when the position is null loading bar is shown , when position is not null map is shown. 
//We are waiting till we get a value for position 
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: position != null ?
      map() : Container(
        child: Center(child: CircularProgressIndicator(),),
      ),
    );
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Update variable position from _getCurrentPosition() method like, this will trigger build method of the widget and draw map.

Position position;
  void _getCurrentPosition() async {
     position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best);
    setState(() {});
  }

Comments

0

What you have to do is to call the build method somehow. You can trigger the build method by using setState(). For more.

When do I use setState in Flutter?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.