简体   繁体   中英

Navigation to next page in xamarin forms

Assume that i'm in the Page_1 while click the button have to navigate to Page_2.In Page_2 Api call has to done.

MyIssue is when i'm clicking the Button it doesn't navigate to Page_2 immediately it waits for the API response.

How to Navigate Immediately to Page_2 without waiting for the APi response.

Code:

Page_1.cs

public partial class Page_1 : ContentPage
{
    public Page_1()
    {
        InitializeComponent();
    }
    private void Btn_click(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page_2());
    }

}

Page_2:

public Page_2()
    {
        InitializeComponent();
    }
    protected override void OnAppearing()
    {
        HttpClient httpClient = new HttpClient();
        var obj = httpClient.GetAsync("//Api//").Result;
        if (obj.IsSuccessStatusCode)
        {

        }
    }

Same code works good in iOS as expected

You could load your data in an other Task to prevent blocking the UI.

protected override void OnAppearing()
{
    Task.Run( () => LoadData());
    base.OnAppearing();
}

private async void LoadData()
{
    HttpClient httpClient = new HttpClient();
    var obj = await httpClient.GetAsync("//Api//");
    if (obj.IsSuccessStatusCode)
    {
        // If you need to set properties on the view be sure to use MainThread
        // otherwise you won't see it on the view.
        Device.BeginInvokeOnMainThread(() => Name = "your text";);
    }
}

As per your question you are calling the API on Page constructor that's why it's taking time to load web API then navigating on page2. If you want to navigate on page2 before a load the api. Check below code

    public partial class Page2 : ContentPage
        {

            bool IsLoading{ get; set; }
            public Page2()
            {
                InitializeComponent();
                  IsLoading = false;
          }
             protected async override void OnAppearing()
            {
                base.OnAppearing();
                if (!IsLoading)
                {
                  IsLoading=true
                  **Call the Web API Method Here**
                }
                IsLoading=false
            }


         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM