Showing
1 changed file
with
633 additions
and
193 deletions
1 | -# Get | 1 | + |
2 | 2 | ||
3 | -Uma biblioteca de navegação completa que permite navegar entre telas, abrir caixas de diálogo, bottomSheets e exibir snackbars de qualquer lugar do seu código, sem precisar usar context. | ||
4 | -## Ponto de partida | 3 | +*Languages: [English](README.md), [Brazilian Portuguese](README.pt-br.md).* |
5 | 4 | ||
6 | -*Idiomas: [Inglês](README.md), [Português](README.pt-br.md).* | ||
7 | - | ||
8 | -A navegação convencional do Flutter possui muito código clichê desnecessário, requer contexto para navegar entre telas, abrir caixas de diálogo e usar snackbars em seu projeto pode ser algo desgastante. | ||
9 | -Além disso, quando uma rota é enviada por push, todo o MaterialApp pode ser reconstruído causando congelamentos, bem, isso não acontece com o Get. | ||
10 | -Essa biblioteca que mudará a maneira como você trabalha com o Framework e salvará sua vida do código clichê, aumentando sua produtividade e eliminando os erros de reconstrução do seu aplicativo, além de um conjunto de APIs não disponíveis na biblioteca padrão do Flutter. | 5 | +[](https://pub.dev/packages/get) |
6 | + | ||
7 | +[](https://gitter.im/flutter_get/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) | ||
8 | +<a href="https://github.com/Solido/awesome-flutter"> | ||
9 | + <img alt="Awesome Flutter" src="https://img.shields.io/badge/Awesome-Flutter-blue.svg?longCache=true&style=flat-square" /> | ||
10 | +</a> | ||
11 | 11 | ||
12 | +Get is an extra-light and powerful library for Flutter that will give you superpowers and increase your productivity. Navigate without context, open dialogs, snackbars or bottomsheets from anywhere in your code, Manage states and inject dependencies in an easy and practical way! Get is secure, stable, up-to-date, and offers a huge range of APIs that are not present on default framework. | ||
12 | 13 | ||
13 | ```dart | 14 | ```dart |
14 | -// Navegação padrão do Flutter: | 15 | +// Default Flutter navigator |
15 | Navigator.of(context).push( | 16 | Navigator.of(context).push( |
16 | context, | 17 | context, |
17 | MaterialPageRoute( | 18 | MaterialPageRoute( |
18 | builder: (BuildContext context) { | 19 | builder: (BuildContext context) { |
19 | - return HomePage(); | 20 | + return Home(); |
20 | }, | 21 | }, |
21 | ), | 22 | ), |
22 | ); | 23 | ); |
23 | 24 | ||
24 | -// Como fazer o mesmo com o Get: | 25 | +// Get syntax |
25 | Get.to(Home()); | 26 | Get.to(Home()); |
26 | ``` | 27 | ``` |
27 | 28 | ||
28 | -##### Se você está na branch master/dev/beta do Flutter, use a versão 1.20.0-dev. | ||
29 | -* Se você usa Modular, adicione ao seu MaterialApp: navigatorKey: Get.addKey(Modular.navigatorKey) | ||
30 | - | ||
31 | -## Como usar? | ||
32 | - | ||
33 | -Adicione esse pacote ao seu arquivo pubspec.yaml: | ||
34 | - | ||
35 | -``` | ||
36 | -dependencies: | ||
37 | - get: ^1.17.3 // ^1.20.1-dev on beta/dev/master | ||
38 | -``` | ||
39 | - | ||
40 | -Importe ele se seu IDE não fizer isso de forma automática: | 29 | +## Getting Started |
30 | + | ||
31 | +Flutter's conventional navigation has a lot of unnecessary boilerplate, requires context to navigate between screens, open dialogs, and use snackbars on framework is really boring. | ||
32 | +In addition, when a route is pushed, the entire MaterialApp can be rebuilt causing freezes, this does not happen with Get. | ||
33 | +This library that will change the way you work with the Framework and save your life from cliche code, increasing your productivity, and eliminating the rebuild bugs of your application. | ||
34 | + | ||
35 | + | ||
36 | +- **[How to use?](#how-to-use)** | ||
37 | +- **[Navigating without named routes](#Navigating-without-named-routes)** | ||
38 | +- **[SnackBars](#SnackBars)** | ||
39 | +- **[Dialogs](#Dialogs)** | ||
40 | +- **[BottomSheets](#BottomSheets)** | ||
41 | +- **[Simple State Manager](#Simple-State-Manager)** | ||
42 | +- **[Reactive State Manager](#Reactive-State-Manager)** | ||
43 | +- **[Simple Instance Manager](#Simple-Instance-Manager)** | ||
44 | +- **[Navigate with named routes](#Navigate-with-named-routes)** | ||
45 | +- **[Send data to named Routes](#Send-data-to-named-Routes)** | ||
46 | +- **[Dynamic urls links](#Dynamic-urls-links)** | ||
47 | +- **[Middleware](#Middleware)** | ||
48 | +- **[Optional Global Settings](#Optional-Global-Settings)** | ||
49 | +- **[Other Advanced APIs and Manual configurations](#Other-Advanced-APIs-and-Manual-configurations)** | ||
50 | +- **[Nested Navigators](#Nested-Navigators)** | ||
51 | + | ||
52 | + | ||
53 | +#### You can contribute to the project in multiple ways: | ||
54 | +- Helping to translate the readme into other languages. | ||
55 | +- Adding documentation to the readme (not even half of Get's functions have been documented yet). | ||
56 | +- Writing articles/videos about Get (they will be inserted in the Readme, and in the future in our Wiki). | ||
57 | +- Offering PRs for code/tests. | ||
58 | +- Including new functions. | ||
59 | + | ||
60 | +Any contribution is welcome! | ||
61 | + | ||
62 | +## How to use? | ||
63 | + | ||
64 | +<!-- - Flutter Master/Dev/Beta: version 2.0.x-dev | ||
65 | +- Flutter Stable branch: version 2.0.x | ||
66 | +(look for latest version on pub.dev) --> | ||
67 | + | ||
68 | +Add Get to your pubspec.yaml file | ||
69 | +<!-- according to the version of Flutter you are using. --> | ||
70 | + | ||
71 | +Exchange your MaterialApp for GetMaterialApp and enjoy! | ||
41 | ```dart | 72 | ```dart |
42 | import 'package:get/get.dart'; | 73 | import 'package:get/get.dart'; |
74 | +GetMaterialApp( // Before: MaterialApp( | ||
75 | + home: MyHome(), | ||
76 | +) | ||
43 | ``` | 77 | ``` |
44 | -Adicione GetKey ao seu MaterialApp e aproveite! | ||
45 | -```dart | ||
46 | -MaterialApp( | ||
47 | - navigatorKey: Get.key, | ||
48 | - home: MyHome(), | ||
49 | - ) | ||
50 | -``` | ||
51 | -### Navegando sem rotas nomeadas | ||
52 | -Para ir para outra tela: | 78 | +## Navigating without named routes |
79 | +To navigate to a new screen: | ||
53 | 80 | ||
54 | ```dart | 81 | ```dart |
55 | Get.to(NextScreen()); | 82 | Get.to(NextScreen()); |
56 | ``` | 83 | ``` |
57 | 84 | ||
58 | -Para voltar para a tela anterior | 85 | +To return to previous screen |
59 | 86 | ||
60 | ```dart | 87 | ```dart |
61 | Get.back(); | 88 | Get.back(); |
62 | ``` | 89 | ``` |
63 | 90 | ||
64 | -Para ir para a próxima tela e tirar a rota atual da stack de navegação (uso comum em SplashScreens, telas de cadastros e qualquer outra tela que você não deseja exibir quando clicar em voltar) | 91 | +To go to the next screen and no option to go back to the previous screen (for use in SplashScreens, login screens and etc.) |
65 | 92 | ||
66 | ```dart | 93 | ```dart |
67 | Get.off(NextScreen()); | 94 | Get.off(NextScreen()); |
68 | ``` | 95 | ``` |
69 | 96 | ||
70 | -Ir para a próxima tela e tirar todas as telas anteriores da stack de navegação (geralmente usado em carrinhos de compras, provas, enquetes e etc) | 97 | +To go to the next screen and cancel all previous routes (useful in shopping carts, polls, and tests) |
71 | 98 | ||
72 | ```dart | 99 | ```dart |
73 | Get.offAll(NextScreen()); | 100 | Get.offAll(NextScreen()); |
74 | ``` | 101 | ``` |
75 | 102 | ||
76 | -Para navegar para uma rota e receber ou atualizar dados assim que voltar dela: | 103 | +To navigate to the next route, and receive or update data as soon as you return from it: |
77 | ```dart | 104 | ```dart |
78 | var data = await Get.to(Payment()); | 105 | var data = await Get.to(Payment()); |
79 | ``` | 106 | ``` |
80 | -Na próxima tela, envie algum dado para a screen anterior ao voltar (pode ser qualquer coisa, Strings, int, Maps, até instâncias de classes, você pode tudo): | 107 | +on other screen, send a data for previous route: |
81 | 108 | ||
82 | ```dart | 109 | ```dart |
83 | Get.back(result: 'sucess'); | 110 | Get.back(result: 'sucess'); |
84 | ``` | 111 | ``` |
85 | -E você pode usar o dado recebido assim: | 112 | +And use it: |
86 | 113 | ||
87 | ex: | 114 | ex: |
88 | ```dart | 115 | ```dart |
89 | if(data == 'sucess') madeAnything(); | 116 | if(data == 'sucess') madeAnything(); |
90 | ``` | 117 | ``` |
91 | 118 | ||
92 | -Você não quer aprender nossa sintaxe? | ||
93 | -Basta alterar o Navigator (maiúsculo) para navigator (minúsculo) e você terá todas as funções da navegação padrão, sem precisar usar o contexto | ||
94 | -Exemplo: | 119 | +Don't you want to learn our syntax? |
120 | +Just change the Navigator (uppercase) to navigator (lowercase), and you will have all the functions of the standard navigation, without having to use context | ||
121 | +Example: | ||
95 | 122 | ||
96 | ```dart | 123 | ```dart |
97 | 124 | ||
98 | -// Navegação padrão | 125 | +// Default Flutter navigator |
99 | Navigator.of(context).push( | 126 | Navigator.of(context).push( |
100 | context, | 127 | context, |
101 | MaterialPageRoute( | 128 | MaterialPageRoute( |
@@ -105,7 +132,7 @@ Navigator.of(context).push( | @@ -105,7 +132,7 @@ Navigator.of(context).push( | ||
105 | ), | 132 | ), |
106 | ); | 133 | ); |
107 | 134 | ||
108 | -// Usando Get com a sintaxe do Flutter | 135 | +// Get using Flutter syntax without needing context |
109 | navigator.push( | 136 | navigator.push( |
110 | MaterialPageRoute( | 137 | MaterialPageRoute( |
111 | builder: (_) { | 138 | builder: (_) { |
@@ -114,7 +141,7 @@ navigator.push( | @@ -114,7 +141,7 @@ navigator.push( | ||
114 | ), | 141 | ), |
115 | ); | 142 | ); |
116 | 143 | ||
117 | -// Usando a sintaxe do Get (Muito melhor, mas você pode discordar disso) | 144 | +// Get syntax (It is much better, but you have the right to disagree) |
118 | Get.to(HomePage()); | 145 | Get.to(HomePage()); |
119 | 146 | ||
120 | 147 | ||
@@ -122,12 +149,12 @@ Get.to(HomePage()); | @@ -122,12 +149,12 @@ Get.to(HomePage()); | ||
122 | 149 | ||
123 | ### SnackBars | 150 | ### SnackBars |
124 | 151 | ||
125 | -Para ter uma simples SnackBar com Flutter, você deve obter o contexto do Scaffold ou usar uma GlobalKey anexada ao seu Scaffold, | 152 | +To have a simple SnackBar with Flutter, you must get the context of Scaffold, or you must use a GlobalKey attached to your Scaffold, |
126 | ```dart | 153 | ```dart |
127 | final snackBar = SnackBar( | 154 | final snackBar = SnackBar( |
128 | - content: Text('Oi!'), | 155 | + content: Text('Hi!'), |
129 | action: SnackBarAction( | 156 | action: SnackBarAction( |
130 | - label: 'Eu sou uma velha e feia snackbar :(', | 157 | + label: 'I am a old and ugly snackbar :(', |
131 | onPressed: (){} | 158 | onPressed: (){} |
132 | ), | 159 | ), |
133 | // Find the Scaffold in the widget tree and use | 160 | // Find the Scaffold in the widget tree and use |
@@ -135,13 +162,13 @@ final snackBar = SnackBar( | @@ -135,13 +162,13 @@ final snackBar = SnackBar( | ||
135 | Scaffold.of(context).showSnackBar(snackBar); | 162 | Scaffold.of(context).showSnackBar(snackBar); |
136 | ``` | 163 | ``` |
137 | 164 | ||
138 | -Já com o Get: | 165 | +With Get: |
139 | 166 | ||
140 | ```dart | 167 | ```dart |
141 | -Get.snackbar('Oi', 'Eu sou uma snackbar bonita e moderna'); | 168 | +Get.snackbar('Hi', 'i am a modern snackbar'); |
142 | ``` | 169 | ``` |
143 | 170 | ||
144 | -Com o Get, tudo o que você precisa fazer é chamar o Get.snackbar de qualquer lugar no seu código ou personalizá-lo como quiser! | 171 | +With Get, all you have to do is call your Get.snackbar from anywhere in your code or customize it however you want! |
145 | 172 | ||
146 | ```dart | 173 | ```dart |
147 | Get.snackbar( | 174 | Get.snackbar( |
@@ -156,12 +183,13 @@ Com o Get, tudo o que você precisa fazer é chamar o Get.snackbar de qualquer l | @@ -156,12 +183,13 @@ Com o Get, tudo o que você precisa fazer é chamar o Get.snackbar de qualquer l | ||
156 | ); | 183 | ); |
157 | 184 | ||
158 | 185 | ||
159 | - ////////// TODOS RECURSOS ////////// | 186 | + ////////// ALL FEATURES ////////// |
160 | // Color colorText, | 187 | // Color colorText, |
161 | // Duration duration, | 188 | // Duration duration, |
162 | // SnackPosition snackPosition, | 189 | // SnackPosition snackPosition, |
163 | // Widget titleText, | 190 | // Widget titleText, |
164 | // Widget messageText, | 191 | // Widget messageText, |
192 | + // bool instantInit, | ||
165 | // Widget icon, | 193 | // Widget icon, |
166 | // bool shouldIconPulse, | 194 | // bool shouldIconPulse, |
167 | // double maxWidth, | 195 | // double maxWidth, |
@@ -191,39 +219,36 @@ Com o Get, tudo o que você precisa fazer é chamar o Get.snackbar de qualquer l | @@ -191,39 +219,36 @@ Com o Get, tudo o que você precisa fazer é chamar o Get.snackbar de qualquer l | ||
191 | // Form userInputForm | 219 | // Form userInputForm |
192 | /////////////////////////////////// | 220 | /////////////////////////////////// |
193 | ``` | 221 | ``` |
194 | -Após a recusa de um aplicativo na AppleStore por usar a snackbar padrão que não combina nada com as Human Guidelines da Apple, resolvi criar a Get.snackbar, mas se você prefere a snackbar padrão, ou não desenvolve para iOS, você pode usar a API de baixo nível `GetBar().show();` que permite por exemplo, excluir a mensagem (Get.snackbar tem título e mensagem obrigatórios). | 222 | +If you prefer the traditional snackbar, or want to customize it from scratch, including adding just one line (Get.snackbar makes use of a mandatory title and message), you can use |
223 | +`Get.rawSnackbar();` which provides the RAW API on which Get.snackbar was built. | ||
195 | 224 | ||
196 | -### Caixas de dialogos | 225 | +### Dialogs |
197 | 226 | ||
198 | -Para abrir uma caixa de diálogo: | 227 | +To open dialog: |
199 | 228 | ||
200 | ```dart | 229 | ```dart |
201 | Get.dialog(YourDialogWidget()); | 230 | Get.dialog(YourDialogWidget()); |
202 | ``` | 231 | ``` |
203 | 232 | ||
204 | -Para abrir o dialogo padrão do Get: | 233 | +To open default dialog: |
205 | 234 | ||
206 | ```dart | 235 | ```dart |
207 | Get.defaultDialog( | 236 | Get.defaultDialog( |
208 | - title: "My Title", | ||
209 | - content: Text("Hi, it's my dialog"), | ||
210 | - confirm: FlatButton( | ||
211 | - child: Text("Ok"), | ||
212 | - onPressed: () => print("OK pressed"), | ||
213 | - ), | ||
214 | - cancel: FlatButton( | ||
215 | - child: Text("Cancel"), | ||
216 | - onPressed: () => Get.back(), | ||
217 | - )); | 237 | + onConfirm: () => print("Ok"), |
238 | + middleText: "Dialog made in 3 lines of code"); | ||
218 | ``` | 239 | ``` |
240 | +You can also use Get.generalDialog instead of showGeneralDialog. | ||
241 | + | ||
242 | +For all other Flutter dialog widgets, including cupertinos, you can use Get.overlayContext instead of context, and open it anywhere in your code. | ||
243 | +For widgets that don't use Overlay, you can use Get.context. | ||
244 | +These two contexts will work in 99% of cases to replace the context of your UI, except for cases where inheritedWidget is used without a navigation context. | ||
219 | 245 | ||
220 | ### BottomSheets | 246 | ### BottomSheets |
221 | -Get.bottomSheet é como showModalBottomSheet, mas não precisa de context. | 247 | +Get.bottomSheet is like showModalBottomSheet, but don't need of context. |
222 | 248 | ||
223 | ```dart | 249 | ```dart |
224 | Get.bottomSheet( | 250 | Get.bottomSheet( |
225 | - builder: (_){ | ||
226 | - return Container( | 251 | + Container( |
227 | child: Wrap( | 252 | child: Wrap( |
228 | children: <Widget>[ | 253 | children: <Widget>[ |
229 | ListTile( | 254 | ListTile( |
@@ -236,137 +261,522 @@ Get.bottomSheet( | @@ -236,137 +261,522 @@ Get.bottomSheet( | ||
236 | title: Text('Video'), | 261 | title: Text('Video'), |
237 | onTap: () => {}, | 262 | onTap: () => {}, |
238 | ), | 263 | ), |
239 | - ], | ||
240 | - ), | 264 | + ], |
265 | + ), | ||
241 | ); | 266 | ); |
242 | } | 267 | } |
243 | ); | 268 | ); |
244 | ``` | 269 | ``` |
245 | -### Configurações Globais | ||
246 | -Você pode criar configurações globais para o Get. Basta adicionar Get.config ao seu código antes de enviar qualquer rota. (Se não souber onde colocar, coloque dentro da função main()) | 270 | + |
271 | +## Simple State Manager | ||
272 | +There are currently several state managers for Flutter. However, most of them involve using ChangeNotifier to update widgets and this is a bad and very bad approach to performance of medium or large applications. You can check in the official Flutter documentation that ChangeNotifier should be used with 1 or a maximum of 2 listeners (https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html), making it practically unusable for any application medium or large. Other state managers are good, but have their nuances. BLoC is very safe and efficient, but it is very complex for beginners, which has kept people from developing with Flutter. MobX is easier than BLoC and reactive, almost perfect, I would say, but you need to use a code generator that for large applications, reduces productivity, you will need to drink a lot of coffees until your code is ready again after a Flutter clean (And this is not MobX's fault, but the codegen which is really slow!). Provider uses InheritedWidget to deliver the same listener, as a way of solving the problem reported above with ChangeNotifier, which implies that any access to its ChangeNotifier class must be within the widget tree because of the context to access o Inherited. | ||
273 | + | ||
274 | +Get isn't better or worse than any other state manager, but that you should analyze these points as well as the points below to choose between using Get in pure form (Vanilla), or using it in conjunction with another state manager. Definitely, Get is not the enemy of any other state manager, because Get is a microframework, not just a state manager, and can be used either alone or in conjunction with them. | ||
275 | + | ||
276 | +Get has a state manager that is extremely light and easy (written in just 95 lines of code), which does not use ChangeNotifier, will meet the need especially for those new to Flutter, and will not cause problems for large applications. | ||
277 | + | ||
278 | +What performance improvements does Get bring? | ||
279 | + | ||
280 | +1- Update only the required widget. | ||
281 | + | ||
282 | +2- Does not use changeNotifier, it is the state manager that uses less memory (close to 0mb for until). | ||
283 | + | ||
284 | +3- Forget StatefulWidget! With Get you will never need it. With the other state managers, you will probably have to use a StatefulWidget to get the instance of your Provider, BLoC, MobX Controller, etc. But have you ever stopped to think that your appBar, your scaffold, and most of the widgets that are in your class are stateless? So why save the state of an entire class, if you can only save the state of the Widget that is stateful? Get solves that, too. Create a Stateless class, make everything stateless. If you need to update a single component, wrap it with GetBuilder, and its state will be maintained. | ||
285 | + | ||
286 | +4- Organize your project for real! Controllers must not be in your UI, place your TextEditController, or any controller you use within your Controller class. | ||
287 | + | ||
288 | +5- Do you need to trigger an event to update a widget as soon as it is rendered? GetBuilder has the property "initState", just like StatefulWidget, and you can call events from your controller, directly from it, no more events being placed in your initState. | ||
289 | + | ||
290 | +6- Do you need to trigger an action like closing streams, timers and etc? GetBuilder also has the dispose property, where you can call events as soon as that widget is destroyed. | ||
291 | + | ||
292 | +7- Use streams only if necessary. You can use your StreamControllers inside your controller normally, and use StreamBuilder also normally, but remember, a stream reasonably consumes memory, reactive programming is beautiful, but you shouldn't abuse it. 30 streams open simultaneously can be worse than changeNotifier (and changeNotifier is very bad). | ||
293 | + | ||
294 | +8- Update widgets without spending ram for that. Get stores only the GetBuilder creator ID, and updates that GetBuilder when necessary. The memory consumption of the get ID storage in memory is very low even for thousands of GetBuilders. When you create a new GetBuilder, you are actually sharing the state of GetBuilder that has a creator ID. A new state is not created for each GetBuilder, which saves A LOT OF ram for large applications. Basically your application will be entirely Stateless, and the few Widgets that will be Stateful (within GetBuilder) will have a single state, and therefore updating one will update them all. The state is just one. | ||
295 | + | ||
296 | +9- Get is omniscient and in most cases it knows exactly the time to take a controller out of memory. You should not worry about when to dispose of a controller, Get knows the best time to do this. Example: | ||
297 | + | ||
298 | +- Class a => Class B (has controller X) => Class C (has controller X) | ||
299 | + | ||
300 | +In class A the controller is not yet in memory, because you have not used it yet (Get is lazyLoad). In class B you used the controller, and it entered memory. In class C you used the same controller as in class B, Get will share the state of controller B with controller C, and the same controller is still in memory. If you close screen C and screen B, Get will automatically take controller X out of memory and free up resources, because Class a is not using the controller. If you navigate to B again, controller X will enter memory again, if instead of going to class C, you return to class A again, Get will take the controller out of memory in the same way. If class C didn't use the controller, and you took class B out of memory, no class would be using controller X and likewise it would be disposed of. The only exception that can mess with Get, is if you remove B from the route unexpectedly, and try to use the controller in C. In this case, the creator ID of the controller that was in B was deleted, and Get was programmed to remove it from memory every controller that has no creator ID. If you intend to do this, add the "autoRemove: false" flag to class B's GetBuilder and use adoptID = true; in class C's GetBuilder. | ||
301 | + | ||
302 | +### Simple state manager usage | ||
247 | 303 | ||
248 | ```dart | 304 | ```dart |
249 | -Get.config( | ||
250 | - enableLog = true, | ||
251 | - defaultPopGesture = true, | ||
252 | - defaultTransition = Transitions.cupertino} | 305 | +// Create controller class and extends GetController |
306 | +class Controller extends GetController { | ||
307 | + int counter = 0; | ||
308 | + void increment() { | ||
309 | + counter++; | ||
310 | + update(this); // use update(this) to update counter variable on UI when increment be called | ||
311 | + } | ||
312 | +} | ||
313 | +// On your Stateless/Stateful class, use GetBuilder to update Text when increment be called | ||
314 | +GetBuilder<Controller>( | ||
315 | + init: Controller(), // INIT IT ONLY THE FIRST TIME | ||
316 | + builder: (_) => Text( | ||
317 | + '${_.counter}', | ||
318 | + )), | ||
319 | +//Initialize your controller only the first time. The second time you are using ReBuilder for the same controller, do not use it again. Your controller will be automatically removed from memory as soon as the widget that marked it as 'init' is deployed. You don't have to worry about that, Get will do it automatically, just make sure you don't start the same controller twice. | ||
320 | +``` | ||
321 | +**Done!** | ||
322 | +- You have already learned how to manage states with Get. | ||
323 | + | ||
324 | +- Note: You may want a larger organization, and not use the init property. For that, you can create a class and extends Bindings class, and within it mention the controllers that will be created within that route. Controllers will not be created at that time, on the contrary, this is just a statement, so that the first time you use a Controller, Get will know where to look. Get will remain lazyLoad, and will continue to dispose Controllers when they are no longer needed. See the pub.dev example to see how it works. | ||
325 | + | ||
326 | + | ||
327 | +If you navigate many routes and need data that was in your previously used controller, you just need to use GetBuilder Again (with no init): | ||
328 | + | ||
329 | +```dart | ||
330 | +class OtherClasse extends StatelessWidget { | ||
331 | + @override | ||
332 | + Widget build(BuildContext context) { | ||
333 | + return Scaffold( | ||
334 | + body: Center( | ||
335 | + child: GetBuilder<Controller>( | ||
336 | + builder: (s) => Text('${s.counter}'), | ||
337 | + ), | ||
338 | + ), | ||
339 | + ); | ||
340 | + } | ||
341 | + | ||
342 | +``` | ||
343 | +If you need to use your controller in many other places, and outside of GetBuilder, just create a get in your controller and have it easily. (or use `Get.find<Controller>()`) | ||
344 | + | ||
345 | +```dart | ||
346 | +class Controller extends GetController { | ||
347 | + | ||
348 | + /// You do not need that. I recommend using it just for ease of syntax. | ||
349 | + /// with static method: Controller.to.counter(); | ||
350 | + /// with no static method: Get.find<Controller>().counter(); | ||
351 | + /// There is no difference in performance, nor any side effect of using either syntax. Only one does not need the type, and the other the IDE will autocomplete it. | ||
352 | + static Controller get to => Get.find(); // add this line | ||
353 | + | ||
354 | + int counter = 0; | ||
355 | + void increment() { | ||
356 | + counter++; | ||
357 | + update(this); | ||
358 | + } | ||
359 | +} | ||
360 | +``` | ||
361 | +And then you can access your controller directly, that way: | ||
362 | +```dart | ||
363 | +FloatingActionButton( | ||
364 | + onPressed:(){ | ||
365 | + Controller.to.increment(), | ||
366 | + } // This is incredibly simple! | ||
367 | + child: Text("${Controller.to.counter}"), | ||
368 | + ), | ||
369 | +``` | ||
370 | +When you press FloatingActionButton, all widgets that are listening to the 'counter' variable will be updated automatically. | ||
371 | + | ||
372 | +#### No StatefulWidget: | ||
373 | +Using StatefulWidgets means storing the state of entire screens unnecessarily, even because if you need to minimally rebuild a widget, you will embed it in a Consumer/Observer/BlocProvider/GetBuilder, which will be another StatefulWidget. | ||
374 | +The StatefulWidget class is a class larger than StatelessWidget, which will allocate more RAM, and this may not make a significant difference between one or two classes, but it will most certainly do when you have 100 of them! | ||
375 | +Unless you need to use a mixin, like TickerProviderStateMixin, it will be totally unnecessary to use a StatefulWidget with Get. | ||
376 | + | ||
377 | +You can call all methods of a StatefulWidget directly from a GetBuilder. | ||
378 | +If you need to call initState() or dispose() method for example, you can call them directly; | ||
379 | + | ||
380 | +```dart | ||
381 | +GetBuilder<Controller>( | ||
382 | + initState(_) => Controller.to.fetchApi(), | ||
383 | + dispose(_) => Controller.to.closeStreams(), | ||
384 | + builder: (s) => Text('${s.username}'), | ||
385 | + ), | ||
386 | +``` | ||
387 | + | ||
388 | +A much better approach than this is to use the onInit() and onClose() method directly from your controller. | ||
389 | + | ||
390 | +```dart | ||
391 | +@override | ||
392 | +void onInit() { | ||
393 | + fetchApi(); | ||
394 | + super.onInit(); | ||
395 | +} | ||
253 | ``` | 396 | ``` |
254 | 397 | ||
255 | -## Gerenciador de instâncias descomplicado | ||
256 | -Além de aumentar produtividade, muita gente usa Get para ter um aplicativo menor. Se você tem várias rotas e snackbars em seu aplicativo, ele provavelmente terá um código final maior que seu aplicativo + essa biblioteca | ||
257 | -Se você já está usando o Get e deseja tornar seu projeto o mais enxuto possível, agora o Get possui um gerenciador de instancias simples que permite recuperar a mesma classe do seu Bloc ou Controller com apenas 1 linhas de código. | 398 | +- NOTE: If you want to start a method at the moment the controller is called for the first time, you DON'T NEED to use constructors for this, in fact, using a performance-oriented package like Get, this borders on bad practice, because it deviates from the logic in which the controllers are created or allocated (if you create an instance of this controller, the constructor will be called immediately, you will be populating a controller before it is even used, you are allocating memory without it being in use, this definitely hurts the principles of this library). The onInit() methods; and onClose(); were created for this, they will be called when the Controller is created, or used for the first time, depending on whether you are using Get.lazyPut or not. If you want, for example, to make a call to your API to populate data, you can forget about the old-fashioned method of initState/dispose, just start your call to the api in onInit, and if you need to execute any command like closing streams, use the onClose() for that. |
399 | +The purpose of this package is precisely to give you a complete solution for navigation of routes, management of dependencies and states, using the least possible dependencies, with a high degree of decoupling. Get engages all high and low level Flutter APIs within itself, to ensure that you work with the least possible coupling. We centralize everything in a single package, to ensure that you don't have any kind of coupling in your project. That way, you can put only widgets in your view, and leave the part of your team that works with the business logic free, to work with the business logic without depending on any element of the View. This provides a much cleaner working environment, so that part of your team works only with widgets, without worrying about sending data to your controller, and part of your team works only with the business logic in its breadth, without depending on no element of the view. | ||
400 | + | ||
401 | +So to simplify this: | ||
402 | +You don't need to call methods in initState and send them by parameter to your controller, nor use your controller constructor for that, you have the onInit() method that is called at the right time for you to start your services. | ||
403 | +You do not need to call the device, you have the onClose() method that will be called at the exact moment when your controller is no longer needed and will be removed from memory. That way, leave views for widgets only, refrain from any kind of business logic from it. | ||
404 | + | ||
405 | +Do not call a dispose method inside GetController, it will not do anything, remember that the controller is not a Widget, you should not "dispose" it, and it will be automatically and intelligently removed from memory by Get. If you used any stream on it and want to close it, just insert it into the close method. Example: | ||
258 | 406 | ||
259 | ```dart | 407 | ```dart |
260 | -Controller controller = Get.put(Controller()); // Em vez de Controller controller = Controller(); | 408 | +class Controller extends GetController { |
409 | +StreamController<User> user = StreamController<User>(); | ||
410 | +StreamController<String> name = StreamController<String>(); | ||
411 | + | ||
412 | +/// close stream = onClose method, not dispose. | ||
413 | +@override | ||
414 | +void onClose() { | ||
415 | + user.close(); | ||
416 | + name.close(); | ||
417 | + super.onClose(); | ||
418 | +} | ||
419 | + | ||
261 | ``` | 420 | ``` |
262 | -Em vez de instanciar seu controlador dentro da classe que você está usando, use o metodo put para que o Get pegue sua instância e disponibilize por todo o seu aplicativo. | ||
263 | -Então você pode usar seu controlador (ou classe Bloc) normalmente. | 421 | +Controller life cycle: |
422 | +- onInit() where it is created. | ||
423 | +- onClose() where it is closed to make any changes in preparation for the delete method | ||
424 | +- deleted: you do not have access to this API because it is literally removing the controller from memory. It is literally deleted, without leaving any trace. | ||
425 | + | ||
426 | +##### Forms of use: | ||
427 | + | ||
428 | +- Recommended usage: | ||
429 | + | ||
430 | +You can use Controller instance directly on GetBuilder value: | ||
431 | + | ||
432 | +```dart | ||
433 | +GetBuilder<Controller>( | ||
434 | + init: Controller(), | ||
435 | + builder: (value) => Text( | ||
436 | + '${value.counter}', //here | ||
437 | + )), | ||
438 | +``` | ||
439 | +You may also need an instance of your controller outside of your GetBuilder, and you can use these approaches to achieve this: | ||
440 | + | ||
441 | +```dart | ||
442 | +class Controller extends GetController { | ||
443 | + static Controller get to => Get.find(); | ||
444 | +[...] | ||
445 | +} | ||
446 | +// on stateful/stateless class | ||
447 | +GetBuilder<Controller>( | ||
448 | + init: Controller(), // use it only first time on each controller | ||
449 | + builder: (_) => Text( | ||
450 | + '${Controller.to.counter}', //here | ||
451 | + )), | ||
452 | +or | ||
453 | + | ||
454 | +class Controller extends GetController { | ||
455 | + // static Controller get to => Get.find(); // with no static get | ||
456 | +[...] | ||
457 | +} | ||
458 | +// on stateful/stateless class | ||
459 | +GetBuilder<Controller>( | ||
460 | + init: Controller(), // use it only first time on each controller | ||
461 | + builder: (_) => Text( | ||
462 | + '${Get.find<Controller>().counter}', //here | ||
463 | + )), | ||
464 | +``` | ||
465 | + | ||
466 | +- You can use "non-canonical" approaches to do this. If you are using some other dependency manager, like get_it, modular, etc., and just want to deliver the controller instance, you can do this: | ||
467 | + | ||
468 | +```dart | ||
469 | + | ||
470 | +Controller controller = Controller(); | ||
471 | +[...] | ||
472 | +GetBuilder( // you dont need to type on this way | ||
473 | + init: controller, //here | ||
474 | + builder: (_) => Text( | ||
475 | + '${controller.counter}', // here | ||
476 | + )), | ||
477 | + | ||
478 | +``` | ||
479 | +This approach is not recommended, as you will have to manually dispose of your controllers, close your streams manually, and literally give up one of the great benefits of this library, which is intelligent memory control. But if you trust your potential, go ahead! | ||
480 | + | ||
481 | +If you want to refine a widget's update control with GetBuilder, you can assign them unique IDs: | ||
482 | +```dart | ||
483 | +GetBuilder<Controller>( | ||
484 | + id: 'text' | ||
485 | + init: Controller(), // use it only first time on each controller | ||
486 | + builder: (_) => Text( | ||
487 | + '${Get.find<Controller>().counter}', //here | ||
488 | + )), | ||
489 | +``` | ||
490 | +And update it this form: | ||
491 | +```dart | ||
492 | +update(this,['text']); | ||
493 | +``` | ||
494 | +You can also impose conditions for the update: | ||
495 | + | ||
496 | +```dart | ||
497 | +update(this,['text'], counter < 10); | ||
498 | +``` | ||
499 | + | ||
500 | +GetX does this automatically and only reconstructs the widget that uses the exact variable that was changed, if you change a variable to the same as the previous one and that does not imply a change of state , GetX will not rebuild the widget to save memory and CPU cycles (3 is being displayed on the screen, and you change the variable to 3 again. In most state managers, this will cause a new rebuild, but with GetX the widget will only is rebuilt again, if in fact his state has changed). | ||
501 | +GetBuilder is aimed precisely at multiple state control. Imagine that you added 30 products to a cart, you click delete one, at the same time that the list is updated, the price is updated and the badge in the shopping cart is updated to a smaller number. This type of approach makes GetBuilder killer, because it groups states and changes them all at once without any "computational logic" for that. GetBuilder was created with this type of situation in mind, since for ephemeral change of state, you can use setState and you would not need a state manager for this. However, there are situations where you want only the widget where a certain variable has been changed to be rebuilt, and this is what GetX does with a mastery never seen before. | ||
502 | + | ||
503 | +That way, if you want an individual controller, you can assign IDs for that, or use GetX. This is up to you, remembering that the more "individual" widgets you have, the more the performance of GetX will stand out, while the performance of GetBuilder should be superior, when there is multiple change of state. | ||
504 | + | ||
505 | +You can use both in any situation, but if you want to tune their application to the maximum possible performance, I would say that: if your variables are changed at different times, use GetX, because there is no competition for it when the subject is to rebuild only what is necessary, if you do not need unique IDs, because all your variables will be changed when you perform an action, use GetBuilder, because it is a simple state updater in blocks, made in a few lines of code, to make just what he promises to do: update state in blocks. There is no way to compare RAM, CPU, or anything else from a giant state manager to a simple StatefulWidget (like GetBuilder) that is updated when you call update(this). It was done in a simple way, to have the least computational logic involved, just to fulfill a single purpose and spend the minimum resources possible for that purpose. | ||
506 | +If you want a powerful state manager, you can go without fear to GetX. It does not work with variables, but flows, everything in it is streams under the hood. You can use rxDart in conjunction with it, because everything is stream, you can hear the event of each "variable", because everything in it is stream, it is literally BLoC, easier than MobX, and without code generator or decorations . | ||
507 | + | ||
508 | + | ||
509 | +## Reactive State Manager | ||
510 | + | ||
511 | +If you want power, Get gives you the most advanced state manager you could ever have. | ||
512 | +GetX was built 100% based on Streams, and give you all the firepower that BLoC gave you, with an easier facility than using MobX. | ||
513 | +Without decorations, you can turn anything into Observable with just a ".obs". | ||
514 | + | ||
515 | +Maximum performance: In addition to having a smart algorithm for minimal reconstruction, Get uses comparators to make sure the state has changed. If you experience any errors in your application, and send a duplicate change of state, Get will ensure that your application does not collapse. | ||
516 | +The state only changes if the values change. That's the main difference between Get, and using Computed from MobX. When joining two observables, when one is changed, the hearing of that observable will change. With Get, if you join two variables (which is unnecessary computed for that), GetX (similar to Observer) will only change if it implies a real change of state. Example: | ||
517 | + | ||
518 | +```dart | ||
519 | +final count1 = 0.obs; | ||
520 | +final count2 = 0.obs; | ||
521 | +int get sum => count1.value + count2.value; | ||
522 | +``` | ||
523 | + | ||
524 | +```dart | ||
525 | + GetX<Controller>( | ||
526 | + builder: (_) { | ||
527 | + print("count 1 rebuild"); | ||
528 | + return Text('${_.count1.value}'); | ||
529 | + }, | ||
530 | + ), | ||
531 | + GetX<Controller>( | ||
532 | + builder: (_) { | ||
533 | + print("count 2 rebuild"); | ||
534 | + return Text('${_.count2.value}'); | ||
535 | + }, | ||
536 | + ), | ||
537 | + GetX<Controller>( | ||
538 | + builder: (_) { | ||
539 | + print("count 3 rebuild"); | ||
540 | + return Text('${_.sum}'); | ||
541 | + }, | ||
542 | + ), | ||
543 | +``` | ||
544 | + | ||
545 | +If we increment the number of count 1, only count 1 and count 3 are reconstructed, because count 1 now has a value of 1, and 1 + 0 = 1, changing the sum value. | ||
546 | + | ||
547 | +If we change count 2, only count2 and 3 are reconstructed, because the value of 2 has changed, and the result of the sum is now 2. | ||
548 | + | ||
549 | +If we add the number 1 to count 1, which already contains 1, no widget is reconstructed. If we add a value of 1 for count 1 and a value of 2 for count 2, only 2 and 3 will be reconstructed, simply because GetX not only changes what is necessary, it avoids duplicating events. | ||
550 | + | ||
551 | +In addition, Get provides refined state control. You can condition an event (such as adding an object to a list), on a certain condition. | ||
552 | + | ||
553 | +```dart | ||
554 | +list.addIf(item<limit, item); | ||
555 | +``` | ||
556 | + | ||
557 | +Without decorations, without a code generator, without complications, GetX will change the way you manage your states in Flutter, and that is not a promise, it is a certainty! | ||
558 | + | ||
559 | +Do you know Flutter's counter app? Your Controller class might look like this: | ||
560 | + | ||
561 | +```dart | ||
562 | +class CountCtl extends RxController { | ||
563 | + final count = 0.obs; | ||
564 | +} | ||
565 | +``` | ||
566 | +With a simple: | ||
567 | +```dart | ||
568 | +ctl.count.value++ | ||
569 | +``` | ||
570 | + | ||
571 | +You could update the counter variable in your UI, regardless of where it is stored. | ||
572 | + | ||
573 | +You can transform anything on obs: | ||
574 | + | ||
575 | +```dart | ||
576 | +class RxUser { | ||
577 | + final name = "Camila".obs; | ||
578 | + final age = 18.obs; | ||
579 | +} | ||
580 | + | ||
581 | +class User { | ||
582 | + User({String name, int age}); | ||
583 | + final rx = RxUser(); | ||
584 | + | ||
585 | + String get name => rx.name.value; | ||
586 | + set name(String value) => rx.name.value = value; | ||
587 | + | ||
588 | + int get age => rx.age.value; | ||
589 | + set age(int value) => rx.age.value = value; | ||
590 | +} | ||
591 | +``` | ||
592 | + | ||
593 | +```dart | ||
594 | + | ||
595 | +void main() { | ||
596 | + final user = User(); | ||
597 | + print(user.name); | ||
598 | + user.age = 23; | ||
599 | + user.rx.age.listen((int age) => print(age)); | ||
600 | + user.age = 24; | ||
601 | + user.age = 25; | ||
602 | +} | ||
603 | +___________ | ||
604 | +out: | ||
605 | +Camila | ||
606 | +23 | ||
607 | +24 | ||
608 | +25 | ||
609 | + | ||
610 | +``` | ||
611 | + | ||
612 | +Before you immerse yourself in this world, I will give you a tip, always access the "value" of your flow when reading it, especially if you are working with lists where this is apparently optional. | ||
613 | +You can access list.length, or list.value.length. Most of the time, both ways will work, since the GetX list inherits directly from the dart List. But there is a difference between you accessing the object, and accessing the flow. I strongly recommend you to access the value: | ||
614 | +```dart | ||
615 | +final list = List<User>().obs; | ||
616 | +``` | ||
617 | +```dart | ||
618 | +ListView.builder ( | ||
619 | +itemCount: list.value.lenght | ||
620 | +``` | ||
621 | +or else create a "get" method for it and abandon "value" for life. example: | ||
622 | + | ||
623 | +```dart | ||
624 | +final _list = List<User>().obs; | ||
625 | +List get list => _list.value; | ||
626 | +``` | ||
627 | +```dart | ||
628 | +ListView.builder ( | ||
629 | +itemCount: list.lenght | ||
630 | +``` | ||
631 | +You could add an existing list of another type to the observable list using a list.assign (oldList); or the assignAll method, which differs from add, and addAll, which must be of the same type. All existing methods in a list are also available on GetX. | ||
632 | + | ||
633 | +We could remove the obligation to use value with a simple decoration and code generator, but the purpose of this lib is precisely not to need any external dependency. It is to offer an environment ready for programming, involving the essentials (management of routes, dependencies and states), in a simple, light and performance way without needing any external package. You can literally add 3 letters to your pubspec (get) and start programming. All solutions included by default, from route management to state management, aim at ease, productivity and performance. The total weight of this library is less than that of a single state manager, even though it is a complete solution, and that is what you must understand. If you are bothered by value, and like a code generator, MobX is a great alternative, and you can use it in conjunction with Get. For those who want to add a single dependency in pubspec and start programming without worrying about the version of a package being incompatible with another, or if the error of a state update is coming from the state manager or dependency, or still, do not want to worrying about the availability of controllers, whether literally "just programming", get is just perfect. | ||
634 | +If you have no problem with the MobX code generator, or have no problem with the BLoC boilerplate, you can simply use Get for routes, and forget that it has state manager. Get SEM and RSM were born out of necessity, my company had a project with more than 90 controllers, and the code generator simply took more than 30 minutes to complete its tasks after a Flutter Clean on a reasonably good machine, if your project it has 5, 10, 15 controllers, any state manager will supply you well. If you have an absurdly large project, and code generator is a problem for you, you have been awarded this solution. | ||
635 | + | ||
636 | +Obviously, if someone wants to contribute to the project and create a code generator, or something similar, I will link in this readme as an alternative, my need is not the need for all devs, but for now I say, there are good solutions that already do that, like MobX. | ||
637 | + | ||
638 | +## Simple Instance Manager | ||
639 | +Are you already using Get and want to make your project as lean as possible? Get has a simple and powerful dependency manager that allows you to retrieve the same class as your Bloc or Controller with just 1 lines of code, no Provider context, no inheritedWidget: | ||
640 | + | ||
641 | +```dart | ||
642 | +Controller controller = Get.put(Controller()); // Rather Controller controller = Controller(); | ||
643 | +``` | ||
644 | +Instead of instantiating your class within the class you are using, you are instantiating it within the Get instance, which will make it available throughout your App. | ||
645 | +So you can use your controller (or class Bloc) normally | ||
264 | 646 | ||
265 | ```dart | 647 | ```dart |
266 | controller.fetchApi();// Rather Controller controller = Controller(); | 648 | controller.fetchApi();// Rather Controller controller = Controller(); |
267 | ``` | 649 | ``` |
268 | 650 | ||
269 | -Agora, imagine que você navegou por inúmeras rotas e precisa de dados que foram deixados para trás em seu controlador; você precisaria de um gerenciador de estado combinado com o Provider ou Get_it, correto? Não com Get. Você só precisa pedir ao Get para "procurar" pelo seu controlador, você não precisa de nenhuma dependência adicional para isso: | 651 | +Imagine that you have navigated through numerous routes, and you need a data that was left behind in your controller, you would need a state manager combined with the Provider or Get_it, correct? Not with Get. You just need to ask Get to "find" for your controller, you don't need any additional dependencies: |
270 | 652 | ||
271 | ```dart | 653 | ```dart |
272 | Controller controller = Get.find(); | 654 | Controller controller = Get.find(); |
273 | -// Sim, parece Magia, o Get irá descobrir qual é seu controller, e irá te entregar. Você pode ter 1 milhão de controllers instanciados, o Get sempre te entregará o controller correto. Apenas se lembre de Tipar seu controller, final controller = Get.find(); por exemplo, não irá funcionar. | 655 | +//Yes, it looks like Magic, Get will find your controller, and will deliver it to you. You can have 1 million controllers instantiated, Get will always give you the right controller. |
274 | ``` | 656 | ``` |
275 | -E então você poderá recuperar os dados do seu controlador obtidos lá: | 657 | +And then you will be able to recover your controller data that was obtained back there: |
276 | 658 | ||
277 | ```dart | 659 | ```dart |
278 | Text(controller.textFromApi); | 660 | Text(controller.textFromApi); |
279 | ``` | 661 | ``` |
280 | 662 | ||
281 | -Quer liberar recursos? Para remover uma instância do Get, apenas delete ela: | 663 | +Looking for lazy loading? You can declare all your controllers, and it will be called only when someone needs it. You can do this with: |
664 | +```dart | ||
665 | +Get.lazyPut<Service>(()=> ApiMock()); | ||
666 | +/// ApiMock will only be called when someone uses Get.find<Service> for the first time | ||
667 | +``` | ||
282 | 668 | ||
669 | +To remove a instance of Get: | ||
283 | ```dart | 670 | ```dart |
284 | -Controller controller = Get.delete(Controller()); | 671 | +Get.delete<Controller>(); |
285 | ``` | 672 | ``` |
286 | -Pronto, você consegue fazer mais com menos código, diminuiu o tamanho de código do seu app, e agora tem um gerenciador de instâncias ultra leve, com apenas 1 biblioteca. | ||
287 | 673 | ||
288 | -## Navegando com rotas nomeadas: | ||
289 | -- Se você prefere navegar por rotas nomeadas, o Get também dá suporte a isso. | ||
290 | 674 | ||
291 | -Para navegar para uma nova tela | 675 | +## Navigate with named routes: |
676 | +- If you prefer to navigate by namedRoutes, Get also supports this. | ||
677 | + | ||
678 | +To navigate to nextScreen | ||
292 | ```dart | 679 | ```dart |
293 | Get.toNamed("/NextScreen"); | 680 | Get.toNamed("/NextScreen"); |
294 | ``` | 681 | ``` |
295 | -Para navegar para uma tela sem a opção de voltar para a rota atual. | 682 | +To navigate and remove the previous screen from the tree. |
296 | ```dart | 683 | ```dart |
297 | Get.offNamed("/NextScreen"); | 684 | Get.offNamed("/NextScreen"); |
298 | ``` | 685 | ``` |
299 | -Para navegar para uma nova tela e remover todas rotas anteriores da stack | 686 | +To navigate and remove all previous screens from the tree. |
300 | ```dart | 687 | ```dart |
301 | Get.offAllNamed("/NextScreen"); | 688 | Get.offAllNamed("/NextScreen"); |
302 | ``` | 689 | ``` |
303 | 690 | ||
304 | -### Enviando dados por rotas nomeadas: | 691 | +To define routes, use GetMaterialApp: |
692 | + | ||
693 | +```dart | ||
694 | +void main() { | ||
695 | + runApp(GetMaterialApp( | ||
696 | + initialRoute: '/', | ||
697 | + namedRoutes: { | ||
698 | + '/': GetRoute(page: MyHomePage()), | ||
699 | + '/second': GetRoute(page: Second()), | ||
700 | + '/third': GetRoute(page: Third(),transition: Transition.cupertino); | ||
701 | + }, | ||
702 | + )); | ||
703 | +} | ||
704 | +``` | ||
705 | + | ||
706 | +### Send data to named Routes: | ||
305 | 707 | ||
306 | -Apenas envie o que você quiser por argumentos. Get aceita qualquer coisa aqui, não importa se é uma String, um Map, uma List, int ou até uma instancia de classe. | 708 | +Just send what you want for arguments. Get accepts anything here, whether it is a String, a Map, a List, or even a class instance. |
307 | ```dart | 709 | ```dart |
308 | Get.toNamed("/NextScreen", arguments: 'Get is the best'); | 710 | Get.toNamed("/NextScreen", arguments: 'Get is the best'); |
309 | ``` | 711 | ``` |
310 | -Agora você pode recuperar em sua classe ou em seu controller: | 712 | +on your class or controller: |
311 | 713 | ||
312 | ```dart | 714 | ```dart |
313 | print(Get.arguments); | 715 | print(Get.arguments); |
314 | //print out: Get is the best | 716 | //print out: Get is the best |
315 | ``` | 717 | ``` |
316 | 718 | ||
317 | -## Configurando rotas nomeadas e adicionando suporte completo à urls amigáveis do Flutter Web | 719 | +#### Dynamic urls links |
720 | +Get offer advanced dynamic urls just like on the Web. Web developers have probably already wanted this feature on Flutter, and most likely have seen a package promise this feature and deliver a totally different syntax than a URL would have on web, but Get also solves that. | ||
318 | 721 | ||
319 | -### Se você ainda não adicionou " navigatorKey: Get.key," ao seu MaterialApp, faça agora. aproveite para adicionar uma "initialRoute" e o seu "onGenerateRoute". | 722 | +```dart |
723 | +Get.offAllNamed("/NextScreen?device=phone&id=354&name=Enzo"); | ||
724 | +``` | ||
725 | +on your controller/bloc/stateful/stateless class: | ||
726 | + | ||
727 | +```dart | ||
728 | +print(Get.parameters['id']); | ||
729 | +// out: 354 | ||
730 | +print(Get.parameters['name']); | ||
731 | +// out: Enzo | ||
732 | +``` | ||
733 | + | ||
734 | +You can also receive NamedParameters with Get easily: | ||
320 | 735 | ||
321 | ```dart | 736 | ```dart |
322 | void main() { | 737 | void main() { |
323 | - runApp(MaterialApp( | ||
324 | - onGenerateRoute: Router.generateRoute, | ||
325 | - initialRoute: "/", | ||
326 | - navigatorKey: Get.key, | ||
327 | - title: 'Navigation', | 738 | + runApp(GetMaterialApp( |
739 | + initialRoute: '/', | ||
740 | + namedRoutes: { | ||
741 | + '/': GetRoute(page: MyHomePage()), | ||
742 | + /// Important! :user is not a new route, it is just a parameter | ||
743 | + /// specification. Do not use '/second/:user' and '/second' | ||
744 | + /// if you need new route to user, use '/second/user/:user' | ||
745 | + /// if '/second' is a route. | ||
746 | + '/second/:user': GetRoute(page: Second()), // receive ID | ||
747 | + '/third': GetRoute(page: Third(),transition: Transition.cupertino); | ||
748 | + }, | ||
328 | )); | 749 | )); |
329 | } | 750 | } |
330 | ``` | 751 | ``` |
331 | -Crie uma classe para gerenciar suas rotas nomeadas, você pode (e deve) copiar esse exemplo | ||
332 | - | ||
333 | -```dart | ||
334 | -class Router { | ||
335 | - static Route<dynamic> generateRoute(RouteSettings settings) { | ||
336 | - switch (settings.name) { | ||
337 | - case '/': | ||
338 | - return GetRoute( | ||
339 | - page: First(), | ||
340 | - settings: settings, | ||
341 | - ); | ||
342 | - case '/second': | ||
343 | - return GetRoute( | ||
344 | - settings: settings, page: Second(), transition: Transition.fade); | ||
345 | - case '/third': | ||
346 | - return GetRoute( | ||
347 | - settings: settings, | ||
348 | - page: Third(), | ||
349 | - popGesture: true, | ||
350 | - transition: Transition.cupertino); | ||
351 | - default: | ||
352 | - return GetRoute( | ||
353 | - settings: settings, | ||
354 | - transition: Transition.fade, | ||
355 | - page: Scaffold( | ||
356 | - body: | ||
357 | - Center(child: Text('No route defined for ${settings.name}')), | ||
358 | - )); | ||
359 | - } | ||
360 | - } | ||
361 | -} | 752 | +Send data on route name |
753 | +```dart | ||
754 | +Get.toNamed("/second/34954"); | ||
755 | +``` | ||
756 | + | ||
757 | +On second screen take the data by parameter | ||
758 | + | ||
759 | +```dart | ||
760 | +print(Get.parameters['user']); | ||
761 | +// out: 34954 | ||
362 | ``` | 762 | ``` |
363 | 763 | ||
364 | -E agora, tudo que você precisa fazer é usar Get.toNamed() para navegar pelas rotas nomeadas, sem qualquer context (você pode chamar suas rotas diretamente da sua classe BLoC ou Controller) e, quando o aplicativo for compilado na Web, suas rotas aparecerão na URL <3 | 764 | +And now, all you need to do is use Get.toNamed() to navigate your named routes, without any context (you can call your routes directly from your BLoC or Controller class), and when your app is compiled to the web, your routes will appear in the url <3 |
765 | + | ||
365 | 766 | ||
366 | #### Middleware | 767 | #### Middleware |
367 | -Se você deseja ouvir eventos de navegação para acionar ações, é possível adicionar um GetObserver ao seu materialApp. Isso é extremamente útil para acionar eventos sempre que uma tela específica é exibida na tela. Atualmente no Flutter, você teria que colocar o evento no initState e aguardar uma possível resposta em um navigator.pop (context); para conseguir isso. Mas com o Get, isso é extremamente simples! | 768 | +If you want listen Get events to trigger actions, you can to use routingCallback to it |
769 | +```dart | ||
770 | +GetMaterialApp( | ||
771 | + routingCallback: (route){ | ||
772 | + if(routing.current == '/second'){ | ||
773 | + openAds(); | ||
774 | + } | ||
775 | + } | ||
776 | + ``` | ||
777 | +If you are not using GetMaterialApp, you can use the manual API to attach Middleware observer. | ||
778 | + | ||
368 | 779 | ||
369 | -##### add GetObserver(); | ||
370 | ```dart | 780 | ```dart |
371 | void main() { | 781 | void main() { |
372 | runApp(MaterialApp( | 782 | runApp(MaterialApp( |
@@ -384,9 +794,9 @@ Create a MiddleWare class | @@ -384,9 +794,9 @@ Create a MiddleWare class | ||
384 | ```dart | 794 | ```dart |
385 | class MiddleWare { | 795 | class MiddleWare { |
386 | static observer(Routing routing) { | 796 | static observer(Routing routing) { |
387 | - /// Você pode ouvir além das rotas, snackbars, caixas de diálogo e bottomsheets em cada tela. | ||
388 | - /// Se você precisar inserir qualquer um desses 3 eventos diretamente aqui, | ||
389 | - /// você deve especificar que o evento é != Do que você está tentando fazer ou você terá um loop. | 797 | + /// You can listen in addition to the routes, the snackbars, dialogs and bottomsheets on each screen. |
798 | + ///If you need to enter any of these 3 events directly here, | ||
799 | + ///you must specify that the event is != Than you are trying to do. | ||
390 | if (routing.current == '/second' && !routing.isSnackbar) { | 800 | if (routing.current == '/second' && !routing.isSnackbar) { |
391 | Get.snackbar("Hi", "You are on second route"); | 801 | Get.snackbar("Hi", "You are on second route"); |
392 | } else if (routing.current =='/third'){ | 802 | } else if (routing.current =='/third'){ |
@@ -395,7 +805,8 @@ class MiddleWare { | @@ -395,7 +805,8 @@ class MiddleWare { | ||
395 | } | 805 | } |
396 | } | 806 | } |
397 | ``` | 807 | ``` |
398 | -Agora é só usar o Get em seu código: | 808 | + |
809 | +Now, use Get on your code: | ||
399 | 810 | ||
400 | ```dart | 811 | ```dart |
401 | class First extends StatelessWidget { | 812 | class First extends StatelessWidget { |
@@ -468,68 +879,120 @@ class Third extends StatelessWidget { | @@ -468,68 +879,120 @@ class Third extends StatelessWidget { | ||
468 | } | 879 | } |
469 | ``` | 880 | ``` |
470 | 881 | ||
882 | +### Change Theme | ||
883 | +Please do not use any higher level widget than GetMaterialApp in order to update it. This can trigger duplicate keys. A lot of people are used to the prehistoric approach of creating a "ThemeProvider" widget just to change the theme of your app, and this is definitely NOT necessary with Get. | ||
884 | + | ||
885 | +You can create your custom theme and simply add it within Get.changeTheme without any boilerplate for that: | ||
886 | + | ||
887 | + | ||
888 | +```dart | ||
889 | +Get.changeTheme(ThemeData.light()); | ||
890 | +``` | ||
891 | + | ||
892 | +If you want to create something like a button that changes the theme with onTap, you can combine two Get APIs for that, the api that checks if the dark theme is being used, and the theme change API, you can just put this within an onPressed: | ||
893 | + | ||
894 | +```dart | ||
895 | +Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark()); | ||
896 | +``` | ||
897 | + | ||
898 | +When darkmode is activated, it will switch to the light theme, and when the light theme is activated, it will change to dark. | ||
899 | + | ||
900 | + | ||
901 | +If you want to know in depth how to change the theme, you can follow this tutorial on Medium that even teaches the persistence of the theme using Get: | ||
902 | + | ||
903 | +- [Dynamic Themes in 3 lines using Get](https://medium.com/swlh/flutter-dynamic-themes-in-3-lines-c3b375f292e3) - Tutorial by [Rod Brown](https://github.com/RodBr). | ||
904 | + | ||
905 | + | ||
906 | +### Optional Global Settings | ||
907 | +You can create Global settings for Get. Just add Get.config to your code before pushing any route or do it directly in your GetMaterialApp | ||
908 | + | ||
909 | +```dart | ||
910 | + | ||
911 | +GetMaterialApp( | ||
912 | + enableLog: true, | ||
913 | + defaultTransition: Transition.fade, | ||
914 | + opaqueRoute: Get.isOpaqueRouteDefault, | ||
915 | + popGesture: Get.isPopGestureEnable, | ||
916 | + transitionDuration: Get.defaultDurationTransition, | ||
917 | + defaultGlobalState: Get.defaultGlobalState, | ||
918 | + ); | ||
471 | 919 | ||
472 | -### APIs Avançadas | ||
473 | -A cada dia, o Get fica mais longe do Framework padrão e fornece uma gama mais ampla de recursos que são impensáveis de serem executados usando o Flutter padrão. | ||
474 | -Com o Get 1.17.0, foi lançada uma série de novas APIs, que permitem por exemplo, o acesso dos argumentos de uma rota nomeada de qualquer lugar do código, se há alguma snackbar ou caixa de diálogo aberta naquele momento ou qual tela está sendo exibida para o usuário. | ||
475 | -Este é um grande passo para desanexar completamente a navegação Flutter de InheritedWidgets. Usar o contexto para acessar o InheritedWidget para usar um recurso simples de navegação é uma das únicas coisas chatas que se pode encontrar nessa estrutura incrível que é o Flutter. Agora, o Get resolveu esse problema, tornou-se onisciente e você terá acesso a basicamente qualquer ferramenta do Flutter que está disponível apenas na árvore de widgets usando o Get. | 920 | +Get.config( |
921 | + enableLog = true, | ||
922 | + defaultPopGesture = true, | ||
923 | + defaultTransition = Transitions.cupertino} | ||
924 | +``` | ||
476 | 925 | ||
477 | -Todas as APIs disponíveis aqui estão na fase beta; elas são totalmente funcionais, passaram em testes internos, mas como foram recém lançadas, não tem maturidade suficiente para garantir sua estabilidade. Get é totalmente estável (quase sempre issues abertas são solicitações de recursos, quase nunca bugs), mas esse conjunto de APIs foi lançado recentemente, portanto, se você encontrar algum erro aqui, abra um problema ou ofereça um PR. | ||
478 | 926 | ||
479 | -- Obrigatório: para ter acesso a essa API, você deve obrigatoriamente inserir o GetObserver em seu MaterialApp | 927 | +### Other Advanced APIs and Manual configurations |
928 | +GetMaterialApp configures everything for you, but if you want to configure Get Manually using advanced APIs. | ||
480 | 929 | ||
481 | ```dart | 930 | ```dart |
482 | MaterialApp( | 931 | MaterialApp( |
483 | navigatorKey: Get.key, | 932 | navigatorKey: Get.key, |
484 | - navigatorObservers: [GetObserver()], // COLOQUE AQUI !!!! | 933 | + navigatorObservers: [GetObserver()], |
485 | ); | 934 | ); |
486 | ``` | 935 | ``` |
487 | 936 | ||
488 | -Você também poderá usar seu próprio Middleware no GetObserver, isso não influenciará em nada. | 937 | +You will also be able to use your own Middleware within GetObserver, this will not influence anything. |
489 | 938 | ||
490 | ```dart | 939 | ```dart |
491 | MaterialApp( | 940 | MaterialApp( |
492 | navigatorKey: Get.key, | 941 | navigatorKey: Get.key, |
493 | - navigatorObservers: [GetObserver(MiddleWare.observer)], // AQUI | 942 | + navigatorObservers: [GetObserver(MiddleWare.observer)], // Here |
494 | ); | 943 | ); |
495 | ``` | 944 | ``` |
496 | 945 | ||
497 | -Principais APIs: | ||
498 | - | ||
499 | ```dart | 946 | ```dart |
500 | -Get.arguments // Te dá os argumentos da rota aberta em qualquer lugar do seu código. | ||
501 | - // você não precisa mais recebê-los, inicializa-los no seu initState e enviar por parâmetro ao seu controller/Bloc, Get é onisciente, ele sabe exatamente qual rota está aberta e quais argumentos enviados para ela. Você pode usar isso diretamente no seu controller/bloc sem medo. | 947 | +Get.arguments // give the current args from currentScreen |
948 | + | ||
949 | +Get.previousArguments // give arguments of previous route | ||
950 | + | ||
951 | +Get.previousRoute // give name of previous route | ||
952 | + | ||
953 | +Get.rawRoute // give the raw route to access for example, rawRoute.isFirst() | ||
954 | + | ||
955 | +Get.routing // give access to Rounting API from GetObserver | ||
956 | + | ||
957 | +Get.isSnackbarOpen // check if snackbar is open | ||
958 | + | ||
959 | +Get.isDialogOpen // check if dialog is open | ||
502 | 960 | ||
503 | -Get.previousArguments // Te dá os argumentos da rota anterior. | 961 | +Get.isBottomSheetOpen // check if bottomsheet is open |
504 | 962 | ||
505 | -Get.previousRoute // Te dá o nome da rota anterior | 963 | +Get.removeRoute() // remove one route. |
506 | 964 | ||
507 | -Get.rawRoute // te dá acesso à rota crua, para explorar APIs de baixo nível | 965 | +Get.until() // back repeatedly until the predicate returns true. |
508 | 966 | ||
509 | -Get.routing // te dá acesso à Rounting API do GetObserver | 967 | +Get.offUntil() // go to next route and remove all the previous routes until the predicate returns true. |
510 | 968 | ||
511 | -Get.isSnackbarOpen // verifique se a snackbar está sendo exibida na tela | 969 | +Get.offNamedUntil() // go to next named route and remove all the previous routes until the predicate returns true. |
512 | 970 | ||
513 | -Get.isDialogOpen // verifique se a caixa de diálogo está sendo exibida na tela | 971 | +GetPlatform.isAndroid/isIOS/isWeb... //(This method is completely compatible with FlutterWeb, unlike the framework. "Platform.isAndroid") |
514 | 972 | ||
515 | -Get.isBottomSheetOpen // verifique se a bottomsheet está sendo exibida na tela | 973 | +Get.height / Get.width // Equivalent to the method: MediaQuery.of(context).size.height |
516 | 974 | ||
975 | +Get.context // Gives the context of the screen in the foreground anywhere in your code. | ||
976 | + | ||
977 | +Get.contextOverlay // Gives the context of the snackbar/dialog/bottomsheet in the foreground anywhere in your code. | ||
517 | 978 | ||
518 | ``` | 979 | ``` |
980 | + | ||
519 | ### Nested Navigators | 981 | ### Nested Navigators |
520 | 982 | ||
521 | -Get fez a navegação aninhada do Flutter ainda mais fácil. | ||
522 | -Você não precisa do contexto e encontrará sua pilha de navegação por um ID exclusivo. | 983 | +Get made Flutter's nested navigation even easier. |
984 | +You don't need the context, and you will find your navigation stack by Id. | ||
523 | 985 | ||
524 | -Veja como é simples: | 986 | +- NOTE: Creating parallel navigation stacks can be dangerous. The ideal is not to use NestedNavigators, or to use sparingly. If your project requires it, go ahead, but keep in mind that keeping multiple navigation stacks in memory may not be a good idea for RAM consumption. |
525 | 987 | ||
988 | +See how simple it is: | ||
526 | ```dart | 989 | ```dart |
527 | Navigator( | 990 | Navigator( |
528 | - key: nestedKey(1), // crie sua key por um index | 991 | + key: nestedKey(1), // create a key by index |
529 | initialRoute: '/', | 992 | initialRoute: '/', |
530 | onGenerateRoute: (settings) { | 993 | onGenerateRoute: (settings) { |
531 | if (settings.name == '/') { | 994 | if (settings.name == '/') { |
532 | - return GetRoute( | 995 | + return GetRouteBase( |
533 | page: Scaffold( | 996 | page: Scaffold( |
534 | appBar: AppBar( | 997 | appBar: AppBar( |
535 | title: Text("Main"), | 998 | title: Text("Main"), |
@@ -538,14 +1001,14 @@ Veja como é simples: | @@ -538,14 +1001,14 @@ Veja como é simples: | ||
538 | child: FlatButton( | 1001 | child: FlatButton( |
539 | color: Colors.blue, | 1002 | color: Colors.blue, |
540 | onPressed: () { | 1003 | onPressed: () { |
541 | - Get.toNamed('/second', 1); // navegue por sua rota aninhada usando o index | 1004 | + Get.toNamed('/second', id:1); // navigate by your nested route by index |
542 | }, | 1005 | }, |
543 | child: Text("Go to second")), | 1006 | child: Text("Go to second")), |
544 | ), | 1007 | ), |
545 | ), | 1008 | ), |
546 | ); | 1009 | ); |
547 | } else if (settings.name == '/second') { | 1010 | } else if (settings.name == '/second') { |
548 | - return GetRoute( | 1011 | + return GetRouteBase( |
549 | page: Center( | 1012 | page: Center( |
550 | child: Scaffold( | 1013 | child: Scaffold( |
551 | appBar: AppBar( | 1014 | appBar: AppBar( |
@@ -562,27 +1025,4 @@ Veja como é simples: | @@ -562,27 +1025,4 @@ Veja como é simples: | ||
562 | ``` | 1025 | ``` |
563 | 1026 | ||
564 | 1027 | ||
565 | -### Outras APIs: | ||
566 | -Desde quando essa biblioteca foi criada, reuni meus esforços para adicionar novos recursos e torná-la mais estável possível. Com isso, ainda há algumas APIs disponíveis que ainda não foram documentadas. Meu tempo é escasso, então vou resumir as principais aqui: | ||
567 | - | ||
568 | -```dart | ||
569 | -Get.removeRoute() // remove uma rota | ||
570 | - | ||
571 | -Get.until() // volta repetidamente até o predicado ser verdadeiro | ||
572 | - | ||
573 | -Get.offUntil() // vá para a próxima rota e remova todas as rotas anteriores até que o predicado retornar verdadeiro. | ||
574 | - | ||
575 | -Get.offNamedUntil() // vá para a próxima rota nomeada e remova todas as rotas anteriores até que o predicado retorne verdadeiro (namedRoutes) | ||
576 | - | ||
577 | -GetPlatform.isAndroid/isIOS/isWeb... //(Este método é totalmente compatível com o FlutterWeb, diferente do padrão "Platform.isAndroid" que usa dart:io) | ||
578 | - | ||
579 | -Get.height / Get.width // Equivalente ao método: MediaQuery.of(context).size.height //width | ||
580 | - | ||
581 | -Get.context // Fornece o contexto da tela em primeiro plano em qualquer lugar do seu código. | ||
582 | - | ||
583 | -Get.overlayContext // Fornece o contexto do dialogo/snackbar/bottomsheet em primeiro plano em qualquer lugar do seu código. | ||
584 | - | ||
585 | - | ||
586 | -``` | ||
587 | - | ||
588 | -Essa biblioteca será sempre atualizada e implementando novos recursos. Sinta-se livre para oferecer PRs e contribuir com ela. | 1028 | +This library will always be updated and implementing new features. Feel free to offer PRs and contribute to them. |
-
Please register or login to post a comment