Are there any examples of how to use "Confirm" from Acr.UserDialogs in Xamarin.forms?

1

I recently made an app from Xamarin.forms in which I disabled the hardware BackButton.

This I did so that the App is not in the background when the user wants to leave and use only the buttons of the App.

As a result of this, I made a button so I can go out where I used Acr.UserDialogs (which was very useful and practical for many things) to show a window where you can confirm that you want to leave .

Inside the Clicked of the button is the following:

private void btnCerrar_Clicked(object sender, System.EventArgs e)
{
    msj.CerrarAppAsync();
}

As you can see, the button calls the CerrarAppAsync() method that is inside another class.

In this method is the following code:

public async void CerrarAppAsync()
{
    var confirmaSalir = new ConfirmConfig();
    confirmaSalir.Title = "Saliendo de la App";
    confirmaSalir.Message = "Está seguro que desea salir?";
    confirmaSalir.OkText = "Si";
    confirmaSalir.CancelText = "No";

    bool result = await UserDialogs.Instance.ConfirmAsync(confirmaSalir);

    if (result == true){
        if (Device.OS == TargetPlatform.Android){
            DependencyService.Get<IAndroidMethods>().CloseApp();
        }
    }else{
        return;
    }
}

This works fine and closes the App without problems, but really what I would like is for the method to return a Boolean value instead of closing the App since then I could use that method for more things. But the problem I have is that the device does not show the Dialog until all the code of the button is executed.

So if I leave the button code like this:

private void btnCerrar_Clicked(object sender, System.EventArgs e)
{
    bool sale = msj.CerrarAppAsync();
    if (sale == true){
        //Aquí va el código para cerrar.
    }
}

The Dialog is not going to show until after having passed through the if.

Is there something I'm doing wrong or just can not do what I want?

Thanks to everyone in advance!

    
asked by Matias 12.01.2018 в 20:20
source

1 answer

2

Calls to asynchronous methods for which a response should be expected are made using the Await instruction.

Otherwise, the calls are made async but the code is executed linearly, with which the following instructions follow their normal course.

To fix the problem you are having, you must do:

private async void btnCerrar_Clicked(object sender, System.EventArgs e)
{
    bool sale = await msj.CerrarAppAsync();
    if (sale == true){
        //Aquí va el código para cerrar.
    }
}

The function must be decorated with async, and the call to the asynchronic function must be using the await instruction

    
answered by 12.01.2018 / 22:20
source