NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML. Using .NET MAUI, you can develop apps that can run on Android, iOS, macOS, and Windows from a single shared code-base. In this post, I will show you how to implement a responsive Flyout in your .NET MAUI app using Microsoft.Maui.Devices
class by detecting when the screen size changes for iOS and Android.
Essentials
In .NET MAUI the Xamarin.Essentials were natively integrated, so you can get all the benefits along with improvements for the DeviceDisplay
class.
Responsive Layout
In the ContentPage we attach an event handler to catch up screen size changes occurring to that particular page, so we render the proper Flyout behavior based on the screen size
protected override void OnAppearing()
{
base.OnAppearing();
SetFlyoutBehavior();
DeviceDisplay.MainDisplayInfoChanged += DeviceDisplay_MainDisplayInfoChanged;
}
private void DeviceDisplay_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
SetFlyoutBehavior();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
DeviceDisplay.MainDisplayInfoChanged -= DeviceDisplay_MainDisplayInfoChanged;
}
private void SetFlyoutBehavior()
{
// Get the screen points
double screenWidth = DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density;
Debug.WriteLine(screenWidth);
// sizes obtained from the official bootstrap CSS
switch (screenWidth)
{
case <= 576:
Shell.Current.FlyoutBehavior = FlyoutBehavior.Flyout;
Shell.Current.FlyoutIsPresented = false;
break;
case > 576:
Shell.Current.FlyoutBehavior = FlyoutBehavior.Locked;
Shell.Current.FlyoutIsPresented = true;
break;
}
}
Conclusion
This is just a sample of how to set the Flyout from App Shell to be locked or hidden based on the screen size, however, you can use it to accommodate other areas of the screen layout.
I hope this helps others to create their own responsive layouts in .NET MAUI.
Top comments (1)
Thank you very much for sharing this useful blog post. I was able to do the same thing for .NET MAUI WebView to set the WidthRequest.
This website also helps you to decide desired Width and Height
responsiveviewer.org/
Thank you again,