Close AlertDialog on Navigating back from second screen and refresh page flutter

Issue

I have a method which check if the current users location is set, if not, open an alert dialog with two buttons: Cancel and Update Profile. the onPressed of the Update Profile button navigates to a second screen with a form to update users location. The issue is: if the user clicks on the Update button and update the location, on clicking back button, the first page is displayed with the alert dialog still open. Expectation: on closing the back button and on updating the location, the back button opens the first screen and refreshes the whole page, getting the new location setting.
See code: FIRST SCREEN (HOME SCREEN)
@override
void initState() {
super.initState();
getUserDetails();
}

  updateProfileLocationPrompt(BuildContext context) {
  Widget cancelButton = FlatButton(
  child: Text("Cancel",
  ),
  onPressed: () {
    Navigator.of(context).pop(true);
  },
  );
  Widget updateProfileButton = FlatButton(
  child: Text("Update",
  ),
  onPressed: () {
    Navigator.of(context)
        .push(new MaterialPageRoute(builder: (context) => SettingsScreen()));
  },
  );
  AlertDialog alert = AlertDialog(
   title: Text("Update location",
   ),
   content: Text(
    "Please Update you location",
   ),
   actions: [
    cancelButton,
    updateProfileButton,
   ],
  );

   // show the dialog
  showDialog(
  context: context,
  builder: (BuildContext context) {
    return alert;
   },
   );
  }

    getUserDetails() async {
   var firebaseUser = FirebaseAuth.instance.currentUser;

   DocumentSnapshot value = await FirebaseFirestore.instance
    .collection(Str.USERS)
    .doc(firebaseUser.uid)
    .get();
  if (value.data()[Str.ADDRESS].toString() == null ||
    value.data()[Str.ADDRESS].toString() == "") {
  return updateProfileAndLocationPrompt(context);
  } else {
  setState(() {
    searchLocationAddress = value.data()[Str.ADDRESS].toString();//got from firebase
    getItems();
  });
 }
 return;
}

SECOND SCREEN – SETTINGS SCREEN
Normal page with textfields for updating location to the firebase.
The issue really: How do I navigate back to home screen, refresh home screen with the new data and reload the page thus not opening the dialog as the check on location once set should not open the dialog.
Currently, even if i navigate from the dialog to the second screen, the alert dialog is still open, home screen is not refreshed with new data.

Solution

Try

  Widget updateProfileButton = FlatButton(
  child: Text("Update",
  ),
  onPressed: () async {
    Navigator.pop(context);
    await Navigator.of(context)
        .push(new MaterialPageRoute(builder: (context) => SettingsScreen()));
    setState((){});

  },
  );

Answered By – Josteve

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *