Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 10 Remote Data

This works fine provided you have a good network connection. The moment you have a slow connection or even no connection, you will notice that things don’t load quite as expected. In fact, you will likely observe a crash. You knew this could happen based on your earlier investigation into the things you need to consider when handling remote data. Let’s now apply some techniques to handle these scenarios.

Adding Some State

The first thing you want to do is to consider the different possible states that your process can be in. There are three key scenarios that you need to handle and provide visual feedback to your users on:

\1.\ The widget is loading the data.

\2.\ The widget has the data.

\3.\ The widget has encountered an issue loading the data.

Let’s handle these three scenarios.

First, create an enum that will represent the above scenarios.

public enum State

{

None = 0, Loading = 1, Loaded = 2, Error = 3

}

You also want to modify your loading code in the view model to make use of this new State.

private async Task LoadWeatherForecast()

{

319

Chapter 10 Remote Data

try

{

State = State.Loading;

var forecast = await weatherForecastService.GetForecast (20.798363, -156.331924);

Temperature = forecast.Current.Temperature; Weather = forecast.Current.Weather.First().Main; IconUrl = forecast.Current.Weather.First().IconUrl;

State = State.Loaded;

}

catch (Exception ex)

{

State = State.Error;

}

}

And you also need to add the State property and backing field.

private State state;

public State State

{

get => state;

set => SetProperty(ref state, value);

}

Converting the State to UI

This section may well deserve a more prominent setting; however, to allow the content to flow through this book, I opted to only expose parts based on the context of the topics you are learning as you build your application.

320

Chapter 10 Remote Data

Quite often in .NET MAUI there are scenarios where you wish to bind a piece of data to the UI but that data type does not match the desired type in the UI. To avoid having to add additional properties and potentially adding view-related information into your view models, you can make use of a concept called converters. A converter enables you to define how a specific data type can be converted from its type to another type. I always find the best way to cover something like this is to see it in action so let’s create a converter to convert from your new State enum above into a bool value ready for binding to the IsVisible property in your view.

Add a new folder and call it Converters and then add a new class file and call it IsEqualToStateConverter.cs and then you can add the following contents:

using System.Globalization; using WidgetBoard.ViewModels;

namespace WidgetBoard.Converters;

public class IsEqualToStateConverter : IValueConverter

{

public State State { get; set; }

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

{

if (value is State state)

{

return state == State;

}

return value;

}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

321

Chapter 10 Remote Data

{

throw new NotImplementedException();

}

}

The IValueConverter interface allows you to define how a value passed in can be converted. Implementations of this interface are for use within a binding using the Converter property.

Displaying the Loading State

It is worth noting that at times data can be loaded very quickly and the act of showing a spinner can provide a negative experience if it flashes very quickly. Of course, it is impossible to know which calls will take longer than others as there are so many factors which can affect the network. At times like this, I like to make sure that there is always a minimum amount of time that you display the spinner so that there isn’t this weird flash to the user.

<?xml version="1.0" encoding="utf-8" ?> <ContentView

xmlns="http://schemas.microsoft.com/dotnet/2021/maui"

xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewmodels="clr-namespace:WidgetBoard.ViewModels" xmlns:converters="clr-namespace:WidgetBoard.Converters" x:Class="WidgetBoard.Views.WeatherWidgetView" x:DataType="viewmodels:WeatherWidgetViewModel">

<ContentView.Resources>

<converters:IsEqualToStateConverter

x:Key="IsLoadingConverter" State="Loading" />

</ContentView.Resources>

322