Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Improving robustness when using MAUI Shell navigation
I'm currently learning dotnet MAUI, particularly using Shell navigation, and am wondering what the best way to go about it is when using query parameters. For example, take this from the documentation
public class MonkeyDetailViewModel : IQueryAttributable, INotifyPropertyChanged
{
public Animal Monkey { get; private set; }
public void ApplyQueryAttributes(IDictionary<string, object> query)
{
Monkey = query["Monkey"] as Animal;
OnPropertyChanged("Monkey");
}
...
}
To navigate to a page, you can use the GoToAsync method with a Dictionary or ShellNavigationQueryParameters object.
var navigationParameter = new ShellNavigationQueryParameters
{
{ "Monkey", animal }
};
await Shell.Current.GoToAsync($"monkeydetail", navigationParameter);
However, this is error prone and fragile; if you happen to mistype or forget one of the query parameters, or if the required parameters change and you didn't update every call site, there is no compile-time error, and it will silently break. Is there any common way of making Shell navigation more strongly typed or otherwise less error prone, ideally being caught at compile time?
1 answer
Take the following with a grain of salt, as I don't know MAUI. There might be some better approach baked in.
At mimimum, I'd be making that param name a const string somewhere. Maybe as far defining extension methods upon IDictionary<string, object>, for each different param. Something like...
public static class QueryAttributeExtensions
{
public const string MonkeyAttributeName
= "monkey";
extension (IDictionary<string, object> queryAttributes)
{
public Monkey GetMonkey()
=> (Monkey)queryAttributes[MonkeyAttributeName];
public void SetMonkey(Monkey monkey)
=> queryAttributes[MonkeyAttributeName] = monkey;
}
}
But really, if there's no baked-in way to do type-safe navigation in this system, I'd be inclined to just build my own system. Maybe something like...
public class NavigationRequest<T>
where T : IViewModel
{
public required T Target { get; init; }
}
With this, the target VM to navigate to has to be constructed by the VM issuing the request, so all the parameters can be nice and type-safe. Then the NavigationRequest<> object can just be bubbled up in the view layer to wherever navigation happens, and all the navigator has to do is lookup the appropriate View layer control for displaying the desired ViewModel type.

0 comment threads