Showing
1 changed file
with
0 additions
and
1188 deletions
.history/README-vi_20210522092000.md
deleted
100644 → 0
1 | - | ||
2 | - | ||
3 | -**Ngôn ngữ: Tiếng Việt (file này), [English](README.md), [Indonesian](README.id-ID.md), [Urdu](README.ur-PK.md), [Chinese](README.zh-cn.md), [Brazilian Portuguese](README.pt-br.md), [Spanish](README-es.md), [Russian](README.ru.md), [Polish](README.pl.md), [Korean](README.ko-kr.md), [French](README-fr.md).** | ||
4 | - | ||
5 | -[](https://pub.dev/packages/get) | ||
6 | -[](https://pub.dev/packages/get/score) | ||
7 | - | ||
8 | -[](https://pub.dev/packages/effective_dart) | ||
9 | -[](https://discord.com/invite/9Hpt99N) | ||
10 | -[](https://communityinviter.com/apps/getxworkspace/getx) | ||
11 | -[](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g) | ||
12 | -<a href="https://github.com/Solido/awesome-flutter"> | ||
13 | -<img alt="Awesome Flutter" src="https://img.shields.io/badge/Awesome-Flutter-blue.svg?longCache=true&style=flat-square" /> | ||
14 | -</a> | ||
15 | -<a href="https://www.buymeacoffee.com/jonataslaw" target="_blank"><img src="https://i.imgur.com/aV6DDA7.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important; box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" > </a> | ||
16 | - | ||
17 | - | ||
18 | - | ||
19 | -- [Về Getx](#about-get) | ||
20 | -- [Cài Đặt](#installing) | ||
21 | -- [Counter App với GetX](#counter-app-with-getx) | ||
22 | -- [Tam Trụ](#the-three-pillars) | ||
23 | - - [Quản lý State](#state-management) | ||
24 | - - [Reactive State Manager](#reactive-state-manager) | ||
25 | - - [Thêm thông tin về quản lý state](#more-details-about-state-management) | ||
26 | - - [Quản lý route](#route-management) | ||
27 | - - [Thêm thông tin về quản lý route](#more-details-about-route-management) | ||
28 | - - [Quản lý dependency](#dependency-management) | ||
29 | - - [More details about dependency management](#more-details-about-dependency-management) | ||
30 | -- [Utils](#utils) | ||
31 | - - [Internationalization](#internationalization) | ||
32 | - - [Translations](#translations) | ||
33 | - - [Using translations](#using-translations) | ||
34 | - - [Locales](#locales) | ||
35 | - - [Change locale](#change-locale) | ||
36 | - - [System locale](#system-locale) | ||
37 | - - [Change Theme](#change-theme) | ||
38 | - - [GetConnect](#getconnect) | ||
39 | - - [Default configuration](#default-configuration) | ||
40 | - - [Custom configuration](#custom-configuration) | ||
41 | - - [GetPage Middleware](#getpage-middleware) | ||
42 | - - [Priority](#priority) | ||
43 | - - [Redirect](#redirect) | ||
44 | - - [onPageCalled](#onpagecalled) | ||
45 | - - [OnBindingsStart](#onbindingsstart) | ||
46 | - - [OnPageBuildStart](#onpagebuildstart) | ||
47 | - - [OnPageBuilt](#onpagebuilt) | ||
48 | - - [OnPageDispose](#onpagedispose) | ||
49 | - - [Other Advanced APIs](#other-advanced-apis) | ||
50 | - - [Optional Global Settings and Manual configurations](#optional-global-settings-and-manual-configurations) | ||
51 | - - [Local State Widgets](#local-state-widgets) | ||
52 | - - [ValueBuilder](#valuebuilder) | ||
53 | - - [ObxValue](#obxvalue) | ||
54 | - - [Useful tips](#useful-tips) | ||
55 | - - [GetView](#getview) | ||
56 | - - [GetResponsiveView](#getresponsiveview) | ||
57 | - - [Hướng dẫn sử dụng trước khi dùng](#how-to-use-it) | ||
58 | - - [GetWidget](#getwidget) | ||
59 | - - [GetxService](#getxservice) | ||
60 | -- [Breaking changes from 2.0](#breaking-changes-from-20) | ||
61 | -- [Why Getx?](#why-getx) | ||
62 | -- [Community](#community) | ||
63 | - - [Community channels](#community-channels) | ||
64 | - - [How to contribute](#how-to-contribute) | ||
65 | - - [Articles and videos](#articles-and-videos) | ||
66 | - | ||
67 | -# Về Getx | ||
68 | - | ||
69 | -- GetX hướng tới sự nhỏ gọn và giải pháp tối ưu cho Flutter với tốc độ ưu việt trong quản lý state, nạp dependency thông minh, và quản lý route nhanh chóng và thực tế. | ||
70 | - | ||
71 | -- GetX hướng tới 3 tham vọng chính, nghĩa là tất cả các tài nguyên của thư viện sẽ dành cho những điểm ưu tiên sau: **NĂNG SUẤT, HIỆU SUẤT VÀ TỔ CHỨC.** | ||
72 | - | ||
73 | - - **HIỆU SUẤT:** GetX tập trung vào hiệu suất và mức tiêu thụ tài nguyên tối thiểu, do đó nó không sử dụng Streams hoặc ChangeNotifier. | ||
74 | - | ||
75 | - - **NĂNG SUẤT:** GetX sử dụng một cú pháp dễ dàng và dễ thở. Bất kể bạn muốn làm gì, luôn có một cách dễ dàng hơn với GetX. Nó sẽ tiết kiệm hàng giờ phát triển và sẽ cung cấp hiệu suất tối đa mà ứng dụng của bạn có thể mang lại. | ||
76 | - | ||
77 | - Nói chung, nhà phát triển nên quan tâm đến việc xóa controller ra khỏi memory. Với GetX, các tài nguyên sẽ | ||
78 | - TỰ ĐỘNG xóa khỏi memory khi không dùng theo mặc định. Nếu bạn muốn giữ nó trong memory, bạn phải khai báo rõ ràng "permanent: true" trong phần dependency của mình. Từ đó, bạn sẽ tiết kiệm thời gian và ít phụ thuộc vào memory. Theo mặc định, tính năng tải dependency cũng lười biếng. | ||
79 | - | ||
80 | - - **TỔ CHỨC:** | ||
81 | - GetX cho phép tách toàn bộ Chế độ xem, presentation logic, business logic, nạp dependencies và điều hướng. Bạn không "context" để điều hướng giữa các route, vì vậy bạn sẽ độc lập trong sơ đồ widget (trực quan hóa). Bạn không cần "context" để truy cập Controller / Blocs của mình thông qua một InheritedWidget, vì vậy bạn hoàn toàn tách rời presentation logic và business logic khỏi lớp trực quan của mình. Bạn không cần phải đưa các Controller / Models / Blocs vào sơ đồ widget của mình thông qua `MultiProvider`, vì GetX sử dụng tính năng nạp dependency của riêng nó, tách hoàn toàn DI khỏi chế độ xem của nó. | ||
82 | - | ||
83 | - Với GetX, bạn biết nơi tìm từng tính năng ứng dụng của mình, với cơ chế clean code theo mặc định. Ngoài việc giúp bảo trì dễ dàng, GetX giúp việc chia sẻ các mô-đun trở thành khả thi trong Flutter. | ||
84 | - BLoC là điểm khởi đầu để tổ chức code trong Flutter, nó tách biệt logic nghiệp vụ với trực quan. GetX nảy sinh từ điều này, không chỉ tách biệt presentation logic mà còn cả business logic. Nạp dependency bổ sung và route cũng được tách ra và lớp dữ liệu cũng biến mất. Bạn sẽ biết mọi thứ ở đâu và sẽ hình dung tất cả những điều này dễ hơn cả "Hello World". | ||
85 | - GetX là cách dễ nhất, thiết thực và có thể mở rộng để xây dựng các ứng dụng hiệu suất cao với Flutter SDK. GetX chứa đựng một hệ sinh thái rộng lớn xung quanh nó hoạt động hoàn hảo cùng nhau, rất dễ dàng cho người mới bắt đầu và nó chính xác cho các chuyên gia. Nó an toàn, ổn định, cập nhật và cung cấp một loạt các API được tích hợp sẵn mà không có trong Flutter SDK mặc định. | ||
86 | - | ||
87 | -- GetX không cồng kềnh và có vô số tính năng cho phép bạn bắt đầu lập trình mà không cần lo lắng về bất cứ điều gì. Đặc biệt, nó cho phép mỗi tính năng này nằm trong các vùng chứa riêng biệt và chỉ được bắt đầu sau khi sử dụng. Nếu bạn chỉ sử dụng quản lý state thì sẽ chỉ có quản lý state được sử dụng. Nếu bạn chỉ sử dụng route, thì GetX không complie quản lý state. | ||
88 | - | ||
89 | -- GetX có một hệ sinh thái khổng lồ, một cộng đồng lớn, một số lượng lớn cộng tác viên và sẽ được duy trì miễn là Flutter còn tồn tại. GetX có khả năng chạy đồng dạng trên Android, iOS, Web, Mac, Linux, Windows và trên máy chủ của bạn. | ||
90 | - **Bạn hoàn toàn có thể sử dụng lại mã của mình trên frontend qua backend với [Get Server](https://github.com/jonataslaw/get_server)**. | ||
91 | - | ||
92 | -**Ngoài ra, toàn bộ quá trình phát triển có thể hoàn toàn tự động, cả trên máy chủ và frontend với [Get CLI](https://github.com/jonataslaw/get_cli)**. | ||
93 | - | ||
94 | -**Ngoài ra, nhằm tăng thêm năng suất của bạn, chúng tôi hỗ trợ | ||
95 | -[extension to VSCode](https://marketplace.visualstudio.com/items?itemName=get-snippets.get-snippets) và [extension to Android Studio/Intellij](https://plugins.jetbrains.com/plugin/14975-getx-snippets)** | ||
96 | - | ||
97 | -# Cài Đặt | ||
98 | - | ||
99 | -Thêm Get vào pubspec.yaml file: | ||
100 | - | ||
101 | -```yaml | ||
102 | -dependencies: | ||
103 | - get: | ||
104 | -``` | ||
105 | - | ||
106 | -Import get vào file cần sử dụng: | ||
107 | - | ||
108 | -```dart | ||
109 | -import 'package:get/get.dart'; | ||
110 | -``` | ||
111 | - | ||
112 | -# Counter App with GetX | ||
113 | - | ||
114 | -Dự án "counter" được tạo theo mặc định trên dự án mới trên Flutter có hơn 100 dòng (có comments). Để thể hiện sức mạnh của Get, tôi sẽ trình bày cách tạo "counter" thay đổi trạng thái với mỗi lần nhấp, chuyển đổi giữa các trang và chia sẻ trạng thái giữa các màn hình, tất cả đều theo cách có tổ chức, tách biệt logic nghiệp vụ khỏi chế độ xem, CHỈ VỚI 26 DÒNG! | ||
115 | - | ||
116 | -- Step 1: | ||
117 | - Thêm "Get" trước MaterialApp, nó sẽ thành GetMaterialApp | ||
118 | - | ||
119 | -```dart | ||
120 | -void main() => runApp(GetMaterialApp(home: Home())); | ||
121 | -``` | ||
122 | - | ||
123 | -- Note: this does not modify the MaterialApp of the Flutter, GetMaterialApp is not a modified MaterialApp, it is just a pre-configured Widget, which has the default MaterialApp as a child. You can configure this manually, but it is definitely not necessary. GetMaterialApp will create routes, inject them, inject translations, inject everything you need for route navigation. If you use Get only for state management or dependency management, it is not necessary to use GetMaterialApp. GetMaterialApp is necessary for routes, snackbars, internationalization, bottomSheets, dialogs, and high-level apis related to routes and absence of context. | ||
124 | -- Note²: This step is only necessary if you gonna use route management (`Get.to()`, `Get.back()` and so on). If you not gonna use it then it is not necessary to do step 1 | ||
125 | - | ||
126 | -- Step 2: | ||
127 | - Create your business logic class and place all variables, methods and controllers inside it. | ||
128 | - You can make any variable observable using a simple ".obs". | ||
129 | - | ||
130 | -```dart | ||
131 | -class Controller extends GetxController{ | ||
132 | - var count = 0.obs; | ||
133 | - increment() => count++; | ||
134 | -} | ||
135 | -``` | ||
136 | - | ||
137 | -- Step 3: | ||
138 | - Create your View, use StatelessWidget and save some RAM, with Get you may no longer need to use StatefulWidget. | ||
139 | - | ||
140 | -```dart | ||
141 | -class Home extends StatelessWidget { | ||
142 | - | ||
143 | - @override | ||
144 | - Widget build(context) { | ||
145 | - | ||
146 | - // Instantiate your class using Get.put() to make it available for all "child" routes there. | ||
147 | - final Controller c = Get.put(Controller()); | ||
148 | - | ||
149 | - return Scaffold( | ||
150 | - // Use Obx(()=> to update Text() whenever count is changed. | ||
151 | - appBar: AppBar(title: Obx(() => Text("Clicks: ${c.count}"))), | ||
152 | - | ||
153 | - // Replace the 8 lines Navigator.push by a simple Get.to(). You don't need context | ||
154 | - body: Center(child: ElevatedButton( | ||
155 | - child: Text("Go to Other"), onPressed: () => Get.to(Other()))), | ||
156 | - floatingActionButton: | ||
157 | - FloatingActionButton(child: Icon(Icons.add), onPressed: c.increment)); | ||
158 | - } | ||
159 | -} | ||
160 | - | ||
161 | -class Other extends StatelessWidget { | ||
162 | - // You can ask Get to find a Controller that is being used by another page and redirect you to it. | ||
163 | - final Controller c = Get.find(); | ||
164 | - | ||
165 | - @override | ||
166 | - Widget build(context){ | ||
167 | - // Access the updated count variable | ||
168 | - return Scaffold(body: Center(child: Text("${c.count}"))); | ||
169 | - } | ||
170 | -} | ||
171 | -``` | ||
172 | - | ||
173 | -Result: | ||
174 | - | ||
175 | - | ||
176 | - | ||
177 | -This is a simple project but it already makes clear how powerful Get is. As your project grows, this difference will become more significant. | ||
178 | - | ||
179 | -Get was designed to work with teams, but it makes the job of an individual developer simple. | ||
180 | - | ||
181 | -Improve your deadlines, deliver everything on time without losing performance. Get is not for everyone, but if you identified with that phrase, Get is for you! | ||
182 | - | ||
183 | -# Tam Trụ | ||
184 | - | ||
185 | -## Quản lý State | ||
186 | - | ||
187 | -Get has two different state managers: the simple state manager (we'll call it GetBuilder) and the reactive state manager (GetX/Obx) | ||
188 | - | ||
189 | -### Reactive State Manager | ||
190 | - | ||
191 | -Reactive programming can alienate many people because it is said to be complicated. GetX turns reactive programming into something quite simple: | ||
192 | - | ||
193 | -- You won't need to create StreamControllers. | ||
194 | -- You won't need to create a StreamBuilder for each variable | ||
195 | -- You will not need to create a class for each state. | ||
196 | -- You will not need to create a get for an initial value. | ||
197 | -- You will not need to use code generators | ||
198 | - | ||
199 | -Reactive programming with Get is as easy as using setState. | ||
200 | - | ||
201 | -Let's imagine that you have a name variable and want that every time you change it, all widgets that use it are automatically changed. | ||
202 | - | ||
203 | -This is your count variable: | ||
204 | - | ||
205 | -```dart | ||
206 | -var name = 'Jonatas Borges'; | ||
207 | -``` | ||
208 | - | ||
209 | -To make it observable, you just need to add ".obs" to the end of it: | ||
210 | - | ||
211 | -```dart | ||
212 | -var name = 'Jonatas Borges'.obs; | ||
213 | -``` | ||
214 | - | ||
215 | -And in the UI, when you want to show that value and update the screen whenever the values changes, simply do this: | ||
216 | - | ||
217 | -```dart | ||
218 | -Obx(() => Text("${controller.name}")); | ||
219 | -``` | ||
220 | - | ||
221 | -That's all. It's _that_ simple. | ||
222 | - | ||
223 | -### Thêm thông tin về Quản lý state | ||
224 | - | ||
225 | -**Xem thông tin cụ thể tại dây [here](./documentation/en_US/state_management.md). Tại đó, bạn có thể tham khảo ví dụ và so sánh sự khác nhau giữa quản lý state cơ bản và quản lý state reactive** | ||
226 | - | ||
227 | -Bạn sẽ hình dung sức mạnh của GetX. | ||
228 | - | ||
229 | -## Quản lý route | ||
230 | - | ||
231 | -Nếu bạn chỉ sử dụng routes/snackbars/dialogs/bottomsheets không có context, GetX là lựa chọn số 2 trừ 1, nhìn đây: | ||
232 | - | ||
233 | -Thêm "Get" trước MaterialApp, nó sẽ biến thành GetMaterialApp | ||
234 | - | ||
235 | -```dart | ||
236 | -GetMaterialApp( // Before: MaterialApp( | ||
237 | - home: MyHome(), | ||
238 | -) | ||
239 | -``` | ||
240 | - | ||
241 | -Di chuyển tới màn hình mới: | ||
242 | - | ||
243 | -```dart | ||
244 | - | ||
245 | -Get.to(NextScreen()); | ||
246 | -``` | ||
247 | - | ||
248 | -Di chuyển tới màn hình mới theo tên. Xem thêm tại đây [here](./documentation/en_US/route_management.md#navigation-with-named-routes) | ||
249 | - | ||
250 | -```dart | ||
251 | - | ||
252 | -Get.toNamed('/details'); | ||
253 | -``` | ||
254 | - | ||
255 | -Để đóng snackbars, dialogs, bottomsheets, hay bất kì thứ gì, bạn có thể xài cái này để thay Navigator.pop(context); | ||
256 | - | ||
257 | -```dart | ||
258 | -Get.back(); | ||
259 | -``` | ||
260 | - | ||
261 | -Đi đến màn hình kế tiếp và bỏ luôn màn hình cũ (thường dùng cho màn hình giới thiệu, màn hình đăng nhập, etc.) | ||
262 | - | ||
263 | -```dart | ||
264 | -Get.off(NextScreen()); | ||
265 | -``` | ||
266 | - | ||
267 | -Đi đến màn hình kế tiếp và đóng tất cả các routes (hữu dụng cho shopping cart, polls, và tests) | ||
268 | - | ||
269 | -```dart | ||
270 | -Get.offAll(NextScreen()); | ||
271 | -``` | ||
272 | - | ||
273 | -Bạn có thấy nãy giờ chúng ta không sử dụng từ khóa "context"? Đây chính là thang điểm 9 + 1 của quản lý route ở Get. Với điểm mạnh trên, bạn có thể thao tác bất cứ đâu, kể cả trong controller class. | ||
274 | - | ||
275 | -### Thêm thông tin về quản lý route | ||
276 | - | ||
277 | -**Get works with named routes and also offers lower-level control over your routes! There is in-depth documentation [here](./documentation/en_US/route_management.md)** | ||
278 | - | ||
279 | -## Quản lý dependency | ||
280 | - | ||
281 | -Get hỗ trợ tính năng giúp bạn lấy class như Bloc hoặc Controller chỉ với 1 dòng, khỏi cần Provider context hay InheritedWidget: | ||
282 | - | ||
283 | -```dart | ||
284 | -Controller controller = Get.put(Controller()); // Rather Controller controller = Controller(); | ||
285 | -``` | ||
286 | - | ||
287 | -- Chí ú: Nếu bạn dùng cái này, nhớ đặt attention to thànhe bindings API, which will make it easier to connect your view to your controller. | ||
288 | - | ||
289 | -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. | ||
290 | -So you can use your controller (or class Bloc) normally | ||
291 | - | ||
292 | -**Tip:** Get dependency management is decoupled from other parts of the package, so if for example, your app is already using a state manager (any one, it doesn't matter), you don't need to rewrite it all, you can use this dependency injection with no problems at all | ||
293 | - | ||
294 | -```dart | ||
295 | -controller.fetchApi(); | ||
296 | -``` | ||
297 | - | ||
298 | -Imagine that you have navigated through numerous routes, and you need 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: | ||
299 | - | ||
300 | -```dart | ||
301 | -Controller controller = Get.find(); | ||
302 | -//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. | ||
303 | -``` | ||
304 | - | ||
305 | -And then you will be able to recover your controller data that was obtained back there: | ||
306 | - | ||
307 | -```dart | ||
308 | -Text(controller.textFromApi); | ||
309 | -``` | ||
310 | - | ||
311 | -### More details about dependency management | ||
312 | - | ||
313 | -**See a more in-depth explanation of dependency management [here](./documentation/en_US/dependency_management.md)** | ||
314 | - | ||
315 | -# Utils | ||
316 | - | ||
317 | -## Internationalization | ||
318 | - | ||
319 | -### Translations | ||
320 | - | ||
321 | -Translations are kept as a simple key-value dictionary map. | ||
322 | -To add custom translations, create a class and extend `Translations`. | ||
323 | - | ||
324 | -```dart | ||
325 | -import 'package:get/get.dart'; | ||
326 | - | ||
327 | -class Messages extends Translations { | ||
328 | - @override | ||
329 | - Map<String, Map<String, String>> get keys => { | ||
330 | - 'en_US': { | ||
331 | - 'hello': 'Hello World', | ||
332 | - }, | ||
333 | - 'de_DE': { | ||
334 | - 'hello': 'Hallo Welt', | ||
335 | - } | ||
336 | - }; | ||
337 | -} | ||
338 | -``` | ||
339 | - | ||
340 | -#### Using translations | ||
341 | - | ||
342 | -Just append `.tr` to the specified key and it will be translated, using the current value of `Get.locale` and `Get.fallbackLocale`. | ||
343 | - | ||
344 | -```dart | ||
345 | -Text('title'.tr); | ||
346 | -``` | ||
347 | - | ||
348 | -#### Using translation with singular and plural | ||
349 | - | ||
350 | -```dart | ||
351 | -var products = []; | ||
352 | -Text('singularKey'.trPlural('pluralKey', products.length, Args)); | ||
353 | -``` | ||
354 | - | ||
355 | -#### Using translation with parameters | ||
356 | - | ||
357 | -```dart | ||
358 | -import 'package:get/get.dart'; | ||
359 | - | ||
360 | - | ||
361 | -Map<String, Map<String, String>> get keys => { | ||
362 | - 'en_US': { | ||
363 | - 'logged_in': 'logged in as @name with email @email', | ||
364 | - }, | ||
365 | - 'es_ES': { | ||
366 | - 'logged_in': 'iniciado sesión como @name con e-mail @email', | ||
367 | - } | ||
368 | -}; | ||
369 | - | ||
370 | -Text('logged_in'.trParams({ | ||
371 | - 'name': 'Jhon', | ||
372 | - 'email': 'jhon@example.com' | ||
373 | - })); | ||
374 | -``` | ||
375 | - | ||
376 | -### Locales | ||
377 | - | ||
378 | -Pass parameters to `GetMaterialApp` to define the locale and translations. | ||
379 | - | ||
380 | -```dart | ||
381 | -return GetMaterialApp( | ||
382 | - translations: Messages(), // your translations | ||
383 | - locale: Locale('en', 'US'), // translations will be displayed in that locale | ||
384 | - fallbackLocale: Locale('en', 'UK'), // specify the fallback locale in case an invalid locale is selected. | ||
385 | -); | ||
386 | -``` | ||
387 | - | ||
388 | -#### Change locale | ||
389 | - | ||
390 | -Call `Get.updateLocale(locale)` to update the locale. Translations then automatically use the new locale. | ||
391 | - | ||
392 | -```dart | ||
393 | -var locale = Locale('en', 'US'); | ||
394 | -Get.updateLocale(locale); | ||
395 | -``` | ||
396 | - | ||
397 | -#### System locale | ||
398 | - | ||
399 | -To read the system locale, you could use `Get.deviceLocale`. | ||
400 | - | ||
401 | -```dart | ||
402 | -return GetMaterialApp( | ||
403 | - locale: Get.deviceLocale, | ||
404 | -); | ||
405 | -``` | ||
406 | - | ||
407 | -## Change Theme | ||
408 | - | ||
409 | -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 **GetX™**. | ||
410 | - | ||
411 | -You can create your custom theme and simply add it within `Get.changeTheme` without any boilerplate for that: | ||
412 | - | ||
413 | -```dart | ||
414 | -Get.changeTheme(ThemeData.light()); | ||
415 | -``` | ||
416 | - | ||
417 | -If you want to create something like a button that changes the Theme in `onTap`, you can combine two **GetX™** APIs for that: | ||
418 | - | ||
419 | -- The api that checks if the dark `Theme` is being used. | ||
420 | -- And the `Theme` Change API, you can just put this within an `onPressed`: | ||
421 | - | ||
422 | -```dart | ||
423 | -Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark()); | ||
424 | -``` | ||
425 | - | ||
426 | -When `.darkmode` is activated, it will switch to the _light theme_, and when the _light theme_ becomes active, it will change to _dark theme_. | ||
427 | - | ||
428 | -## GetConnect | ||
429 | - | ||
430 | -GetConnect is an easy way to communicate from your back to your front with http or websockets | ||
431 | - | ||
432 | -### Default configuration | ||
433 | - | ||
434 | -You can simply extend GetConnect and use the GET/POST/PUT/DELETE/SOCKET methods to communicate with your Rest API or websockets. | ||
435 | - | ||
436 | -```dart | ||
437 | -class UserProvider extends GetConnect { | ||
438 | - // Get request | ||
439 | - Future<Response> getUser(int id) => get('http://youapi/users/$id'); | ||
440 | - // Post request | ||
441 | - Future<Response> postUser(Map data) => post('http://youapi/users', body: data); | ||
442 | - // Post request with File | ||
443 | - Future<Response<CasesModel>> postCases(List<int> image) { | ||
444 | - final form = FormData({ | ||
445 | - 'file': MultipartFile(image, filename: 'avatar.png'), | ||
446 | - 'otherFile': MultipartFile(image, filename: 'cover.png'), | ||
447 | - }); | ||
448 | - return post('http://youapi/users/upload', form); | ||
449 | - } | ||
450 | - | ||
451 | - GetSocket userMessages() { | ||
452 | - return socket('https://yourapi/users/socket'); | ||
453 | - } | ||
454 | -} | ||
455 | -``` | ||
456 | - | ||
457 | -### Custom configuration | ||
458 | - | ||
459 | -GetConnect is highly customizable You can define base Url, as answer modifiers, as Requests modifiers, define an authenticator, and even the number of attempts in which it will try to authenticate itself, in addition to giving the possibility to define a standard decoder that will transform all your requests into your Models without any additional configuration. | ||
460 | - | ||
461 | -```dart | ||
462 | -class HomeProvider extends GetConnect { | ||
463 | - @override | ||
464 | - void onInit() { | ||
465 | - // All request will pass to jsonEncode so CasesModel.fromJson() | ||
466 | - httpClient.defaultDecoder = CasesModel.fromJson; | ||
467 | - httpClient.baseUrl = 'https://api.covid19api.com'; | ||
468 | - // baseUrl = 'https://api.covid19api.com'; // It define baseUrl to | ||
469 | - // Http and websockets if used with no [httpClient] instance | ||
470 | - | ||
471 | - // It's will attach 'apikey' property on header from all requests | ||
472 | - httpClient.addRequestModifier((request) { | ||
473 | - request.headers['apikey'] = '12345678'; | ||
474 | - return request; | ||
475 | - }); | ||
476 | - | ||
477 | - // Even if the server sends data from the country "Brazil", | ||
478 | - // it will never be displayed to users, because you remove | ||
479 | - // that data from the response, even before the response is delivered | ||
480 | - httpClient.addResponseModifier<CasesModel>((request, response) { | ||
481 | - CasesModel model = response.body; | ||
482 | - if (model.countries.contains('Brazil')) { | ||
483 | - model.countries.remove('Brazilll'); | ||
484 | - } | ||
485 | - }); | ||
486 | - | ||
487 | - httpClient.addAuthenticator((request) async { | ||
488 | - final response = await get("http://yourapi/token"); | ||
489 | - final token = response.body['token']; | ||
490 | - // Set the header | ||
491 | - request.headers['Authorization'] = "$token"; | ||
492 | - return request; | ||
493 | - }); | ||
494 | - | ||
495 | - //Autenticator will be called 3 times if HttpStatus is | ||
496 | - //HttpStatus.unauthorized | ||
497 | - httpClient.maxAuthRetries = 3; | ||
498 | - } | ||
499 | - } | ||
500 | - | ||
501 | - @override | ||
502 | - Future<Response<CasesModel>> getCases(String path) => get(path); | ||
503 | -} | ||
504 | -``` | ||
505 | - | ||
506 | -## GetPage Middleware | ||
507 | - | ||
508 | -The GetPage has now new property that takes a list of GetMiddleWare and run them in the specific order. | ||
509 | - | ||
510 | -**Chí ú**: Nếu bạn dùng cái này, nhớ đặten of thànhis page will have the same middlewares automatically. | ||
511 | - | ||
512 | -### Priority | ||
513 | - | ||
514 | -The Order of the Middlewares to run can pe set by the priority in the GetMiddleware. | ||
515 | - | ||
516 | -```dart | ||
517 | -final middlewares = [ | ||
518 | - GetMiddleware(priority: 2), | ||
519 | - GetMiddleware(priority: 5), | ||
520 | - GetMiddleware(priority: 4), | ||
521 | - GetMiddleware(priority: -8), | ||
522 | -]; | ||
523 | -``` | ||
524 | - | ||
525 | -those middlewares will be run in this order **-8 => 2 => 4 => 5** | ||
526 | - | ||
527 | -### Redirect | ||
528 | - | ||
529 | -This function will be called when the page of the called route is being searched for. It takes RouteSettings as a result to redirect to. Or give it null and there will be no redirecting. | ||
530 | - | ||
531 | -```dart | ||
532 | -RouteSettings redirect(String route) { | ||
533 | - final authService = Get.find<AuthService>(); | ||
534 | - return authService.authed.value ? null : RouteSettings(name: '/login') | ||
535 | -} | ||
536 | -``` | ||
537 | - | ||
538 | -### onPageCalled | ||
539 | - | ||
540 | -This function will be called when this Page is called before anything created | ||
541 | -you can use it to change something about the page or give it new page | ||
542 | - | ||
543 | -```dart | ||
544 | -GetPage onPageCalled(GetPage page) { | ||
545 | - final authService = Get.find<AuthService>(); | ||
546 | - return page.copyWith(title: 'Welcome ${authService.UserName}'); | ||
547 | -} | ||
548 | -``` | ||
549 | - | ||
550 | -### OnBindingsStart | ||
551 | - | ||
552 | -This function will be called right before the Bindings are initialize. | ||
553 | -Here you can change Bindings for this page. | ||
554 | - | ||
555 | -```dart | ||
556 | -List<Bindings> onBindingsStart(List<Bindings> bindings) { | ||
557 | - final authService = Get.find<AuthService>(); | ||
558 | - if (authService.isAdmin) { | ||
559 | - bindings.add(AdminBinding()); | ||
560 | - } | ||
561 | - return bindings; | ||
562 | -} | ||
563 | -``` | ||
564 | - | ||
565 | -### OnPageBuildStart | ||
566 | - | ||
567 | -This function will be called right after the Bindings are initialize. | ||
568 | -Here you can do something after that you created the bindings and before creating the page widget. | ||
569 | - | ||
570 | -```dart | ||
571 | -GetPageBuilder onPageBuildStart(GetPageBuilder page) { | ||
572 | - print('bindings are ready'); | ||
573 | - return page; | ||
574 | -} | ||
575 | -``` | ||
576 | - | ||
577 | -### OnPageBuilt | ||
578 | - | ||
579 | -This function will be called right after the GetPage.page function is called and will give you the result of the function. and take the widget that will be showed. | ||
580 | - | ||
581 | -### OnPageDispose | ||
582 | - | ||
583 | -This function will be called right after disposing all the related objects (Controllers, views, ...) of the page. | ||
584 | - | ||
585 | -## Other Advanced APIs | ||
586 | - | ||
587 | -```dart | ||
588 | -// give the current args from currentScreen | ||
589 | -Get.arguments | ||
590 | - | ||
591 | -// give name of previous route | ||
592 | -Get.previousRoute | ||
593 | - | ||
594 | -// give the raw route to access for example, rawRoute.isFirst() | ||
595 | -Get.rawRoute | ||
596 | - | ||
597 | -// give access to Routing API from GetObserver | ||
598 | -Get.routing | ||
599 | - | ||
600 | -// check if snackbar is open | ||
601 | -Get.isSnackbarOpen | ||
602 | - | ||
603 | -// check if dialog is open | ||
604 | -Get.isDialogOpen | ||
605 | - | ||
606 | -// check if bottomsheet is open | ||
607 | -Get.isBottomSheetOpen | ||
608 | - | ||
609 | -// remove one route. | ||
610 | -Get.removeRoute() | ||
611 | - | ||
612 | -// back repeatedly until the predicate returns true. | ||
613 | -Get.until() | ||
614 | - | ||
615 | -// go to next route and remove all the previous routes until the predicate returns true. | ||
616 | -Get.offUntil() | ||
617 | - | ||
618 | -// go to next named route and remove all the previous routes until the predicate returns true. | ||
619 | -Get.offNamedUntil() | ||
620 | - | ||
621 | -//Check in what platform the app is running | ||
622 | -GetPlatform.isAndroid | ||
623 | -GetPlatform.isIOS | ||
624 | -GetPlatform.isMacOS | ||
625 | -GetPlatform.isWindows | ||
626 | -GetPlatform.isLinux | ||
627 | -GetPlatform.isFuchsia | ||
628 | - | ||
629 | -//Check the device type | ||
630 | -GetPlatform.isMobile | ||
631 | -GetPlatform.isDesktop | ||
632 | -//All platforms are supported independently in web! | ||
633 | -//You can tell if you are running inside a browser | ||
634 | -//on Windows, iOS, OSX, Android, etc. | ||
635 | -GetPlatform.isWeb | ||
636 | - | ||
637 | - | ||
638 | -// Equivalent to : MediaQuery.of(context).size.height, | ||
639 | -// but immutable. | ||
640 | -Get.height | ||
641 | -Get.width | ||
642 | - | ||
643 | -// Gives the current context of the Navigator. | ||
644 | -Get.context | ||
645 | - | ||
646 | -// Gives the context of the snackbar/dialog/bottomsheet in the foreground, anywhere in your code. | ||
647 | -Get.contextOverlay | ||
648 | - | ||
649 | -// Chí ú: Nếu bạn dùng cái này, nhớ đặtt. thànhnce you | ||
650 | -// have access to context in any place of your UI, you can use it anywhere in the UI code | ||
651 | - | ||
652 | -// If you need a changeable height/width (like Desktop or browser windows that can be scaled) you will need to use context. | ||
653 | -context.width | ||
654 | -context.height | ||
655 | - | ||
656 | -// Gives you the power to define half the screen, a third of it and so on. | ||
657 | -// Useful for responsive applications. | ||
658 | -// param dividedBy (double) optional - default: 1 | ||
659 | -// param reducedBy (double) optional - default: 0 | ||
660 | -context.heightTransformer() | ||
661 | -context.widthTransformer() | ||
662 | - | ||
663 | -/// Similar to MediaQuery.of(context).size | ||
664 | -context.mediaQuerySize() | ||
665 | - | ||
666 | -/// Similar to MediaQuery.of(context).padding | ||
667 | -context.mediaQueryPadding() | ||
668 | - | ||
669 | -/// Similar to MediaQuery.of(context).viewPadding | ||
670 | -context.mediaQueryViewPadding() | ||
671 | - | ||
672 | -/// Similar to MediaQuery.of(context).viewInsets; | ||
673 | -context.mediaQueryViewInsets() | ||
674 | - | ||
675 | -/// Similar to MediaQuery.of(context).orientation; | ||
676 | -context.orientation() | ||
677 | - | ||
678 | -/// Check if device is on landscape mode | ||
679 | -context.isLandscape() | ||
680 | - | ||
681 | -/// Check if device is on portrait mode | ||
682 | -context.isPortrait() | ||
683 | - | ||
684 | -/// Similar to MediaQuery.of(context).devicePixelRatio; | ||
685 | -context.devicePixelRatio() | ||
686 | - | ||
687 | -/// Similar to MediaQuery.of(context).textScaleFactor; | ||
688 | -context.textScaleFactor() | ||
689 | - | ||
690 | -/// Get the shortestSide from screen | ||
691 | -context.mediaQueryShortestSide() | ||
692 | - | ||
693 | -/// True if width be larger than 800 | ||
694 | -context.showNavbar() | ||
695 | - | ||
696 | -/// True if the shortestSide is smaller than 600p | ||
697 | -context.isPhone() | ||
698 | - | ||
699 | -/// True if the shortestSide is largest than 600p | ||
700 | -context.isSmallTablet() | ||
701 | - | ||
702 | -/// True if the shortestSide is largest than 720p | ||
703 | -context.isLargeTablet() | ||
704 | - | ||
705 | -/// True if the current device is Tablet | ||
706 | -context.isTablet() | ||
707 | - | ||
708 | -/// Returns a value<T> according to the screen size | ||
709 | -/// can give value for: | ||
710 | -/// watch: if the shortestSide is smaller than 300 | ||
711 | -/// mobile: if the shortestSide is smaller than 600 | ||
712 | -/// tablet: if the shortestSide is smaller than 1200 | ||
713 | -/// desktop: if width is largest than 1200 | ||
714 | -context.responsiveValue<T>() | ||
715 | -``` | ||
716 | - | ||
717 | -### Optional Global Settings and Manual configurations | ||
718 | - | ||
719 | -GetMaterialApp configures everything for you, but if you want to configure Get manually. | ||
720 | - | ||
721 | -```dart | ||
722 | -MaterialApp( | ||
723 | - navigatorKey: Get.key, | ||
724 | - navigatorObservers: [GetObserver()], | ||
725 | -); | ||
726 | -``` | ||
727 | - | ||
728 | -You will also be able to use your own Middleware within `GetObserver`, this will not influence anything. | ||
729 | - | ||
730 | -```dart | ||
731 | -MaterialApp( | ||
732 | - navigatorKey: Get.key, | ||
733 | - navigatorObservers: [ | ||
734 | - GetObserver(MiddleWare.observer) // Here | ||
735 | - ], | ||
736 | -); | ||
737 | -``` | ||
738 | - | ||
739 | -You can create _Global Settings_ for `Get`. Just add `Get.config` to your code before pushing any route. | ||
740 | -Or do it directly in your `GetMaterialApp` | ||
741 | - | ||
742 | -```dart | ||
743 | -GetMaterialApp( | ||
744 | - enableLog: true, | ||
745 | - defaultTransition: Transition.fade, | ||
746 | - opaqueRoute: Get.isOpaqueRouteDefault, | ||
747 | - popGesture: Get.isPopGestureEnable, | ||
748 | - transitionDuration: Get.defaultDurationTransition, | ||
749 | - defaultGlobalState: Get.defaultGlobalState, | ||
750 | -); | ||
751 | - | ||
752 | -Get.config( | ||
753 | - enableLog = true, | ||
754 | - defaultPopGesture = true, | ||
755 | - defaultTransition = Transitions.cupertino | ||
756 | -) | ||
757 | -``` | ||
758 | - | ||
759 | -You can optionally redirect all the logging messages from `Get`. | ||
760 | -If you want to use your own, favourite logging package, | ||
761 | -and want to capture the logs there: | ||
762 | - | ||
763 | -```dart | ||
764 | -GetMaterialApp( | ||
765 | - enableLog: true, | ||
766 | - logWriterCallback: localLogWriter, | ||
767 | -); | ||
768 | - | ||
769 | -void localLogWriter(String text, {bool isError = false}) { | ||
770 | - // pass the message to your favourite logging package here | ||
771 | - // please note that even if enableLog: false log messages will be pushed in this callback | ||
772 | - // you get check the flag if you want through GetConfig.isLogEnable | ||
773 | -} | ||
774 | - | ||
775 | -``` | ||
776 | - | ||
777 | -### Local State Widgets | ||
778 | - | ||
779 | -These Widgets allows you to manage a single value, and keep the state ephemeral and locally. | ||
780 | -We have flavours for Reactive and Simple. | ||
781 | -For instance, you might use them to toggle obscureText in a `TextField`, maybe create a custom | ||
782 | -Expandable Panel, or maybe modify the current index in `BottomNavigationBar` while changing the content | ||
783 | -of the body in a `Scaffold`. | ||
784 | - | ||
785 | -#### ValueBuilder | ||
786 | - | ||
787 | -A simplification of `StatefulWidget` that works with a `.setState` callback that takes the updated value. | ||
788 | - | ||
789 | -```dart | ||
790 | -ValueBuilder<bool>( | ||
791 | - initialValue: false, | ||
792 | - builder: (value, updateFn) => Switch( | ||
793 | - value: value, | ||
794 | - onChanged: updateFn, // same signature! you could use ( newValue ) => updateFn( newValue ) | ||
795 | - ), | ||
796 | - // if you need to call something outside the builder method. | ||
797 | - onUpdate: (value) => print("Value updated: $value"), | ||
798 | - onDispose: () => print("Widget unmounted"), | ||
799 | -), | ||
800 | -``` | ||
801 | - | ||
802 | -#### ObxValue | ||
803 | - | ||
804 | -Similar to [`ValueBuilder`](#valuebuilder), but this is the Reactive version, you pass a Rx instance (remember the magical .obs?) and | ||
805 | -updates automatically... isn't it awesome? | ||
806 | - | ||
807 | -```dart | ||
808 | -ObxValue((data) => Switch( | ||
809 | - value: data.value, | ||
810 | - onChanged: data, // Rx has a _callable_ function! You could use (flag) => data.value = flag, | ||
811 | - ), | ||
812 | - false.obs, | ||
813 | -), | ||
814 | -``` | ||
815 | - | ||
816 | -## Useful tips | ||
817 | - | ||
818 | -`.obs`ervables (also known as _Rx_ Types) have a wide variety of internal methods and operators. | ||
819 | - | ||
820 | -> Is very common to _believe_ that a property with `.obs` **IS** the actual value... but make no mistake! | ||
821 | -> We avoid the Type declaration of the variable, because Dart's compiler is smart enough, and the code | ||
822 | -> looks cleaner, but: | ||
823 | - | ||
824 | -```dart | ||
825 | -var message = 'Hello world'.obs; | ||
826 | -print( 'Message "$message" has Type ${message.runtimeType}'); | ||
827 | -``` | ||
828 | - | ||
829 | -Even if `message` _prints_ the actual String value, the Type is **RxString**! | ||
830 | - | ||
831 | -So, you can't do `message.substring( 0, 4 )`. | ||
832 | -You have to access the real `value` inside the _observable_: | ||
833 | -The most "used way" is `.value`, but, did you know that you can also use... | ||
834 | - | ||
835 | -```dart | ||
836 | -final name = 'GetX'.obs; | ||
837 | -// only "updates" the stream, if the value is different from the current one. | ||
838 | -name.value = 'Hey'; | ||
839 | - | ||
840 | -// All Rx properties are "callable" and returns the new value. | ||
841 | -// but this approach does not accepts `null`, the UI will not rebuild. | ||
842 | -name('Hello'); | ||
843 | - | ||
844 | -// is like a getter, prints 'Hello'. | ||
845 | -name() ; | ||
846 | - | ||
847 | -/// numbers: | ||
848 | - | ||
849 | -final count = 0.obs; | ||
850 | - | ||
851 | -// You can use all non mutable operations from num primitives! | ||
852 | -count + 1; | ||
853 | - | ||
854 | -// Watch out! this is only valid if `count` is not final, but var | ||
855 | -count += 1; | ||
856 | - | ||
857 | -// You can also compare against values: | ||
858 | -count > 2; | ||
859 | - | ||
860 | -/// booleans: | ||
861 | - | ||
862 | -final flag = false.obs; | ||
863 | - | ||
864 | -// switches the value between true/false | ||
865 | -flag.toggle(); | ||
866 | - | ||
867 | - | ||
868 | -/// all types: | ||
869 | - | ||
870 | -// Sets the `value` to null. | ||
871 | -flag.nil(); | ||
872 | - | ||
873 | -// All toString(), toJson() operations are passed down to the `value` | ||
874 | -print( count ); // calls `toString()` inside for RxInt | ||
875 | - | ||
876 | -final abc = [0,1,2].obs; | ||
877 | -// Converts the value to a json Array, prints RxList | ||
878 | -// Json is supported by all Rx types! | ||
879 | -print('json: ${jsonEncode(abc)}, type: ${abc.runtimeType}'); | ||
880 | - | ||
881 | -// RxMap, RxList and RxSet are special Rx types, that extends their native types. | ||
882 | -// but you can work with a List as a regular list, although is reactive! | ||
883 | -abc.add(12); // pushes 12 to the list, and UPDATES the stream. | ||
884 | -abc[3]; // like Lists, reads the index 3. | ||
885 | - | ||
886 | - | ||
887 | -// equality works with the Rx and the value, but hashCode is always taken from the value | ||
888 | -final number = 12.obs; | ||
889 | -print( number == 12 ); // prints > true | ||
890 | - | ||
891 | -/// Custom Rx Models: | ||
892 | - | ||
893 | -// toJson(), toString() are deferred to the child, so you can implement override on them, and print() the observable directly. | ||
894 | - | ||
895 | -class User { | ||
896 | - String name, last; | ||
897 | - int age; | ||
898 | - User({this.name, this.last, this.age}); | ||
899 | - | ||
900 | - @override | ||
901 | - String toString() => '$name $last, $age years old'; | ||
902 | -} | ||
903 | - | ||
904 | -final user = User(name: 'John', last: 'Doe', age: 33).obs; | ||
905 | - | ||
906 | -// `user` is "reactive", but the properties inside ARE NOT! | ||
907 | -// So, if we change some variable inside of it... | ||
908 | -user.value.name = 'Roi'; | ||
909 | -// The widget will not rebuild!, | ||
910 | -// `Rx` don't have any clue when you change something inside user. | ||
911 | -// So, for custom classes, we need to manually "notify" the change. | ||
912 | -user.refresh(); | ||
913 | - | ||
914 | -// or we can use the `update()` method! | ||
915 | -user.update((value){ | ||
916 | - value.name='Roi'; | ||
917 | -}); | ||
918 | - | ||
919 | -print( user ); | ||
920 | -``` | ||
921 | -## StateMixin | ||
922 | - | ||
923 | -Another way to handle your `UI` state is use the `StateMixin<T>` . | ||
924 | -To implement it, use the `with` to add the `StateMixin<T>` | ||
925 | -to your controller which allows a T model. | ||
926 | - | ||
927 | -``` dart | ||
928 | -class Controller extends GetController with StateMixin<User>{} | ||
929 | -``` | ||
930 | - | ||
931 | -The `change()` method change the State whenever we want. | ||
932 | -Just pass the data and the status in this way: | ||
933 | - | ||
934 | -```dart | ||
935 | -change(data, status: RxStatus.success()); | ||
936 | -``` | ||
937 | - | ||
938 | -RxStatus allow these status: | ||
939 | - | ||
940 | -``` dart | ||
941 | -RxStatus.loading(); | ||
942 | -RxStatus.success(); | ||
943 | -RxStatus.empty(); | ||
944 | -RxStatus.error('message'); | ||
945 | -``` | ||
946 | - | ||
947 | -To represent it in the UI, use: | ||
948 | - | ||
949 | -```dart | ||
950 | -class OtherClass extends GetView<Controller> { | ||
951 | - @override | ||
952 | - Widget build(BuildContext context) { | ||
953 | - return Scaffold( | ||
954 | - | ||
955 | - body: controller.obx( | ||
956 | - (state)=>Text(state.name), | ||
957 | - | ||
958 | - // here you can put your custom loading indicator, but | ||
959 | - // by default would be Center(child:CircularProgressIndicator()) | ||
960 | - onLoading: CustomLoadingIndicator(), | ||
961 | - onEmpty: Text('No data found'), | ||
962 | - | ||
963 | - // here also you can set your own error widget, but by | ||
964 | - // default will be an Center(child:Text(error)) | ||
965 | - onError: (error)=>Text(error), | ||
966 | - ), | ||
967 | - ); | ||
968 | -} | ||
969 | -``` | ||
970 | - | ||
971 | -#### GetView | ||
972 | - | ||
973 | -I love this Widget, is so simple, yet, so useful! | ||
974 | - | ||
975 | -Is a `const Stateless` Widget that has a getter `controller` for a registered `Controller`, that's all. | ||
976 | - | ||
977 | -```dart | ||
978 | - class AwesomeController extends GetController { | ||
979 | - final String title = 'My Awesome View'; | ||
980 | - } | ||
981 | - | ||
982 | - // ALWAYS remember to pass the `Type` you used to register your controller! | ||
983 | - class AwesomeView extends GetView<AwesomeController> { | ||
984 | - @override | ||
985 | - Widget build(BuildContext context) { | ||
986 | - return Container( | ||
987 | - padding: EdgeInsets.all(20), | ||
988 | - child: Text(controller.title), // just call `controller.something` | ||
989 | - ); | ||
990 | - } | ||
991 | - } | ||
992 | -``` | ||
993 | - | ||
994 | -#### GetResponsiveView | ||
995 | - | ||
996 | -Extend this widget to build responsive view. | ||
997 | -this widget contains the `screen` property that have all | ||
998 | -information about the screen size and type. | ||
999 | - | ||
1000 | -##### Hướng dẫn sử dụng trước khi dùng | ||
1001 | - | ||
1002 | -You have two options to build it. | ||
1003 | - | ||
1004 | -- with `builder` method you return the widget to build. | ||
1005 | -- with methods `desktop`, `tablet`,`phone`, `watch`. the specific | ||
1006 | - method will be built when the screen type matches the method | ||
1007 | - when the screen is [ScreenType.Tablet] the `tablet` method | ||
1008 | - will be exuded and so on. | ||
1009 | - **Chí ú:** Nếu bạn dùng cái này, nhớ đặt `alwaysUseBuilder` thành `false` | ||
1010 | - | ||
1011 | -Với `settings` property bạn có thể đặt chiều dài tối thiểu cho các loại màn hình. | ||
1012 | - | ||
1013 | - | ||
1014 | -Code to this screen | ||
1015 | -[code](https://github.com/SchabanBo/get_page_example/blob/master/lib/pages/responsive_example/responsive_view.dart) | ||
1016 | - | ||
1017 | -#### GetWidget | ||
1018 | - | ||
1019 | -Most people have no idea about this Widget, or totally confuse the usage of it. | ||
1020 | -The use case is very rare, but very specific: It `caches` a Controller. | ||
1021 | -Because of the _cache_, can't be a `const Stateless`. | ||
1022 | - | ||
1023 | -> So, when do you need to "cache" a Controller? | ||
1024 | - | ||
1025 | -If you use, another "not so common" feature of **GetX**: `Get.create()`. | ||
1026 | - | ||
1027 | -`Get.create(()=>Controller())` will generate a new `Controller` each time you call | ||
1028 | -`Get.find<Controller>()`, | ||
1029 | - | ||
1030 | -That's where `GetWidget` shines... as you can use it, for example, | ||
1031 | -to keep a list of Todo items. So, if the widget gets "rebuilt", it will keep the same controller instance. | ||
1032 | - | ||
1033 | -#### GetxService | ||
1034 | - | ||
1035 | -This class is like a `GetxController`, it shares the same lifecycle ( `onInit()`, `onReady()`, `onClose()`). | ||
1036 | -But has no "logic" inside of it. It just notifies **GetX** Dependency Injection system, that this subclass | ||
1037 | -**can not** be removed from memory. | ||
1038 | - | ||
1039 | -So is super useful to keep your "Services" always reachable and active with `Get.find()`. Like: | ||
1040 | -`ApiService`, `StorageService`, `CacheService`. | ||
1041 | - | ||
1042 | -```dart | ||
1043 | -Future<void> main() async { | ||
1044 | - await initServices(); /// AWAIT SERVICES INITIALIZATION. | ||
1045 | - runApp(SomeApp()); | ||
1046 | -} | ||
1047 | - | ||
1048 | -/// Is a smart move to make your Services intiialize before you run the Flutter app. | ||
1049 | -/// as you can control the execution flow (maybe you need to load some Theme configuration, | ||
1050 | -/// apiKey, language defined by the User... so load SettingService before running ApiService. | ||
1051 | -/// so GetMaterialApp() doesnt have to rebuild, and takes the values directly. | ||
1052 | -void initServices() async { | ||
1053 | - print('starting services ...'); | ||
1054 | - /// Here is where you put get_storage, hive, shared_pref initialization. | ||
1055 | - /// or moor connection, or whatever that's async. | ||
1056 | - await Get.putAsync(() => DbService().init()); | ||
1057 | - await Get.putAsync(SettingsService()).init(); | ||
1058 | - print('All services started...'); | ||
1059 | -} | ||
1060 | - | ||
1061 | -class DbService extends GetxService { | ||
1062 | - Future<DbService> init() async { | ||
1063 | - print('$runtimeType delays 2 sec'); | ||
1064 | - await 2.delay(); | ||
1065 | - print('$runtimeType ready!'); | ||
1066 | - return this; | ||
1067 | - } | ||
1068 | -} | ||
1069 | - | ||
1070 | -class SettingsService extends GetxService { | ||
1071 | - void init() async { | ||
1072 | - print('$runtimeType delays 1 sec'); | ||
1073 | - await 1.delay(); | ||
1074 | - print('$runtimeType ready!'); | ||
1075 | - } | ||
1076 | -} | ||
1077 | - | ||
1078 | -``` | ||
1079 | - | ||
1080 | -The only way to actually delete a `GetxService`, is with `Get.reset()` which is like a | ||
1081 | -"Hot Reboot" of your app. So remember, if you need absolute persistence of a class instance during the | ||
1082 | -lifetime of your app, use `GetxService`. | ||
1083 | - | ||
1084 | -# Breaking changes from 2.0 | ||
1085 | - | ||
1086 | -1- Rx types: | ||
1087 | - | ||
1088 | -| Before | After | | ||
1089 | -| ------- | ---------- | | ||
1090 | -| StringX | `RxString` | | ||
1091 | -| IntX | `RxInt` | | ||
1092 | -| MapX | `RxMap` | | ||
1093 | -| ListX | `RxList` | | ||
1094 | -| NumX | `RxNum` | | ||
1095 | -| DoubleX | `RxDouble` | | ||
1096 | - | ||
1097 | -RxController and GetBuilder now have merged, you no longer need to memorize which controller you want to use, just use GetxController, it will work for simple state management and for reactive as well. | ||
1098 | - | ||
1099 | -2- NamedRoutes | ||
1100 | -Before: | ||
1101 | - | ||
1102 | -```dart | ||
1103 | -GetMaterialApp( | ||
1104 | - namedRoutes: { | ||
1105 | - '/': GetRoute(page: Home()), | ||
1106 | - } | ||
1107 | -) | ||
1108 | -``` | ||
1109 | - | ||
1110 | -Now: | ||
1111 | - | ||
1112 | -```dart | ||
1113 | -GetMaterialApp( | ||
1114 | - getPages: [ | ||
1115 | - GetPage(name: '/', page: () => Home()), | ||
1116 | - ] | ||
1117 | -) | ||
1118 | -``` | ||
1119 | - | ||
1120 | -Why this change? | ||
1121 | -Often, it may be necessary to decide which page will be displayed from a parameter, or a login token, the previous approach was inflexible, as it did not allow this. | ||
1122 | -Inserting the page into a function has significantly reduced the RAM consumption, since the routes will not be allocated in memory since the app was started, and it also allowed to do this type of approach: | ||
1123 | - | ||
1124 | -```dart | ||
1125 | - | ||
1126 | -GetStorage box = GetStorage(); | ||
1127 | - | ||
1128 | -GetMaterialApp( | ||
1129 | - getPages: [ | ||
1130 | - GetPage(name: '/', page:(){ | ||
1131 | - return box.hasData('token') ? Home() : Login(); | ||
1132 | - }) | ||
1133 | - ] | ||
1134 | -) | ||
1135 | -``` | ||
1136 | - | ||
1137 | -# Why Getx? | ||
1138 | - | ||
1139 | -1- Many times after a Flutter update, many of your packages will break. Sometimes compilation errors happen, errors often appear that there are still no answers about, and the developer needs to know where the error came from, track the error, only then try to open an issue in the corresponding repository, and see its problem solved. Get centralizes the main resources for development (State, dependency and route management), allowing you to add a single package to your pubspec, and start working. After a Flutter update, the only thing you need to do is update the Get dependency, and get to work. Get also resolves compatibility issues. How many times a version of a package is not compatible with the version of another, because one uses a dependency in one version, and the other in another version? This is also not a concern using Get, as everything is in the same package and is fully compatible. | ||
1140 | - | ||
1141 | -2- Flutter is easy, Flutter is incredible, but Flutter still has some boilerplate that may be unwanted for most developers, such as `Navigator.of(context).push (context, builder [...]`. Get simplifies development. Instead of writing 8 lines of code to just call a route, you can just do it: `Get.to(Home())` and you're done, you'll go to the next page. Dynamic web urls are a really painful thing to do with Flutter currently, and that with GetX is stupidly simple. Managing states in Flutter, and managing dependencies is also something that generates a lot of discussion, as there are hundreds of patterns in the pub. But there is nothing as easy as adding a ".obs" at the end of your variable, and place your widget inside an Obx, and that's it, all updates to that variable will be automatically updated on the screen. | ||
1142 | - | ||
1143 | -3- Ease without worrying about performance. Flutter's performance is already amazing, but imagine that you use a state manager, and a locator to distribute your blocs/stores/controllers/ etc. classes. You will have to manually call the exclusion of that dependency when you don't need it. But have you ever thought of simply using your controller, and when it was no longer being used by anyone, it would simply be deleted from memory? That's what GetX does. With SmartManagement, everything that is not being used is deleted from memory, and you shouldn't have to worry about anything but programming. You will be assured that you are consuming the minimum necessary resources, without even having created a logic for this. | ||
1144 | - | ||
1145 | -4- Actual decoupling. You may have heard the concept "separate the view from the business logic". This is not a peculiarity of BLoC, MVC, MVVM, and any other standard on the market has this concept. However, this concept can often be mitigated in Flutter due to the use of context. | ||
1146 | -If you need context to find an InheritedWidget, you need it in the view, or pass the context by parameter. I particularly find this solution very ugly, and to work in teams we will always have a dependence on View's business logic. Getx is unorthodox with the standard approach, and while it does not completely ban the use of StatefulWidgets, InitState, etc., it always has a similar approach that can be cleaner. Controllers have life cycles, and when you need to make an APIREST request for example, you don't depend on anything in the view. You can use onInit to initiate the http call, and when the data arrives, the variables will be populated. As GetX is fully reactive (really, and works under streams), once the items are filled, all widgets that use that variable will be automatically updated in the view. This allows people with UI expertise to work only with widgets, and not have to send anything to business logic other than user events (like clicking a button), while people working with business logic will be free to create and test the business logic separately. | ||
1147 | - | ||
1148 | -This library will always be updated and implementing new features. Feel free to offer PRs and contribute to them. | ||
1149 | - | ||
1150 | -# Community | ||
1151 | - | ||
1152 | -## Community channels | ||
1153 | - | ||
1154 | -GetX has a highly active and helpful community. If you have questions, or would like any assistance regarding the use of this framework, please join our community channels, your question will be answered more quickly, and it will be the most suitable place. This repository is exclusive for opening issues, and requesting resources, but feel free to be part of GetX Community. | ||
1155 | - | ||
1156 | -| **Slack** | **Discord** | **Telegram** | | ||
1157 | -| :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- | | ||
1158 | -| [](https://communityinviter.com/apps/getxworkspace/getx) | [](https://discord.com/invite/9Hpt99N) | [](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g) | | ||
1159 | - | ||
1160 | -## How to contribute | ||
1161 | - | ||
1162 | -_Want to contribute to the project? We will be proud to highlight you as one of our collaborators. Here are some points where you can contribute and make Get (and Flutter) even better._ | ||
1163 | - | ||
1164 | -- Helping to translate the readme into other languages. | ||
1165 | -- Adding documentation to the readme (a lot of Get's functions haven't been documented yet). | ||
1166 | -- Write articles or make videos teaching how to use Get (they will be inserted in the Readme and in the future in our Wiki). | ||
1167 | -- Offering PRs for code/tests. | ||
1168 | -- Including new functions. | ||
1169 | - | ||
1170 | -Any contribution is welcome! | ||
1171 | - | ||
1172 | -## Articles and videos | ||
1173 | - | ||
1174 | -- [Flutter Getx EcoSystem package for arabic people](https://www.youtube.com/playlist?list=PLV1fXIAyjeuZ6M8m56zajMUwu4uE3-SL0) - Tutorial by [Pesa Coder](https://github.com/UsamaElgendy). | ||
1175 | -- [Dynamic Themes in 3 lines using GetX™](https://medium.com/swlh/flutter-dynamic-themes-in-3-lines-c3b375f292e3) - Tutorial by [Rod Brown](https://github.com/RodBr). | ||
1176 | -- [Complete GetX™ Navigation](https://www.youtube.com/watch?v=RaqPIoJSTtI) - Route management video by Amateur Coder. | ||
1177 | -- [Complete GetX State Management](https://www.youtube.com/watch?v=CNpXbeI_slw) - Quản lý State video by Amateur Coder. | ||
1178 | -- [GetX™ Other Features](https://youtu.be/ttQtlX_Q0eU) - Utils, storage, bindings and other features video by Amateur Coder. | ||
1179 | -- [Firestore User with GetX | Todo App](https://www.youtube.com/watch?v=BiV0DcXgk58) - Video by Amateur Coder. | ||
1180 | -- [Firebase Auth with GetX | Todo App](https://www.youtube.com/watch?v=-H-T_BSgfOE) - Video by Amateur Coder. | ||
1181 | -- [The Flutter GetX™ Ecosystem ~ State Management](https://medium.com/flutter-community/the-flutter-getx-ecosystem-state-management-881c7235511d) - Quản lý State by [Aachman Garg](https://github.com/imaachman). | ||
1182 | -- [The Flutter GetX™ Ecosystem ~ Dependency Injection](https://medium.com/flutter-community/the-flutter-getx-ecosystem-dependency-injection-8e763d0ec6b9) - Dependency Injection by [Aachman Garg](https://github.com/imaachman). | ||
1183 | -- [GetX, the all-in-one Flutter package](https://www.youtube.com/watch?v=IYQgtu9TM74) - A brief tutorial covering State Management and Navigation by Thad Carnevalli. | ||
1184 | -- [Build a To-do List App from scratch using Flutter and GetX](https://www.youtube.com/watch?v=EcnqFasHf18) - UI + State Management + Storage video by Thad Carnevalli. | ||
1185 | -- [GetX Flutter Firebase Auth Example](https://medium.com/@jeffmcmorris/getx-flutter-firebase-auth-example-b383c1dd1de2) - Article by Jeff McMorris. | ||
1186 | -- [Flutter State Management with GetX – Complete App](https://www.appwithflutter.com/flutter-state-management-with-getx/) - by App With Flutter. | ||
1187 | -- [Flutter Routing with Animation using Get Package](https://www.appwithflutter.com/flutter-routing-using-get-package/) - by App With Flutter. | ||
1188 | -- [A minimal example on dartpad](https://dartpad.dev/2b3d0d6f9d4e312c5fdbefc414c1727e?) - by [Roi Peker](https://github.com/roipeker) |
-
Please register or login to post a comment