OnAppearing is a .NET MAUI page lifecycle method called after a page becomes visible. Use it for work that should happen when the page appears, especially page initialization and data loading. section 7.3 section 7.3.1
Use OnAppearing to:
- Load data from a database or web API through asynchronous code. section 7.3.1
- Keep constructors focused on setting initial field values rather than performing page work. section 7.3.1
- Show a loading indicator while visible-page data loads. section 7.3.3
Loading a to-do list
Override OnAppearing as async, call base.OnAppearing(), await the database query, and add the returned items to the page collection. This replaces a separate Initialize method called from the constructor. section 7.3.1
Loading movie data
A movie page sets IsLoading, retrieves genres and trending movies with HttpClient, then clears IsLoading after both requests complete. section 6.2.1
Listing 7.5 The OnAppearing method in MainPage.xaml.cs
protected override async void OnAppearing() #1
{
base.OnAppearing(); #2
var todos = await _database.GetTodos(); #3
foreach (var todo in todos) #3
{
Todos.Add(todo); #3
}
}
View the complete OnAppearing override used to load to-do items from a database. section 7.3.1
