Xamarin表单页面在异步调用完成之前不会加载

时间:2018-11-12 20:14:41

标签: c# xaml xamarin xamarin.forms

我正在尝试打开一个新页面,该页面显示了一个列表,其中填充了来自服务器的数据。从服务器获取数据的调用是使用从OnAppearing方法调用的异步函数完成的。但是,即使该方法是异步的,在调用完成之前也不会显示我的UI页面。如何解决该问题,或者进行此呼叫的最佳做法是什么?

这是我的页面XAML代码:

<StackLayout>
  <Label
    x:Name="NoPostsMessage"
    Text="You have not created any posts yet :("
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand" />

  <ListView
    x:Name="PostList"
    SelectionMode="None">
    <ListView.ItemTemplate>
      <DataTemplate>
        <TextCell Text="{Binding Text}" Detail="{Binding Detail}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout>

这是我的C#代码:

protected override void OnAppearing()
{
  base.OnAppearing();

  GetContributions();
}

async private void GetContributions()
{
  HttpClient client = new HttpClient();

  client.DefaultRequestHeaders.Add("Accept", "application/json");

  HttpResponseMessage response = await client
    .GetAsync
    (
      "websiteURL.com"
    );

  if (response.IsSuccessStatusCode)
  {
    APIResponse data = JsonConvert.DeserializeObject<APIResponse>(response.Content.ReadAsStringAsync().Result);
    if (data.ResponseCode == 1)
    {
      string payloadData = data.Data.ToString();
      List<TextCell> userPosts = JsonConvert.DeserializeObject<List<TextCell>>(payloadData);

      if (userPosts.Count == 0)
      {
        NoPostsMessage.IsVisible = true;
        PostList.IsVisible = false;
      }
      else
      {
        NoPostsMessage.IsVisible = false;
        PostList.IsVisible = true;

        ReportsList.ItemsSource = userPosts;
      }
    }
    else
    {
      await DisplayAlert("Error", data.ErrorMessage, "OK");
    }
  }
  else
  {
    await DisplayAlert("Error", "An error has occurred, please try again later", "OK");
  }
}

1 个答案:

答案 0 :(得分:3)

如果您不使用await,则async调用将阻止用户界面

protected async override void OnAppearing()
{
  base.OnAppearing();

  await GetContributions();
}