From 5107876a809c385e9095009d79cea47cf5d4f182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hector=20Cust=C3=B3dio?= Date: Thu, 10 Mar 2022 10:58:08 -0300 Subject: [PATCH] Translates navigation folder for flutter docs (#869) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Hector Custódio --- content/pt/flutter/navigation/_index.md | 4 +- .../navigation/navigation-controllers.md | 68 +++++++++++-------- .../flutter/navigation/open-beagle-screen.md | 64 +++++++++-------- 3 files changed, 78 insertions(+), 58 deletions(-) diff --git a/content/pt/flutter/navigation/_index.md b/content/pt/flutter/navigation/_index.md index ff7d8cde5..77ea4a510 100644 --- a/content/pt/flutter/navigation/_index.md +++ b/content/pt/flutter/navigation/_index.md @@ -1,5 +1,5 @@ --- -title: Navigation +title: Navegação weight: 1 -description: In this section, you will learn how to use Beagle Flutter's navigation system. +description: Nesta seção você aprende como usar o sistema de navegação do Beagle Flutter. --- diff --git a/content/pt/flutter/navigation/navigation-controllers.md b/content/pt/flutter/navigation/navigation-controllers.md index fe4fb2cbb..c95ad4cea 100644 --- a/content/pt/flutter/navigation/navigation-controllers.md +++ b/content/pt/flutter/navigation/navigation-controllers.md @@ -2,46 +2,51 @@ title: Navigation controllers weight: 3 description: >- - In this section, you will find information on how to control the navigation feedback. + Nesta seção você aprende como controlar e tratar as respostas de navegação. --- --- -# Introduction -The navigation controllers are responsible for implementing the behavior of the loading, error and success events of the navigation between Beagle pages. +# Introdução +Os controles de navegação são responsáveis por implementar o comportamento de eventos de carregamento, erro e sucesso das navegações entre páginas Beagle. -If not set, Beagle will use the `DefaultNavigationController`, which implements the following behavior: +Se não for implementada será usado o `DefaultNavigationController` que implementa as seguintes funções: -- **onLoading**: render a Beagle UI tree with a single component called `custom:loading`. -- **onError**: render a Beagle UI tree with a single component called `custom:error`. -- **onSuccess**: render a Beagle UI tree with the UI tree returned from the backend. +- **onLoading**: renderiza uma árvore Beagle UI com um único componente `custom:loading`. +- **onError**: renderiza uma árvore Beagle UI com um único componente `custom:error`. +- **onSuccess**: renderiza uma árvore Beagle UI com a árvore de resposta do sucesso da requisição ao backend. -This behavior can be customized by implementing your own NavigationController. You can have multiple navigation controllers in a single application, one for each section, for instance. Beagle, from the backend, can tell which NavigationController must be used for the next set of screens. +Todos esses comportamentos podem ser personalizados implementando um `NavigationController` customizado. Você pode ter vários controladores de navegação em um único aplicativo, um para cada seção, se desejar. O framework Beagle presente em seu Frontend consegue definir qual `NavigationController` deve ser chamado para cada conjunto de telas que vem de um Backend. -When navigating to a new Stack (PushStack, ResetStack or ResetApplication), the backend can provide a controllerId to the navigation action and Beagle uses this id to find the corresponding NavigationController in the front-end. We can have an entire stack that has a totally different loading feedback, for example. +Ao navegar para um novo Stack (usando, por exemplo, ações como PushStack, ResetStack ou ResetApplication), o backend pode fornecer um `controllerId` para a ação de navegação que está sendo acionada (você só listará uma Id se quiser usar um controlador de navegação personalizado (`custom NavigationController`)). -# The NavigationController interface +O Beagle usará este id para encontrar o `NavigationController` correspondente no Front end de sua aplicação. Dessa forma, você poderá ter uma pilha inteira de telas com um feedback de carregamento diferente. + +# A interface NavigationController ## onLoading -Called whenever Beagle is loading a new view. It receives the following named parameters: +Chamado quando o Beagle esta prestes a carregar uma nova view. Recebe os seguintes parâmetros: + +- `BeagleView view`: a [BeagleView]({{< ref path="/flutter/other/beagle-view" lang="en" >}}) que renderiza a página server driven. +- `BuildContext context`: o "build context" atual. +- `Function completeNavigation`: uma função para completar a navegação. por exemplo, para adicionar a nova página ao "navigator" com o `BeagleWidget`. Você precisa chamá-la assim que for renderizada uma Beagle JSON. -- `BeagleView view`: the [BeagleView]({{< ref path="/flutter/other/beagle-view" lang="en" >}}) that renders this server driven UI. -- `BuildContext context`: the current build context. -- `Function completeNavigation`: a function to complete the navigation, i.e. to finally push the new page to the navigator with the `BeagleWidget`. You need to call it as soon as you want to render a Beagle JSON. For instance, if your loading feedback is to render a beagle component, you must call completeNavigation from withing the `onLoading` method. If you'll render a Beagle UI only in the success event, you don't need to ever call `completeNavigation` because it gets automatically called after `onSuccess`. +- `Function completeNavigation`: uma função para completar a navegação, ou seja, para finalmente enviar a nova página para o navegador com o `BeagleWidget`. Você precisa chamá-lo assim que quiser renderizar um Beagle JSON. Por exemplo, se seu feedback de carregamento é para renderizar um componente beagle, você deve chamar completeNavigation de dentro do método `onLoading`. Se você renderizar uma interface do usuário do Beagle apenas no evento de sucesso, não precisará chamar `completeNavigation` porque ele é chamado automaticamente após `onSuccess`. ## onError -Called whenever an error happens while loading a new view. It receives the same parameters as the `onLoading` method plus: +Chamada sempre que acontecer um erro enquanto é carregada uma nova "view". Recebe os mesmo parâmetros de `onLoading` além de: -- `dynamic error`: the error thrown while making the request or processing the response. -- `StackTrace stackTrace`: the stack trace linked to the error. -- `Future Function() retry`: a function that, when called, tries to fetch the view again. +- `dynamic error`:o erro recebido ao ser feita a requisição. +- `StackTrace stackTrace`: a pilha de erros relacionada ao erro da requisição. +- `Future Function() retry`: uma função, que quando chamada tenta refazer a requisição. ## onSuccess -Called whenever a view is successfully loaded. To render the view, this method must call `beagleView.getRenderer().doFullRenderer(screen)`. This renders the server driven screen to the current `BeagleView`. With the exception of `completeNavigation`, which will be called anyway by Beagle, the `onSuccess` method accepts the same parameters as the `onLoading` plus: -- `BeagleUIElement screen`: the server driven view recovered from the [ViewClient]({{< ref path="/flutter/network/view-client" lang="en" >}}). +Chamado sempre que uma "view" é carregada com sucesso. Para renderizar a "view", este método deve chamar `beagleView.getRenderer().doFullRenderer(screen)`. Isso renderiza a tela do servidor para o `BeagleView` atual. Com exceção de `completeNavigation`, que será chamado de qualquer maneira pelo Beagle, o método `onSuccess` aceita os mesmos parâmetros que o `onLoading` além de: -# Example +- `BeagleUIElement screen`: a server driven view recuperada do [ViewClient]({{< ref path="/flutter/network/view-client" lang="pt" >}}). + +# Examplo ```dart import 'package:flutter/material.dart'; @@ -129,16 +134,25 @@ class InYourFaceNavigationController implements NavigationController { } ``` -This is a terrible navigation controller with the sole purpose of demonstrating the feature. It shows a dialog every time a page starts loading. If an error happens, it replaces the loading dialog with an error dialog, which offers an option to retry. When the page is successfully loaded, it removes the loading dialog and renders the page. +Este é um controlador de navegação simples com o único objetivo de demonstrar esse recurso. +- Mostra uma caixa de diálogo sempre que uma página começa a carregar. Se ocorrer um erro. +- mostra uma caixa de diálogo de erro, que oferece a opção de tentar novamente. +- Quando a página é carregada com sucesso, ela renderiza a página. + +O único parâmetro não intuitivo no NavigationController é o `completeNavigation`. -The only non-intuitive parameter of the functions in a NavigationController is the `completeNavigation`. You can ignore this if you don't intend to show a Beagle UI before the success event. By default, i.e., if you don't call `completeNavigation`, the navigation with the Beagle structure of the new view will only happen after the success event. But, some navigation controllers, like the default one, uses the Beagle Structure to render the feedback. The DefaultNavigationController renders the Beagle component `custom:loading` whenever a loading event happens and because of this, it needs to call `completeNavigation` right on the method `onLoading`, so Beagle can properly render the component. +{{% alert color="success" %}} +Você pode ignorar isso se não pretender mostrar uma IU do Beagle antes do evento de sucesso. +{{% /alert %}} +Por padrão, se você não chamar a função `completeNavigation`, a navegação ocorrerá após o evento de sucesso. Mas, os controladores de navegação, como o padrão, usam a Estrutura Beagle para renderizar o feedback. +O `Default NavigationController` renderiza o componente `custom:loading` Beagle sempre que um evento de carregamento acontece e é por isso que ele precisa chamar a função `completeNavigation` dentro do método `onLoading`. Dessa forma, o Beagle pode renderizar corretamente o componente. -# Registering the navigation controllers -To provide all navigation controllers that can be used by the backend, you must create a map where the keys are the controller ids and the values are instances of `NavigationController`. +## Registrando os controladores de navegação +1. Você deve criar um mapa para lidar com todos os `controladores de navegação` que podem ser usados ​​pelo backend, onde as chaves são os *IDs do controlador* e os valores são instâncias de `NavigationController`. -To tell Beagle what NavigationController is the default, you need to set the property `defaultNavigationController`. The default navigation controller is used whenever no controllerId is provided or whenever no controller corresponding to the provided id is found. +2. Neste mapa você pode também definir um outro navegador que queira que seja usado como padrão. Para tal basta a propriedade `defaultNavigationController`. O controlador de navegação padrão é usado sempre que nenhum ``controllerId`` for fornecido ou sempre que nenhum controlador correspondente ao id fornecido for encontrado. -Suppose you have three navigation controllers: `inYourFace`, `secured` and `public`. `inYourFace` is the default, while `secured` and `public` are used in specific sections of the app and are referenced via the controllerId, from the backend. The configuration would be as following: +Se você tiver três controladores de navegação: `inYourFace`, `secured` e `public`. `inYourFace` é o padrão, enquanto `secured` e `public` serão usados ​​em seções específicas do aplicativo e referenciados via controllerIds, definidos em sua tela no backend. A configuração ficaria da seguinte forma: ```dart final beagleService = BeagleService( diff --git a/content/pt/flutter/navigation/open-beagle-screen.md b/content/pt/flutter/navigation/open-beagle-screen.md index 781bc91a1..a9784e896 100644 --- a/content/pt/flutter/navigation/open-beagle-screen.md +++ b/content/pt/flutter/navigation/open-beagle-screen.md @@ -1,38 +1,42 @@ --- -title: Start a Beagle flow +title: Iniciando um fluxo Beagle weight: 3 description: >- - In this section, you will find information on how to use openBeagleScreen function and what it does. + Nesta seção, você aprende como usar e para que serve a função openBeagleScreen. --- --- -# What is it? -The `openBeagleScreen` is the entrypoint to a Server Driven flow. When it's a called a new Page is pushed to the parent navigator containing the follow widget structure: +# O que é? + +O `openBeagleScreen` é a entrada para um fluxo server driven. Quando chamada uma nova página é adicionada ao navegador pai com a seguinte estrutura: - RootNavigator - StackNavigator - screenBuilder result -Both RootNavigator and StackNavigator are spawned by Beagle to deal with navigations within the server driven flow. The screenBuilder result is the Widget returned by the third parameter passed to `openBeagleScreen`. If no third parameter is passed, then the default screenBuilder is used, which just returns the BeagleWidget. The BeagleWidget is responsible for displaying the server driven content. +Ambos `RootNavigator` e `StackNavigator` são iniciados pelo Beagle para tratar navegações dentro do fluxo "server driven". O resultado do `screenBuilder` é o Widget retornado pelo terceiro parâmetro passado ao `openBeagleScreen`. Se não possuir o terceiro parâmetro, então, o resultado padrão do `screenBuilder` é usado, que é um `BeagleWidget`. O BeagleWidget é responsável por apresentar o conteúdo "server driven". + +Usamos dois navegadores (`RootNavigator` e `StackNavigator`) para que seja possível representar a estrutura de navegação do Beagle, que é composta de uma pilha de telas. Na implementação, o `RootNavigator` contém um `StackNavigator` para cada pilha e os `StackNavigators` contém as telas. -We use two navigators (RootNavigator and StackNavigator) so we're able to represent the Beagle Navigation structure, which is composed of a stack of stack of screens. In our implementation, the RootNavigator holds one StackNavigator for each stack and the StackNavigators hold the screens themselves. +## Primeiro parâmetro: route (obrigatório) -## 1st parameter: the route (required) -The first parameter of `openBeagleScreen` is a BeagleRoute. A BeagleRoute can be either a LocalView or a RemoteView. Normally, only remote views will be used, but for testing and some edge cases, it may be interesting to use a LocalView. Local views are JSONs that can be rendered without a fetch operation to the server. +O primeiro parâmetro do `openBeagleScreen` é o `BeagleRoute`. Um `BeagleRoute` pode ser uma `LocalView` ou uma `RemoteView`. Normalmente, apenas telas remotas são usadas, mas para testar alguns casos, é possível optar pela view local. `LocalView` é um JSON renderizado sem precisar de uma operação de requisição ao servidor. ### RemoteView -A RemoteView is instantiated with one required positional parameter (url) and many optional named parameters. For instance, `RemoteView('/home')` is used to fetch the view from the address `GET $baseUrl/home`. Any additional configuration can be passed with the following named parameters: +Uma `RemoteView` é instanciada com apenas um parâmetro obrigatório (url). Por exemplo, `RemoteView('/home')` faz uma requisição para o endereço `GET $baseUrl/home`. + +Existem outros parâmetros adicionais para um `RemoteView`. Veja a lista: -- **fallback:** Beagle UI tree to render if the request fails. -- **shouldPrefetch:** useless when used for the `openBeagleScreen` function. In other situations, it tells the ViewClient to fetch the view as soon as possible and not wait for an specific action to trigger it. -- **httpAdditionalData:** used to set up the request. An HttpAdditionalData contains: - - **method:** the HttpMethod, the default is GET. - - **headers:** a map from string to string with all headers to pass along with the request. - - **body:** the body of the request. This is only valid for POST requests. The value passed here must be serializable! +- **fallback:** árvore Beagle UI tree para renderizar em caso de erro. +- **shouldPrefetch:** diz ao ViewClient para carregar uma tela o mais rápido o possível e não esperar por ações específicas. Não funciona ao usar com o `openBeagleScreen`. +- **httpAdditionalData:** usado para configurar opções adicionais a requisição. Um HttpAdditionalData contém: + - **method:** o método HttpMethod, o padrão é GET. + - **headers:** um mapa de "strings" com todos os "headers" para serem enviados na requisição. + - **body:** o corpo da requisição. Apenas válido para requisições POST. O valor passado deve ser do tipo "serializable" ### LocalView -The LocalView is a wrapper for a BeagleUIElement. See the example below: +O `LocalView` encapsula uma `BeagleUIElement`. Veja o exemplo abaixo: ```dart final myLocalView = LocalView(BeagleUIElement({ @@ -45,11 +49,12 @@ final myLocalView = LocalView(BeagleUIElement({ })) ``` -## 2nd parameter: the context (required) -Well, there's not much to say here. Like everything in Flutter, we need the BuildContext to set everything up, so just pass the context received by your build method. +## Segundo parâmetro: o context (obrigatório) -## 3rd parameter: the screen builder (optional) -The `screenBuilder` is a function that tells Beagle how to create every screen that comes from Beagle and is the ideal place to implement a UI where part is server driven and part is not. See the example below: +Como toda funcionalidade no Beagle Flutter, precisamos de um BuildContext para configurar tudo, apenas repasse o contexto recebido pelo método build + +## Terceiro parâmetro: o screen builder (opcional) +O `screenBuilder`é uma função que diz ao Beagle como criar telas Beagle e o local ideal para implementar telas híbridas com e sem componentes server driven. Veja o exemplo: ```dart Widget screenBuilder(BeagleWidget beagleWidget, BuildContext context) => Column( @@ -67,18 +72,19 @@ Widget build(BuildContext context) => ElevatedButton( ); ``` -In the example above, instead of rendering pure server driven screens, Beagle will render UIs with content that mixes widgets that come from the frontend and the backend. In this case, it will place a header, a menu and then the server driven content. After the server driven content, it also places a footer. +No exemplo acima, ao invés de renderizar telas puramente "server driven", O Beagle irá renderizar UIs com conteúdos mistos do frontend e do backend. Foi renderizado, um componente "header", um "menu", os conteúdos "server-driven". Por fim, é renderizado um componente "footer". + +Se não for passado, o Beagle irá usar um "screen builder" padrão: `Widget screenBuilder(BeagleWidget beagleWidget, BuildContext context) => beagleWidget;` -When not provided, Beagle uses the default screen builder, which is: `Widget screenBuilder(BeagleWidget beagleWidget, BuildContext context) => beagleWidget;` +## Quarto parâmetro: o controllerId (optional) +O `controllerId` faz com que a primeira pilha de navegação não use o controlador de navegação padrão, mas sim aquele que corresponde ao id fornecido. Para saber mais sobre controladores de navegação, leia [artigo sobre controladores de navegação]({{< ref path="/flutter/navigation/navigation-controllers" lang="pt" >}}). -## 4th parameter: the controllerId (optional) -The `controllerId` makes it so the first navigation stack doesn't use the default navigation controller, but instead, the one that corresponds to the provided id. To know more about navigation controllers please read [article about navigation controllers]({{< ref path="/flutter/navigation/navigation-controllers" lang="en" >}}). -# What does it do? -The `openBeagleScreen` function pushes a new page to the parent navigator. This new page contains a RootNavigator which is initialized with a StackNavigator. The StackNavigator is initialized with a page that contains the BeagleWidget. +# Como funciona? +A função `openBeagleScreen` envia uma nova página para o navegador pai. Esta nova página contém um "RootNavigator" que é inicializado com um "StackNavigator". O "StackNavigator" é inicializado com uma página que contém o "BeagleWidget". -The stack navigator is responsible for calling the ViewClient service with the BeagleRoute passed as parameter to the function `openBeagleScreen`. When the loading starts, the StackNavigator calls the navigation controller method `onLoading`. The default navigation controller renders a BeagleUITree containing a single component called `custom:loading`. When the loading succeeds, the StackNavigator calls the method `onSuccess` of the navigation controller. The default navigation controller just renders the BeagleUIElement that has come from the backend. If an error happens, the StackNavigator calls `onError` on the navigation controller. The default navigation controller renders a BeagleUIElement containing the component `custom:error`. For more information on navigation controllers, check this [link]({{< ref path="/flutter/navigation/navigation-controllers" lang="en" >}}). +O navegador de pilha é responsável por chamar o serviço "ViewClient" com o "BeagleRoute" passado como parâmetro para a função `openBeagleScreen`. Quando o carregamento começa, o "StackNavigator" chama o método do controlador de navegação `onLoading`. O controlador de navegação padrão renderiza um "BeagleUITree" contendo um único componente chamado `custom:loading`. Quando o carregamento é bem-sucedido, o "StackNavigator" chama o método `onSuccess` do controlador de navegação. O controlador de navegação padrão apenas renderiza o "BeagleUIElement" que veio do "backend". Se ocorrer um erro, o "StackNavigator" chama `onError` no controlador de navegação. O controlador de navegação padrão renderiza um "BeagleUIElement" contendo o componente `custom:error`. Para obter mais informações sobre controladores de navegação, acesse este [link]({{< ref path="/flutter/navigation/navigation-controllers" lang="pt" >}}). -The stack navigator is also responsible for instantiating the BeagleWidget. Each page in the Stack Navigator must have a different BeagleWidget. +O navegador de pilha também é responsável por instanciar o "BeagleWidget". Cada página no "StackNavigator" deve ter um "BeagleWidget" diferente. -The BeagleWidget is the widget responsible for rendering the server driven UI itself. It holds a reference to a BeagleView, which is the main structure of Beagle. The BeagleView stores the Beagle UI tree and is responsible for making changes and re-rendering it whenever necessary. To know more about the BeagleView, check [this article]({{< ref path="/flutter/other/beagle-view" lang="en" >}}). +O "BeagleWidget" é o widget responsável por renderizar uma "server-driven UI". Ele contém uma referência a um "BeagleView", que é a estrutura principal do Beagle. O "BeagleView" armazena a árvore da interface do usuário do Beagle e é responsável por fazer alterações e renderizá-la novamente sempre que necessário. Para saber mais sobre o "BeagleView", consulte [este artigo]({{< ref path="/flutter/other/beagle-view" lang="pt" >}}).