Skip to content
This repository has been archived by the owner on Jun 1, 2024. It is now read-only.

Commit

Permalink
Flutter - Adds Portuguese translation for network folder (#870)
Browse files Browse the repository at this point in the history
* Translates flutter network folder

Signed-off-by: Hector Custódio <hector.custodio@zup.com.br>

* Removes typo, adjusts text

Signed-off-by: Hector Custódio <hector.custodio@zup.com.br>
  • Loading branch information
hectorcustodiozup committed Mar 10, 2022
1 parent 4aa7430 commit b793a8f
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 63 deletions.
2 changes: 1 addition & 1 deletion content/en/flutter/network/view-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class MyViewClient extends DefaultViewClient {
}
```

Above we implemented a very simple logic that will store every fetch result into the disk using the lib `sharedPreferences`. This is a very dumb implementation, because this cache would never expire, but the objective here is just to show how such feature could be implemented using the ViewClient.
Above we implemented a very simple logic that will store every fetch result into the disk using the lib `sharedPreferences`. This was done exclusively for demonstration, because this cache would never expire, but the objective here is just to show how such feature could be implemented using the ViewClient.

We extended the DefaultViewClient to take advantage of everything that is already implemented there, like the pre-fetch behavior. But you can also write it from the ground up by extending `ViewClient`, which is just an interface.

Expand Down
4 changes: 2 additions & 2 deletions content/pt/flutter/network/_index.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Network
title: Rede
weight: 1
description: In this section, you will learn how to setup network in Beagle Flutter.
description: Nesta seção, você aprende como configurar a parte de rede no Beagle Flutter.
---
44 changes: 22 additions & 22 deletions content/pt/flutter/network/http-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,48 @@
title: HTTP client
weight: 3
description: >-
In this section, you will find information on how to setup an HTTP client in Beagle Flutter.
Nesta seção, você encontra mais informações sobre como configurar um cliente HTTP no Beagle Flutter.
---

---

# Introduction
The HttpClient is responsible for sending all requests made by Beagle. Beagle already uses a default implementation of the HttpClient which makes the requests as they come from the JSON (DefaultHttpClient). If you need to change the default behavior, you must implement your own HttpClient, i.e., you must implement the following interface:
# Introdução
O "HttpClient" é responsável por enviar todas as requisições feitas pelo Beagle. O Beagle já tem uma implementação padrão deste serviço. Se você precisar mudar este comportamento, é necessário implementar seu próprio HttpClient usando a interface a seguir:

```dart
abstract class HttpClient {
Future<Response> sendRequest(BeagleRequest req);
}
```

In the **sendRequest** method, you can create the rules for your network layer. You can add headers to your requests, change the HTTP method, request body, response, run cryptography, etc.
No método **sendRequest**, você cria regras para a camada de redes. Pode adicionar "headers", mudar o método de requisição, adicionar o corpo da requisição, resposta, colocar criptografia, etc.

The `sendRequest` receives a single parameter of type `BeagleRequest` and returns an object of type `Response`. See below what each of these types does:
O `sendRequest` recebe um parâmetro único do tipo `BeagleRequest` e retorna um objeto do tipo `Response`. Veja abaixo o que cada um destes faz:

# BeagleRequest
It's the class for configuring HTTP requests.
É a classe para configurar as requisições HTTP.

| **Attribute** | **Type** | **Required** | **Definition** |
| :--- | :--- | :---: | :--- |
| url | String || The endpoint that returns the server driven UI (view) you wish to display. |
| method | BeagleHttpMethod | | Enum class that defines the [HTTP operation/verb](https://www.restapitutorial.com/lessons/httpmethods.html). The default value is `GET`. |
| headers | Map<String, String> | | Used when you need to send data via HTTP headers. |
| body | String | | Used when you need to send a HTTP messages as body data. |
| url | String || O endpoint que retorna a tela "server-driven". |
| method | BeagleHttpMethod | | Classe enum que define a [Operação HTTP](https://www.restapitutorial.com/lessons/httpmethods.html). O valor padrão é `GET`. |
| headers | Map<String, String> | | Usado ao enviar dados por HTTP headers. |
| body | String | | Usado para enviar mensagens HTTP como corpo da requisição. |

# Response
It's used to return the data retrieved by the request.
# Resposta
É usado para acessar a resposta da requisição.

| **Attribute** | **Type** | **Required** | **Definition** |
| :--- | :--- | :---: | :--- |
| status | int || Status code of the response. |
| body | String || Body of the response. |
| headers | Map<String, String> || Headers of the response. |
| bodyBytes | Uint8List || Body, in bytes, of the request. |
| status | int || Código do status da resposta. |
| body | String || Corpo da resposta. |
| headers | Map<String, String> || "Headers" da resposta. |
| bodyBytes | Uint8List || Corpo, em bytes, da requisição. |

The response also has a method `toJson` which returns a String with the `status`, `body` and `headers` encoded.
A resposta também possui um método `toJson` que retorna uma String com o `status`, `corpo` e `headers` codificado.

# Create a custom HTTP client
See below an example of a custom HttpClient that adds the header `platform` to every `GET` request:
# Criar um HTTP client customizado
Veja abaixo um examplo de customização do `HttpClient` que adiciona um header `platform` para toda requisição `GET`.

```dart
import 'dart:async';
Expand All @@ -68,11 +68,11 @@ class MyHttpClient implements HttpClient {
}
}
```
Este exemplo mostra de forma simplificada como implementar essa funcionalidade. Seria mais simples em alguns casos extender o `DefaultHttpClient`, que já contém a maioria das implementações. Mesmo assim, na maioria dos casos, toda a implementação deve ser feita para cobrir cada caso de uso específico quando necessário.

This is a very simple example and, to implement this, it would be easier to extend the `DefaultHttpClient` instead, which already contains most of the implementation. Nonetheless, in most scenarios, the entire implementation will need to be replaced, hence the example.
# Use um HTTP client customizado
Para usar seu novo "client", passe para o BeagleService na inicialização `BeagleSdk.init`. Veja o exemplo abaixo:

# Use a custom HTTP client
To use your client, pass it in the Beagle initialization method `BeagleSdk.init` just like the example below:
```dart
final beagleService = BeagleService(
httpClient: const MyHttpClient(),
Expand Down
23 changes: 12 additions & 11 deletions content/pt/flutter/network/image-downloader.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@
title: Image Downloader
weight: 3
description: >-
In this section, you will find information on how to use and configure the Image Downloader in Beagle Flutter.
Nesta seção, você encontra informações de como configurar e usar o Image Downloader no Beagle Flutter.
---

---

# Introduction
The image downloader handles how remote images are downloaded. It is supposed to be used by any Image component and our intent when letting this be a configurable service is so that any additional logic to download images can be easily implemented without the need of replacing the image component of the library of components being used.
# Introdução
O "ImageDownloader" lida com como as imagens remotas são baixadas. Ele deve ser usado por qualquer componente de Imagem e nossa intenção ao deixar este ser um serviço configurável é que qualquer lógica adicional para download de imagens possa ser facilmente implementada sem a necessidade de substituir o componente de imagem da biblioteca de componentes que está sendo usada.

Similar to the ViewClient, the ImageDownloader is also responsible for creating requests for the HttpClient and processing its responses, the only difference is that the ViewClient does it for server driven views (JSONs) and the ImageDownloader does it for images.
Semelhante ao "ViewClient", o "ImageDownloader" também é responsável por criar solicitações para o "HttpClient" e processar suas respostas, a única diferença é que o "ViewClient" faz isso para visualizações orientadas a servidor (JSONs) e o "ImageDownloader" faz isso para imagens.

The default ImageDownloader is very simple, it just creates the request, pass it to the HttpClient and transform the response into a `Uint8List`. An interesting application of a custom ImageDownloader would be caching. The custom ImageDownloader would save the images in disk and use the stored value instead of making the request to the HttpClient whenever possible.
O "ImageDownloader" padrão é muito simples, apenas cria a requisição, passa para o HttpClient e transforma a resposta em um `Uint8List`. Uma aplicação interessante de um "ImageDownloader" personalizado seria o cache. O "ImageDownloader" personalizado salvaria as imagens em disco e usaria o valor armazenado em vez de fazer a solicitação ao "HttpClient" sempre que possível.

Here's the ImageDownloader interface:
Aqui está a interface do `ImageDownloader`:

```dart
abstract class BeagleImageDownloader {
Future<Uint8List> downloadImage(String url);
}
```

The `downloadImage` method takes as a parameter the image url and returns a `Future<Uint8List>` as the representation of the downloaded image.
O método `downloadImage` recebe como parâmetro a url da imagem e retorna um `Future<Uint8List>` como representação da imagem baixada.

# Create a custom image downloader
To create your own image downloader, you need to implement the `downloadImage` method, see a simplified version of the default implementation:
# Criando um ImageDownloader customizado
Para criar seu próprio image downloades, você precisa implementar o método `downloadImage`, veja uma versão simplificada da versão padrão:

```dart
class DefaultBeagleImageDownloader implements BeagleImageDownloader {
Expand Down Expand Up @@ -54,8 +54,9 @@ class DefaultBeagleImageDownloader implements BeagleImageDownloader {
}
```

# Use the custom image downloader
To use your image downloader, pass it in the BeagleService just like the example below:
# Usando o ImageDownloader customizado
Para usaro o ImageDownloader, apenas passe para a propriedade equivalente no BeagleService. Veja:

```dart
final beagleService = BeagleService(
imageDownloader: MyImageDownloader(),
Expand Down
26 changes: 13 additions & 13 deletions content/pt/flutter/network/localhost.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
---
title: Accessing the localhost
title: Acessando o localhost
weight: 3
description: >-
In this section, you will find information on how to refer to the localhost on Beagle Flutter.
Nesta seção, você encontra informações de como acessar o localhost pelo Beagle Flutter.
---

---

## Running a backend in the localhost
In the previous steps, the `baseUrl` used was `https://usebeagle.io/start`, but this is just an example and you will need to replace this address by your own backend.
## Rodar um backend no localhost
Nas documentações anteriores, o `baseUrl` usado foi o `https://usebeagle.io/start`, mas foi apenas apra exemplificar e em aplicações reais você usaria sua própria URL.

### Making HTTP requests
By default, both Android and iOS will make only HTTPS (secured) requests. To change this behavior, follow the steps below:
### Fazendo requisições HTTP
Por padrão, ambos Android e iOS fazem apenas requisições seguras com o protocolo HTTPS. Para mudar este comportamento, siga os passos a seguir:

#### Android
1. Open `android/app/src/main/AndroidManifest.xml`
2. Place the rule `android:usesCleartextTraffic="true"` in `<application>` tag:
1. Abra `android/app/src/main/AndroidManifest.xml`
2. Adicione a regra `android:usesCleartextTraffic="true"` na `<application>` tag:

```xml
<application
Expand All @@ -29,8 +29,8 @@ By default, both Android and iOS will make only HTTPS (secured) requests. To cha
```

#### iOS
1. Open `ios/{project_name}/info.plist`
2. Make sure the configuration for `NSAppTransportSecurity` is the following one:
1. Abra `ios/{project_name}/info.plist`
2. Veja se a configuração `NSAppTransportSecurity` tem o seguinte valor:

```xml
<key>NSAppTransportSecurity</key>
Expand All @@ -47,13 +47,13 @@ By default, both Android and iOS will make only HTTPS (secured) requests. To cha
```

{{% alert color="warning" %}}
This configuration is not recommended for production builds. HTTP requests should be blocked while not in development.
Esta configuração é apenas para testes e não deveser usada em builds finais de produção.
{{% /alert %}}

### localhost vs 10.0.2.2
When running your backend in the localhost, iOS works with the address `localhost`, however the Android emulator does not.
Ao rodar o backend no localhost, o iOS funciona no endereço `localhost`, no entando o emulador do Android não funciona assim.

To access the localhost in the Android emulator, you need to use the **IP `10.0.2.2`.** To solve this problem, you can use Flutter's `Platform` to decide what address to use. See the example below:
Para acessar o localhost no emulador do Android, você precisa usar o **IP `10.0.2.2`.**. No Flutter se você quiser alterar este comportamento basta seguir o exemplo abaixo e decidir qual endereço usar:

```dart
final localhost = Platform.isAndroid ? '10.0.2.2' : 'localhost';
Expand Down
28 changes: 14 additions & 14 deletions content/pt/flutter/network/view-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@
title: View client
weight: 3
description: >-
In this section, you will find information on how to setup a ViewClient in Beagle Flutter.
Nesta seção, você encontra informações de como configurar uma ViewClient no BeagleFlutter.
---

---

# Introduction
Similar to the HttpClient, but more specific. While the hHttpClient is responsible for managing every request (views, json data, images, etc), the ViewClient is only responsible for fetching views, i.e. server driven pages.
# Introdução

The ViewClient creates the BeagleRequest that is sent to the HttpClient. The default implementation does two things:
1. creates the BeagleRequest according to what has been requested by its caller (normally, the navigator);
2. when the response arrives from the httpClient, it checks for navigation actions where `preFetch` is `true` and, asynchronously, pre-fetches their results.
Semelhante ao HttpClient, mas mais específico. Enquanto o hHttpClient é responsável por gerenciar todas as solicitações ("views", dados json, imagens, etc), o ViewClient é responsável apenas por buscar "views", ou seja, páginas "server-driven".

It does nothing other than this, and this might be enough for most applications. But some applications may need extra behavior when fetching views, and this is the place where it should be implemented.
O ViewClient cria o BeagleRequest que é enviado ao HttpClient. A implementação padrão faz duas coisas:
1. cria o BeagleRequest de acordo com o que foi solicitado pelo cliente (normalmente, o navegador);
2. quando a resposta chega do httpClient, ele verifica as ações de navegação onde `preFetch` é `true` e, de forma assíncrona, pré-busca seus resultados.

# Creating a new ViewClient
Ele não faz nada além disso, e isso pode ser suficiente para a maioria dos aplicativos. Mas alguns aplicativos podem precisar de comportamento extra ao buscar "views", e este é o lugar onde isso deve ser implementado.

A good example is caching. Let's say we want to locally store a view so when Beagle calls `viewClient.fetch` again, it returns the cached result instead of calling the hHttpClient. To do this, we can implement a new ViewClient that has storage and implements `fetch` as follows:
# Criando uma nova ViewClient

Um bom exemplo é o "caching". Digamos que precisamos guardar uma view localmente, assim quando o Beagle chamar `viewClient.fetch` novamente, o resultado do cache será retornado ao invés de chamar o HttpClient novamente. O exemplo a seguir mostra como fazer isso ao criar uma nova `ViewClient` que tem um "storage" e implementa o `fetch`:

```dart
import 'dart:convert';
Expand Down Expand Up @@ -46,13 +47,12 @@ class MyViewClient extends DefaultViewClient {
}
}
```
A implementação acima mosta uma lógica bem simples usando a biblioteca `sharedPreferences`, em um cenário real ela nem seria necessária, mas é um ótimo exemplo para mostrar de forma direta e rápida como o ViewClient customizado pode ser feito.

Above we implemented a very simple logic that will store every fetch result into the disk using the lib `sharedPreferences`. This is a very dumb implementation, because this cache would never expire, but the objective here is just to show how such feature could be implemented using the ViewClient.

We extended the DefaultViewClient to take advantage of everything that is already implemented there, like the pre-fetch behavior. But you can also write it from the ground up by extending `ViewClient`, which is just an interface.
Nós extendemos o `DefaultViewClient` para tirar vantagem de tudo que já está implementado. como por exemplo, o pre-fetch. Você pode também se preferir ou se precisar extender diretamento a `ViewClient` e implementar toda a interface do zero.

# Registering the new ViewClient
After creating your custom ViewClient, you just need to pass it to your BeagleService instance:
# Registrando o novo ViewClient
Após criar o seu ViewClient customizado, basta apenas passá-la para a instância do BeagleService:

```dart
final baseUrl = 'https://my-bff.com';
Expand Down

0 comments on commit b793a8f

Please sign in to comment.