I want to display alert in my main page loading time. So i declared display alert in my constructor. But i didn't get any response.
I have attached my sample code.
public Home()
{
InitializeComponent();
if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
{
if (System.IO.File.Exists(path + "App" + "/Data.txt"))
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Success", "Saved", "OK");
});
}
else
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Oops", "Login Required", "OK");
});
}
}
else
{
GetDetails();
}
}
The constructor is meant to keep Initialization code. TheOnAppearing() method is called when the Page is about to be displayed.The displayAlert() will succeed inside this method. This is the sample code.
protected override void OnAppearing()
{
Application.Current.MainPage.DisplayAlert("Success", "Saved", "OK");
base.OnAppearing();
}
Keep you initialization code in the constructor or new Task(Init).Start(); as suggested in other answer. Save the status of if else in field of type bool. Alter the message in the OnAppearing() method according to the field.
You can not directly await a Task within the .ctor of a class (search SO there are plenty of Q&A on this).
In your .ctor, after the InitializeComponent start a void Task (fire and forget style):
new Task(Init).Start();
The void task Init will look like:
async void Init()
{
if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
{
~~~
}
else
{
GetDetails();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With