Cameron Johnson
Cameron Johnson

Reputation: 163

How to refresh state when a variable is not null in flutter?

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();
    }
    }

Upvotes: 1

Views: 632

Answers (3)

Jeslin Jacob
Jeslin Jacob

Reputation: 659

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(),),
      ),
    );
 }

Upvotes: 2

Md omer arafat
Md omer arafat

Reputation: 466

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?

Upvotes: 0

Jitesh Mohite
Jitesh Mohite

Reputation: 34200

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(() {});
  }

Upvotes: 1

Related Questions