I'm trying to get a list from a web api which I've written before. Then I'll use that list in Xamarin.Forms ListView. My code is here:
public static class DataSource
{
public static async Task<Restoran[]> GetRestoransAsync()
{
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
var restorans = JsonConvert.DeserializeObject<Restoran[]>(result);
return restorans;
}
}
}
My ContentPage:
public class MenuPage : ContentPage
{
ListView listView;
List<Restoran> restorans = new List<Restoran>();
async Task LoadRestorans()
{
restorans = (await DataSource.GetRestoransAsync()).ToList();
}
public MenuPage(string masa)
{
var loadData = LoadRestorans();
loadData.Wait();
listView = new ListView(ListViewCachingStrategy.RecycleElement)
{
ItemsSource = restorans,
ItemTemplate = new DataTemplate(() => {
var nativeCell = new CustomCell();
return nativeCell;
})
};
}
}
But when I debugged this code, "LoadRestorans()" method has called just before initialization of "restorans" list. I think I don't understand the mentality of async methods. What should I do?