A time ago Steven Thewissen created a great plugin called StateSquid which allowed displaying a specific view when a page is in a specific state. It has evolved and now it’s part of the Xamarin Community Toolkit.
In this article, I’m going to show you how to use and integrate it to load data into your collections.
Let’s start with the basics
First, install the XamarinCommunityToolkit Package. After that, you will be able to use the StateLayout.
This control allows you to have different views according to a specific state. The view will change automatically according to the current state. For example:
There’s a list of pre-defined states that you can use (Loading, Error, Success, Saving, etc), but you can also define your own custom state:
Some extra functionalities are:
StateToBooleanConverter
It will return true if the specified state matches the bound state. To use it you have to pass the state you want to check as the ConverterParameter. For example:
AnimateStateChanges
Indicates if you want an animated transition when switching between states.
How to use it with Collections
1. Create your Collection
Add your CollectionView with your custom template UI. Let’s have the following UI as our example:
CollectionView should be inside a layout, where we will specify the CurrentState.
2. Create an EmptyTemplate
This template will define how the view looks without data. In order to create it we can use BoxViews with grey color and make it look like this:
If we want an animation to make it look as if it was loading, you can add a view called SkeletonView (created by Steven) to your project.
This view is a BoxView with animation, so you can use this view instead of the BoxViews. Also, you can set extra properties to customize it:
3. Set the EmptyTemplate to the StateView
The StateView supports setting a template and also you can specify how many times you want to repeat this view. Is important to mention that this is not part of the CollectionView, it is a separate view that will be visible for a specific state.
Set the template to the StateView:
The full code looks like this:
Check the full XAML here.
Using it for lazy loading
We can use StateView for data lazy loading, I took this idea from the MVP Sample, which has a great sample for lazy loading.
We will use the Footer of the CollectionView, and make it visible according to if LoadingMoreItem is true. Also, use a BindableLayout.ItemTemplate to set the EmptyUserTemplate that we used before. This will simulate adding a random element by using a Static ItemSource.
That’s all for now, you can check the full sample here.
Happy coding!