Flutter show and hide AlertDialog depend on dynamic value

Viewed 1505

In this snippet event value is stream value that can change dynamically.

LocationPermissions().serviceStatus.listen((event) {
    if(event == ServiceStatus.disabled){
      print('Location Disabled');
      testAlert(context); // Show dialog
    }else{
      testAlert(context); //I want hide dialog when user enable location.How do?
      print('Location Enabled');
         }
}   

This is my dialog code.

void testAlert(BuildContext context){
  showDialog(
    context: context,
    builder: (BuildContext context) {
      // return object of type Dialog
      return AlertDialog(
        title: new Text("Location service disable"),
        content: new Text("You must enable your location access"),
        actions: <Widget>[
          // usually buttons at the bottom of the dialog
          new FlatButton(
            child: new Text("Go Setting"),
            onPressed: () {
              openLocationSetting();
              //visible ?Navigator.pop(context , true): Navigator.pop(context, false);

            },
          ),
        ],
      );
    },
  );
}

How show and hide depend on event value.Thanks.

1 Answers

When user has enabled location then do no call the dialog method , just remove this line testAlert(context);

LocationPermissions().serviceStatus.listen((event) {
    if(event == ServiceStatus.disabled){
      print('Location Disabled');
      testAlert(context); // Show dialog
    }else{
     // testAlert(context); //remove or just comment this line 
      print('Location Enabled');
         }

}

Update:-

Dismiss alert on flat button by calling Navigator.pop() in this dialog will be dismissed

Example:-

void testAlert(BuildContext context){
  showDialog(
    context: context,
    builder: (BuildContext context) {
      // return object of type Dialog
      return AlertDialog(
        title: new Text("Location service disable"),
        content: new Text("You must enable your location access"),
        actions: <Widget>[
          // usually buttons at the bottom of the dialog
          new FlatButton(
            child: new Text("Go Setting"),
            onPressed: () {
              Navigator.pop(context)
              openLocationSetting();
              

            },
          ),
        ],
      );
    },
  );
}

Call this in lifecycle ie didChangeAppLifecycleState() method when user comes back to app again

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  // If user resumed to this app, check permission
  if(state == AppLifecycleState.resumed) {
   LocationPermissions().serviceStatus.listen((event) {
    if(event == ServiceStatus.disabled){
      print('Location Disabled');
      testAlert(context); // Show dialog
    }else{
      testAlert(context); //I want hide dialog when user enable location.How do?
      print('Location Enabled');
         }
    }  
  }
}
Related