Neste artigo veremos como criar uma página de Login com MVVM e usar a base de dados Firebase para armazenar as credenciais do usuário. |
Continuando a segunda parte do artigo vamos criar as entidades para representar as categorias e os produtos bem como definir métodos para incluir as categorias e os produtos no Firebase.
Na aula anterior vimos como registrar um usuário e fazer login lendo dados do Firebase. Podemos também incluir dados manualmente no Firebase mas para tornar o processo menos sujeito a erros vamos definir uma lógica para incluir os dados das categorias e produtos que iremos usar.
Criando as classes para categorias e produtos
Vamos criar as classes para representar as categorias e os produtos que iremos tratar em nossa aplicação.
Na pasta Models do projeto crie o arquivo Category.cs e defina o código a seguir:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryPoster { get; set; }
public string ImageUrl { get; set; }
}
|
Agora na pasta Helpers crie a classes AddCategoryData com o código abaixo:
using Firebase.Database;
using Firebase.Database.Query;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
using XF_LancheApp.Models;
namespace XF_LancheApp.Helpers
{
public class AddCategoryData
{
public List<Category> Categories { get; set; }
FirebaseClient client;
public AddCategoryData()
{
client = new FirebaseClient("https://xamarinfirestore-bc526.firebaseio.com/");
Categories = new List<Category>()
{
new Category()
{
CategoryId = 1,
CategoryName="Lanches",
CategoryPoster = "MainBurger",
ImageUrl = "Lanches.png"
},
new Category()
{
CategoryId = 2,
CategoryName="Pizzas",
CategoryPoster = "MainPizza",
ImageUrl = "Pizza.png"
},
new Category()
{
CategoryId = 3,
CategoryName="Sobremesas",
CategoryPoster = "MainSobremessas",
ImageUrl = "Sobremessas.png"
},
new Category()
{
CategoryId = 4,
CategoryName= "Naturais",
CategoryPoster = "MainNatural",
ImageUrl = "Natural.png"
},
};
}
public async Task AddCategoryAsync()
{
try
{
foreach (var category in Categories)
{
await client.Child("Categories").PostAsync(new Category()
{
CategoryId = category.CategoryId,
CategoryName = category.CategoryName,
CategoryPoster = category.CategoryPoster,
ImageUrl = category.ImageUrl
});
}
}
catch (System.Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Erro", ex.Message, "Ok");
}
}
}
}
|
Este código define uma lista de categorias com 4 categorias e a seguir inclui essas categorias no Firebase criando a coleção Categories e as propriedades que definimos na entidade Category.
Novamente na pasta Models defina a classe Product :
public class Product
{
public int ProductId { get; set; }
public string ImageUrl { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Rating { get; set; }
public string RatingDetail { get; set; }
public string HomeSelected { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
}
|
Seguindo a mesma lógica vamos criar a classe AddProductData na pasta Helpers:
using Firebase.Database;
using Firebase.Database.Query;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
using XF_LancheApp.Models;
namespace XF_LancheApp.Helpers
{
class AddProductData
{
public List<Product> Products { get; set; }
FirebaseClient client;
public AddProductData()
{
client = new FirebaseClient("https://xamarinfirestore-bc526.firebaseio.com/");
Products = new List<Product>()
{
new Product()
{
ProductId = 1,
ImageUrl= "cheeseburger1.jpg",
Name = "Cheese Burger",
Description = "Cheese burger com presunto,queijo e tomate",
Rating = " 4.6",
RatingDetail = "(90 avaliações)",
HomeSelected = "EmptyHeart",
Price = 12.50M,
CategoryId = 1
},
new Product()
{
ProductId = 2,
ImageUrl= "cheesesalada1.jpg",
Name = "Cheese Salada",
Description = "Cheese salada com presento,queijo,tomate,alface e cebola",
Rating = " 4.5",
RatingDetail = "(100 avaliações)",
HomeSelected = "EmptyHeart",
Price = 14.50M,
CategoryId = 1
},
new Product()
{
ProductId = 3,
ImageUrl= "pudim1.jpg",
Name = "Pudim de leite",
Description = "Pudim de leite com calda de ameixa",
Rating = " 4.8",
RatingDetail = "(120 avaliações)",
HomeSelected = "CompleteHeart",
Price = 12,
CategoryId = 3
},
new Product()
{
ProductId = 4,
ImageUrl= "Atum1.jpg",
Name = "Lanche de Atum Natural",
Description = "Pão integral, atum, maionese, alface e tomate",
Rating = " 4.7",
RatingDetail = "(110 avaliações)",
HomeSelected = "EmptyHeart",
Price = 15.90M,
CategoryId = 4
},
new Product()
{
ProductId = 5,
ImageUrl= "pizza1.jpg",
Name = "Pizza de mussarela",
Description = "Fatia de pizza de mussarela",
Rating = " 4.4",
RatingDetail = "(70 avaliações)",
HomeSelected = "EmptyHeart",
Price = 6.50M,
CategoryId = 3
},
};
}
public async Task AddProductAsync()
{
try
{
foreach (var item in Products)
{
await client.Child("Products").PostAsync(new Product()
{
ProductId = item.ProductId,
Name = item.Name,
Description = item.Description,
ImageUrl = item.ImageUrl,
CategoryId = item.CategoryId,
HomeSelected = item.HomeSelected,
Price = item.Price,
Rating = item.Rating,
RatingDetail = item.RatingDetail
});
}
}
catch (System.Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Erro", ex.Message, "Ok");
}
}
}
}
|
Este código vai incluir os produtos definidos na coleção Products criada no Firebase.
Agora vamos criar uma página chamada SettingsPage.xaml na pasta Views onde vamos usar essas classes.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="XF_LancheApp.Views.SettingsPage"
Title="Gerenciar Categorias e Produtos">
<ContentPage.Content>
<Frame Padding="10" CornerRadius="20" BackgroundColor="Aquamarine" >
<StackLayout>
<Label Text="Incluir Categorias e Produtos no Firebase"
TextColor="Indigo" FontSize="Medium"/>
<Button Text="Incluir Categorias"
x:Name="btnCategorias"
Clicked="btnCategorias_Clicked"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Button Text="Incluir Produtos"
x:Name="btnProdutos"
Clicked="btnProdutos_Clicked"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</Frame>
</ContentPage.Content>
</ContentPage>
|
E no arquivo Settings.xaml.cs defina o código que vai tratar o evento de cada botão:
...
private async void btnProdutos_Clicked(object sender, EventArgs e)
{
var novosProdutos = new AddProductData();
await novosProdutos.AddProductAsync();
}
private async void btnCategorias_Clicked(object sender, EventArgs e)
{
var novasCategorias = new AddCategoryData();
await novasCategorias.AddCategoryAsync();
}
...
|
Agora vamos ajustar a MainPage para chamar a página de login e a página para incluir categorias e produtos.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="XF_LancheApp.MainPage"
Title="Menu">
<Frame Padding="10" CornerRadius="20" BackgroundColor="Aquamarine" >
<StackLayout>
<Label Text="Menu de Opções"
TextColor="Indigo" FontSize="Medium"/>
<Button Text="Gerenciar Categorias e Produtos"
x:Name="btnGerencia"
Clicked="btnGerencia_Clicked"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Button Text="Fazer o Login no Firebase"
x:Name="btnLogin"
Clicked="btnLogin_Clicked"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</Frame>
</ContentPage>
|
No arquivo MainPage.xaml.cs inclua o código para tratar os eventos de cada botão:
...
private void btnLogin_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new LoginView());
}
private void btnGerencia_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new SettingsPage());
}
...
|
Finalmente altere o código da classe App para chamar a MainPage:
... public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); } ... |
Agora executando o projeto podemos chamar a página para gerenciar categorias e produtos.
Ao clicar no botão para incluir as categorias e a seguir os produtos veremos os dados incluídos no Firebase nas coleções Categories e Products conforme mostrado a seguir:
A seguir vamos implementar exibição dos produtos.
Pegue o código do projeto compartilhado aqui: XF_LancheApp2.zip
"E se abrires a
tua alma ao faminto, e fartares a alma aflita; então a tua luz nascerá nas
trevas, e a tua escuridão será como o meio-dia."
Isaías 58:10
Referências:
NET - Apresentando o padrão Model-View-ViewModel -
Xamarin Forms - MVVM - Macoratti.net
NET - O padrão MVVM (Model-View-ViewModel) revisitado
Xamarin Forms - MVVM - A interface ICommand -
Padrão de Projeto - Aprendendo o padrão MVVM ...