Ahmed Fwela

Merge branch 'master' of https://github.com/jonataslaw/getx

Showing 41 changed files with 6433 additions and 116 deletions
{
"cSpell.enableFiletypes": ["!markdown"]
}
... ...
## [4.3.8]
- Fix nav2 toNamed remove the route
## [4.3.7]
- Fix wrong currentRoute when a route is removed
- Remove take that limits the router outlet depth (@steven-spiel)
## [4.3.6]
- Fix error with autodispose of additional dependencies beyond GetxController
- Added ability to add your own delegate to RouterOutlet (@steven-spiel)
- Added listenAndPump to Rx to give Rx the same behavior as BehaviorSubject (@steven-spiel)
## [4.3.5]
- Fix GetConnect timeout (@jasonlaw)
- Improve Vietnamese docs (@hp1909)
- Refactor placeholder name route to unnamed routes (@roipeker).
- Fix: Navigate to a page identical to Get.offNamed.
- Fix: Wrong nameRoute after a route is removed
- Added assert to prevent the user from starting a route name without slash.
## [4.3.4]
- Improve docs
... ...
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png)
[![pub package](https://img.shields.io/pub/v/get.svg?label=get&color=blue)](https://pub.dev/packages/get)
[![likes](https://badges.bar/get/likes)](https://pub.dev/packages/get/score)
![building](https://github.com/jonataslaw/get/workflows/build/badge.svg)
[![style: effective dart](https://img.shields.io/badge/style-effective_dart-40c4ff.svg)](https://pub.dev/packages/effective_dart)
[![Discord Shield](https://img.shields.io/discord/722900883784073290.svg?logo=discord)](https://discord.com/invite/9Hpt99N)
[![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](https://communityinviter.com/apps/getxworkspace/getx)
[![Telegram](https://img.shields.io/badge/chat-on%20Telegram-blue.svg)](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g)
<a href="https://github.com/Solido/awesome-flutter">
<img alt="Awesome Flutter" src="https://img.shields.io/badge/Awesome-Flutter-blue.svg?longCache=true&style=flat-square" />
</a>
<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>
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png)
<div align="center">
**Languages:**
[![English](https://img.shields.io/badge/Language-English-blueviolet?style=for-the-badge)](README.md)
[![Vietnamese](https://img.shields.io/badge/Language-Vietnamese-blueviolet?style=for-the-badge)](README-vi.md)
[![Indonesian](https://img.shields.io/badge/Language-Indonesian-blueviolet?style=for-the-badge)](README.id-ID.md)
[![Urdu](https://img.shields.io/badge/Language-Urdu-blueviolet?style=for-the-badge)](README.ur-PK.md)
[![Chinese](https://img.shields.io/badge/Language-Chinese-blueviolet?style=for-the-badge)](README.zh-cn.md)
[![Portuguese](https://img.shields.io/badge/Language-Portuguese-blueviolet?style=for-the-badge)](README.pt-br.md)
[![Spanish](https://img.shields.io/badge/Language-Spanish-blueviolet?style=for-the-badge)](README-es.md)
[![Russian](https://img.shields.io/badge/Language-Russian-blueviolet?style=for-the-badge)](README.ru.md)
[![Polish](https://img.shields.io/badge/Language-Polish-blueviolet?style=for-the-badge)](README.pl.md)
[![Korean](https://img.shields.io/badge/Language-Korean-blueviolet?style=for-the-badge)](README.ko-kr.md)
[![French](https://img.shields.io/badge/Language-French-blueviolet?style=for-the-badge)](README-fr.md)
[![العربيه](https://img.shields.io/badge/Language-arabic-blueviolet?style=for-the-badge)](README-ar.md)
</div>
<div dir="rtl">
- [عن المكتبة](#عن-المكتبة)
- [التركيب](#التركيب)
- [بناء تطبيق العداد 🔢](#بناء-تطبيق-العداد-)
- [The Three pillars](#the-three-pillars)
- [State management](#state-management)
- [Reactive State Manager](#reactive-state-manager)
- [More details about state management](#more-details-about-state-management)
- [Route management](#route-management)
- [More details about route management](#more-details-about-route-management)
- [Dependency management](#dependency-management)
- [More details about dependency management](#more-details-about-dependency-management)
- [Utils](#utils)
- [Internationalization](#internationalization)
- [Translations](#translations)
- [Using translations](#using-translations)
- [Using translation with singular and plural](#using-translation-with-singular-and-plural)
- [Using translation with parameters](#using-translation-with-parameters)
- [Locales](#locales)
- [Change locale](#change-locale)
- [System locale](#system-locale)
- [Change Theme](#change-theme)
- [GetConnect](#getconnect)
- [Default configuration](#default-configuration)
- [Custom configuration](#custom-configuration)
- [GetPage Middleware](#getpage-middleware)
- [Priority](#priority)
- [Redirect](#redirect)
- [onPageCalled](#onpagecalled)
- [OnBindingsStart](#onbindingsstart)
- [OnPageBuildStart](#onpagebuildstart)
- [OnPageBuilt](#onpagebuilt)
- [OnPageDispose](#onpagedispose)
- [Other Advanced APIs](#other-advanced-apis)
- [Optional Global Settings and Manual configurations](#optional-global-settings-and-manual-configurations)
- [Local State Widgets](#local-state-widgets)
- [ValueBuilder](#valuebuilder)
- [ObxValue](#obxvalue)
- [Useful tips](#useful-tips)
- [StateMixin](#statemixin)
- [GetView](#getview)
- [GetResponsiveView](#getresponsiveview)
- [How to use it](#how-to-use-it)
- [GetWidget](#getwidget)
- [GetxService](#getxservice)
- [Tests](#tests)
- [Tips](#tips)
- [Mockito or mocktail](#mockito-or-mocktail)
- [Using Get.reset()](#using-getreset)
- [Get.testMode](#gettestmode)
- [Breaking changes from 2.0](#breaking-changes-from-20)
- [Why Getx?](#why-getx)
- [Community](#community)
- [Community channels](#community-channels)
- [How to contribute](#how-to-contribute)
- [Articles and videos](#articles-and-videos)
# عن المكتبة
- `GetX` مكتبه خفيفه وقوية لفلاتر , توفر المكتبه السرعه العاليه في التحكم في الحاله , نظام حقن `Ddependency injection` ذكي , والتحكم في التنقل بين الصفحات بسرعه وسهوله
- `GetX`
- تعتمد علي 3 نقاط اساسية . **الانتاجية والسرعه والتنظيم**
- **السرعه:** `GetX` تركز علي السرعه واقل استخدام للموارد,`GetX` لا تستخدم `Streams` او `ChangeNotifier`.
- **الانتاجية:** `GetX` تستخدم طريقه سهله ومريحة في كتابة الكود , لا يهم ماذا تريد انت تبني , يوجد دائما طريقه اسهل لبناء باستخدام `GetX` , ستوفر ساعات من العمل وتوفر لك اعلي سرعه يمكن الوصل لها في تطبيقاتك عموما , يجب ان يهتم المطور بالتخلص من الموارد الغير مستخدمه من الذاكرة , مع `GetX` هذا غير ضروري لانه يتم التخلص من الموارد الغير مستخدمه من الذاكره تلقائيا, اذا اردت تركهم دائما في الذاكرة يمكنك ذلك لكن يجب عليك ان تستخدم `permanent: true` بالاضافه الي توفير الوقت تم تقليل امكانية ترك الموارد في الذاكره بدون التخلص منها , يتم حقن الموارد `lazy` افتراضيا
- **التنظيم:** `GetX` تسمح لك بفصل الـ `view` عن الـ `presentation logic` و `business logic` باكامل,
بالنسبة للحقن `dependency injection` و التنقل بين الشاشات لا تحتاج فيهم `context` للتنقل بين الصفحات , ولا تحتاك `context` للوصول للموارد عن طريق widget tree, لذلك يتم الفصل بالكامل بين `presentation logic` و `business logic` لا تحتاج لحقن ال `Controllers/Models/Blocs`
داخل شجره العناصر `Widget Tree` خلال `MultiProvider`s.
لان , `GetX` تستخدم نظام حقن خاص بها ويمكنك من فصل الـ `DI` عن الوجهات بالكامل .
- مع `Getx` تعرف ايه يكون الكود الخاص ب كل جزء في التطبيق , تساعدك في كتابة كود نظيف , بالاضافه الي سهوله التطوير مستقبلا , وهذا يمكنك من مشاركه الاجزاء `modules` امر صعب ليصبح سهل جدا .
`BLOC` كان نقطه البداية لهذا الامر وتظيم الكود بهذه الطريقه في فلاتر , عن طريق فصل كود البزنس عن الواجهات , `GetX` هي التطور لذلك الامر , وذلك عن طريق الاضافه الي ذلك فصل حقن الموارد وفصل التنقل بين الشاشات ايضا , وطبقه البيانات بالكامل ايضا , تعلم اين يكون كل شي في المشروع
- `Getx` توفر لك السهوله في بناء المشروع والاستقرار كلما كبر حجم المشروع واقصي سرعه ممكن , توفر لك ايضا نظام كامل يعمل في تجانس تام , سهل للمبتدئين , ومنظم للخبراء , امن , مستقر , ومحدث باستمرار ويوفر لك موجموعه من الادوات لتسهل عليك
- `GetX` ليست ضخمه , تمتلك المكتبة العديد من المميزات تجعلك تبدا في البرمجه بدون القلق عن اي شي كل ميزه منهم منقسمه عن الاخري ولا يبداو الا عندما تستخدمهم , اذا استخدمت جزء التحكم في الحاله فقط لن يتم استخدام جزء التنقل بين الشاشات في تطبيقك الا `Compiled` والعكس صحيح ! .
-`Getx` لديها نظام شامل , ومجتمع كبير , وعداد كبير من المطورين , وسوف يتم تحديثها باستمرار , تعمل المكتبة علي كل الانظمه بنفس الكود دون تغيير `Android`, `iOS`, `Web`, `Mac`, `Linux`, `Windows` حتي علي الخادم يمكنك استخدام `Getx` لبناء تطبيقات الويب
**[Get Server](https://github.com/jonataslaw/get_server)**.
**بالاضافه الي ذلك يمكن محاكاه الامر اكثر في فلاتر والخادم عن طريق [Get CLI](https://github.com/jonataslaw/get_cli)**.
**وللمزيد من الانتاجية يمكنك استخدام اضافه للـ**
- [فيجوال ستوديو كود](https://marketplace.visualstudio.com/items?itemName=get-snippets.get-snippets)
- [اندرويد استوديو و انتلج](https://plugins.jetbrains.com/plugin/14975-getx-snippets)
# التركيب
استخدم المكتبة في ملف `pubspec.yaml`
<div dir="ltr" >
```yaml
dependencies:
get:
```
</div>
استدعي المكتبة في الملفات الي ستستخدمها
<div dir="ltr" >
```dart
import 'package:get/get.dart';
```
</div>
# بناء تطبيق العداد 🔢
تطبيق العداد الذي يتم انشاء مع كل مشروع جديد يتعدي ال 100 سطر (بالتعليقات) ولكي اريك مدي قوه `GetX`
ساوضح لك كيفيه بناء التطبيق مع تغير قيمه العداد مع كل ضغطه زر والتقل بين الشاشات ومشاركه الحاله كل ذلك بطريقه منذمه وفصل تام لكود البزنس عن الواجهات فقط ب 26 سطر من ضمنهم التعليقات 🔥
- الخطوه الاولي :
اكتب `Get` امام `MaterialApp` لتصبح `GetMaterialApp`
<div dir="ltr" >
```dart
void main() => runApp(GetMaterialApp(home: Home()));
```
</div>
- ملحوظه : هذا لا يعتبر تعديل علي `MaterialApp` لان , `GetMaterialApp` عباره عن عنصر معد مسبقا ويستخدم `MaterialApp` تحت الغطاء , يمكن تغير الاعدادات يدوين لكن هذا غير ضروري لان ``سيقوم بعمل المسارات و حقن العناصر والترجمه وكل شي تحتاجه ولكن اذا كنت تنوي لاستخدام المكتبة فقط للتحكم في الحاله`State managment`فهذه الخطوه غير ضرورية تكون هذه الخطوه ضرورية عندما تريد التنقل بين الشاشات او عرض`snackbars`والترجمه و اي شي يعتمد علي`context`وتقوم`getx` بتوفيره
- الخطوه الثانية
قم بكتابة الكود داخل `class` وكتابة المتغيرات والدوال , يمكنك جعل المتغير قابلع لاعاده بناء الواجها عند تغير قيمته باستخدام ال `getter` `.obs` .
<div dir="ltr" >
```dart
class Controller extends GetxController{
var count = 0.obs;
increment() => count++;
}
```
</div>
- الخطوه الثالثه
ابني الواجهه واستخدم `StatelessWidget` لتوفير الموارد , مع `Getx` يمكنك الاستغناء عن `StatefulWidget`.
<div dir="ltr" >
```dart
class Home extends StatelessWidget {
@override
Widget build(context) {
// Instantiate your class using Get.put() to make it available for all "child" routes there.
final c = Get.put(Controller());
return Scaffold(
// Use Obx(()=> to update Text() whenever count is changed.
appBar: AppBar(title: Obx(() => Text("Clicks: ${c.count}"))),
// Replace the 8 lines Navigator.push by a simple Get.to(). You don't need context
body: Center(child: ElevatedButton(
child: Text("Go to Other"), onPressed: () => Get.to(Other()))),
floatingActionButton:
FloatingActionButton(child: Icon(Icons.add), onPressed: c.increment));
}
}
class Other extends StatelessWidget {
// You can ask Get to find a Controller that is being used by another page and redirect you to it.
final Controller c = Get.find();
@override
Widget build(context){
// Access the updated count variable
return Scaffold(body: Center(child: Text("${c.count}")));
}
}
```
</div>
Result:
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif)
This is a simple project but it already makes clear how powerful Get is. As your project grows, this difference will become more significant.
Get was designed to work with teams, but it makes the job of an individual developer simple.
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!
# The Three pillars
## State management
Get has two different state managers: the simple state manager (we'll call it GetBuilder) and the reactive state manager (GetX/Obx)
### Reactive State Manager
Reactive programming can alienate many people because it is said to be complicated. GetX turns reactive programming into something quite simple:
- You won't need to create StreamControllers.
- You won't need to create a StreamBuilder for each variable
- You will not need to create a class for each state.
- You will not need to create a get for an initial value.
- You will not need to use code generators
Reactive programming with Get is as easy as using setState.
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.
This is your count variable:
```dart
var name = 'Jonatas Borges';
```
To make it observable, you just need to add ".obs" to the end of it:
```dart
var name = 'Jonatas Borges'.obs;
```
And in the UI, when you want to show that value and update the screen whenever the values changes, simply do this:
```dart
Obx(() => Text("${controller.name}"));
```
That's all. It's _that_ simple.
### More details about state management
**See an more in-depth explanation of state management [here](./documentation/en_US/state_management.md). There you will see more examples and also the difference between the simple state manager and the reactive state manager**
You will get a good idea of GetX power.
## Route management
If you are going to use routes/snackbars/dialogs/bottomsheets without context, GetX is excellent for you too, just see it:
Add "Get" before your MaterialApp, turning it into GetMaterialApp
```dart
GetMaterialApp( // Before: MaterialApp(
home: MyHome(),
)
```
Navigate to a new screen:
```dart
Get.to(NextScreen());
```
Navigate to new screen with name. See more details on named routes [here](./documentation/en_US/route_management.md#navigation-with-named-routes)
```dart
Get.toNamed('/details');
```
To close snackbars, dialogs, bottomsheets, or anything you would normally close with Navigator.pop(context);
```dart
Get.back();
```
To go to the next screen and no option to go back to the previous screen (for use in SplashScreens, login screens, etc.)
```dart
Get.off(NextScreen());
```
To go to the next screen and cancel all previous routes (useful in shopping carts, polls, and tests)
```dart
Get.offAll(NextScreen());
```
Noticed that you didn't have to use context to do any of these things? That's one of the biggest advantages of using Get route management. With this, you can execute all these methods from within your controller class, without worries.
### More details about route management
**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)**
## Dependency management
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:
```dart
Controller controller = Get.put(Controller()); // Rather Controller controller = Controller();
```
- Note: If you are using Get's State Manager, pay more attention to the bindings API, which will make it easier to connect your view to your controller.
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.
So you can use your controller (or class Bloc) normally
**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
```dart
controller.fetchApi();
```
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:
```dart
Controller controller = Get.find();
//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.
```
And then you will be able to recover your controller data that was obtained back there:
```dart
Text(controller.textFromApi);
```
### More details about dependency management
**See a more in-depth explanation of dependency management [here](./documentation/en_US/dependency_management.md)**
# Utils
## Internationalization
### Translations
Translations are kept as a simple key-value dictionary map.
To add custom translations, create a class and extend `Translations`.
```dart
import 'package:get/get.dart';
class Messages extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'en_US': {
'hello': 'Hello World',
},
'de_DE': {
'hello': 'Hallo Welt',
}
};
}
```
#### Using translations
Just append `.tr` to the specified key and it will be translated, using the current value of `Get.locale` and `Get.fallbackLocale`.
```dart
Text('title'.tr);
```
#### Using translation with singular and plural
```dart
var products = [];
Text('singularKey'.trPlural('pluralKey', products.length, Args));
```
#### Using translation with parameters
```dart
import 'package:get/get.dart';
Map<String, Map<String, String>> get keys => {
'en_US': {
'logged_in': 'logged in as @name with email @email',
},
'es_ES': {
'logged_in': 'iniciado sesión como @name con e-mail @email',
}
};
Text('logged_in'.trParams({
'name': 'Jhon',
'email': 'jhon@example.com'
}));
```
### Locales
Pass parameters to `GetMaterialApp` to define the locale and translations.
```dart
return GetMaterialApp(
translations: Messages(), // your translations
locale: Locale('en', 'US'), // translations will be displayed in that locale
fallbackLocale: Locale('en', 'UK'), // specify the fallback locale in case an invalid locale is selected.
);
```
#### Change locale
Call `Get.updateLocale(locale)` to update the locale. Translations then automatically use the new locale.
```dart
var locale = Locale('en', 'US');
Get.updateLocale(locale);
```
#### System locale
To read the system locale, you could use `Get.deviceLocale`.
```dart
return GetMaterialApp(
locale: Get.deviceLocale,
);
```
## Change Theme
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™**.
You can create your custom theme and simply add it within `Get.changeTheme` without any boilerplate for that:
```dart
Get.changeTheme(ThemeData.light());
```
If you want to create something like a button that changes the Theme in `onTap`, you can combine two **GetX™** 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`:
```dart
Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark());
```
When `.darkmode` is activated, it will switch to the _light theme_, and when the _light theme_ becomes active, it will change to _dark theme_.
## GetConnect
GetConnect is an easy way to communicate from your back to your front with http or websockets
### Default configuration
You can simply extend GetConnect and use the GET/POST/PUT/DELETE/SOCKET methods to communicate with your Rest API or websockets.
```dart
class UserProvider extends GetConnect {
// Get request
Future<Response> getUser(int id) => get('http://youapi/users/$id');
// Post request
Future<Response> postUser(Map data) => post('http://youapi/users', body: data);
// Post request with File
Future<Response<CasesModel>> postCases(List<int> image) {
final form = FormData({
'file': MultipartFile(image, filename: 'avatar.png'),
'otherFile': MultipartFile(image, filename: 'cover.png'),
});
return post('http://youapi/users/upload', form);
}
GetSocket userMessages() {
return socket('https://yourapi/users/socket');
}
}
```
### Custom configuration
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.
```dart
class HomeProvider extends GetConnect {
@override
void onInit() {
// All request will pass to jsonEncode so CasesModel.fromJson()
httpClient.defaultDecoder = CasesModel.fromJson;
httpClient.baseUrl = 'https://api.covid19api.com';
// baseUrl = 'https://api.covid19api.com'; // It define baseUrl to
// Http and websockets if used with no [httpClient] instance
// It's will attach 'apikey' property on header from all requests
httpClient.addRequestModifier((request) {
request.headers['apikey'] = '12345678';
return request;
});
// Even if the server sends data from the country "Brazil",
// it will never be displayed to users, because you remove
// that data from the response, even before the response is delivered
httpClient.addResponseModifier<CasesModel>((request, response) {
CasesModel model = response.body;
if (model.countries.contains('Brazil')) {
model.countries.remove('Brazilll');
}
});
httpClient.addAuthenticator((request) async {
final response = await get("http://yourapi/token");
final token = response.body['token'];
// Set the header
request.headers['Authorization'] = "$token";
return request;
});
//Autenticator will be called 3 times if HttpStatus is
//HttpStatus.unauthorized
httpClient.maxAuthRetries = 3;
}
}
@override
Future<Response<CasesModel>> getCases(String path) => get(path);
}
```
## GetPage Middleware
The GetPage has now new property that takes a list of GetMiddleWare and run them in the specific order.
**Note**: When GetPage has a Middlewares, all the children of this page will have the same middlewares automatically.
### Priority
The Order of the Middlewares to run can be set by the priority in the GetMiddleware.
```dart
final middlewares = [
GetMiddleware(priority: 2),
GetMiddleware(priority: 5),
GetMiddleware(priority: 4),
GetMiddleware(priority: -8),
];
```
those middlewares will be run in this order **-8 => 2 => 4 => 5**
### Redirect
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.
```dart
RouteSettings redirect(String route) {
final authService = Get.find<AuthService>();
return authService.authed.value ? null : RouteSettings(name: '/login')
}
```
### onPageCalled
This function will be called when this Page is called before anything created
you can use it to change something about the page or give it new page
```dart
GetPage onPageCalled(GetPage page) {
final authService = Get.find<AuthService>();
return page.copyWith(title: 'Welcome ${authService.UserName}');
}
```
### OnBindingsStart
This function will be called right before the Bindings are initialize.
Here you can change Bindings for this page.
```dart
List<Bindings> onBindingsStart(List<Bindings> bindings) {
final authService = Get.find<AuthService>();
if (authService.isAdmin) {
bindings.add(AdminBinding());
}
return bindings;
}
```
### OnPageBuildStart
This function will be called right after the Bindings are initialize.
Here you can do something after that you created the bindings and before creating the page widget.
```dart
GetPageBuilder onPageBuildStart(GetPageBuilder page) {
print('bindings are ready');
return page;
}
```
### OnPageBuilt
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.
### OnPageDispose
This function will be called right after disposing all the related objects (Controllers, views, ...) of the page.
## Other Advanced APIs
```dart
// give the current args from currentScreen
Get.arguments
// give name of previous route
Get.previousRoute
// give the raw route to access for example, rawRoute.isFirst()
Get.rawRoute
// give access to Routing API from GetObserver
Get.routing
// check if snackbar is open
Get.isSnackbarOpen
// check if dialog is open
Get.isDialogOpen
// check if bottomsheet is open
Get.isBottomSheetOpen
// remove one route.
Get.removeRoute()
// back repeatedly until the predicate returns true.
Get.until()
// go to next route and remove all the previous routes until the predicate returns true.
Get.offUntil()
// go to next named route and remove all the previous routes until the predicate returns true.
Get.offNamedUntil()
//Check in what platform the app is running
GetPlatform.isAndroid
GetPlatform.isIOS
GetPlatform.isMacOS
GetPlatform.isWindows
GetPlatform.isLinux
GetPlatform.isFuchsia
//Check the device type
GetPlatform.isMobile
GetPlatform.isDesktop
//All platforms are supported independently in web!
//You can tell if you are running inside a browser
//on Windows, iOS, OSX, Android, etc.
GetPlatform.isWeb
// Equivalent to : MediaQuery.of(context).size.height,
// but immutable.
Get.height
Get.width
// Gives the current context of the Navigator.
Get.context
// Gives the context of the snackbar/dialog/bottomsheet in the foreground, anywhere in your code.
Get.contextOverlay
// Note: the following methods are extensions on context. Since you
// have access to context in any place of your UI, you can use it anywhere in the UI code
// If you need a changeable height/width (like Desktop or browser windows that can be scaled) you will need to use context.
context.width
context.height
// Gives you the power to define half the screen, a third of it and so on.
// Useful for responsive applications.
// param dividedBy (double) optional - default: 1
// param reducedBy (double) optional - default: 0
context.heightTransformer()
context.widthTransformer()
/// Similar to MediaQuery.of(context).size
context.mediaQuerySize()
/// Similar to MediaQuery.of(context).padding
context.mediaQueryPadding()
/// Similar to MediaQuery.of(context).viewPadding
context.mediaQueryViewPadding()
/// Similar to MediaQuery.of(context).viewInsets;
context.mediaQueryViewInsets()
/// Similar to MediaQuery.of(context).orientation;
context.orientation()
/// Check if device is on landscape mode
context.isLandscape()
/// Check if device is on portrait mode
context.isPortrait()
/// Similar to MediaQuery.of(context).devicePixelRatio;
context.devicePixelRatio()
/// Similar to MediaQuery.of(context).textScaleFactor;
context.textScaleFactor()
/// Get the shortestSide from screen
context.mediaQueryShortestSide()
/// True if width be larger than 800
context.showNavbar()
/// True if the shortestSide is smaller than 600p
context.isPhone()
/// True if the shortestSide is largest than 600p
context.isSmallTablet()
/// True if the shortestSide is largest than 720p
context.isLargeTablet()
/// True if the current device is Tablet
context.isTablet()
/// Returns a value<T> according to the screen size
/// can give value for:
/// watch: if the shortestSide is smaller than 300
/// mobile: if the shortestSide is smaller than 600
/// tablet: if the shortestSide is smaller than 1200
/// desktop: if width is largest than 1200
context.responsiveValue<T>()
```
### Optional Global Settings and Manual configurations
GetMaterialApp configures everything for you, but if you want to configure Get manually.
```dart
MaterialApp(
navigatorKey: Get.key,
navigatorObservers: [GetObserver()],
);
```
You will also be able to use your own Middleware within `GetObserver`, this will not influence anything.
```dart
MaterialApp(
navigatorKey: Get.key,
navigatorObservers: [
GetObserver(MiddleWare.observer) // Here
],
);
```
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`
```dart
GetMaterialApp(
enableLog: true,
defaultTransition: Transition.fade,
opaqueRoute: Get.isOpaqueRouteDefault,
popGesture: Get.isPopGestureEnable,
transitionDuration: Get.defaultDurationTransition,
defaultGlobalState: Get.defaultGlobalState,
);
Get.config(
enableLog = true,
defaultPopGesture = true,
defaultTransition = Transitions.cupertino
)
```
You can optionally redirect all the logging messages from `Get`.
If you want to use your own, favourite logging package,
and want to capture the logs there:
```dart
GetMaterialApp(
enableLog: true,
logWriterCallback: localLogWriter,
);
void localLogWriter(String text, {bool isError = false}) {
// pass the message to your favourite logging package here
// please note that even if enableLog: false log messages will be pushed in this callback
// you get check the flag if you want through GetConfig.isLogEnable
}
```
### Local State Widgets
These Widgets allows you to manage a single value, and keep the state ephemeral and locally.
We have flavours for Reactive and Simple.
For instance, you might use them to toggle obscureText in a `TextField`, maybe create a custom
Expandable Panel, or maybe modify the current index in `BottomNavigationBar` while changing the content
of the body in a `Scaffold`.
#### ValueBuilder
A simplification of `StatefulWidget` that works with a `.setState` callback that takes the updated value.
```dart
ValueBuilder<bool>(
initialValue: false,
builder: (value, updateFn) => Switch(
value: value,
onChanged: updateFn, // same signature! you could use ( newValue ) => updateFn( newValue )
),
// if you need to call something outside the builder method.
onUpdate: (value) => print("Value updated: $value"),
onDispose: () => print("Widget unmounted"),
),
```
#### ObxValue
Similar to [`ValueBuilder`](#valuebuilder), but this is the Reactive version, you pass a Rx instance (remember the magical .obs?) and
updates automatically... isn't it awesome?
```dart
ObxValue((data) => Switch(
value: data.value,
onChanged: data, // Rx has a _callable_ function! You could use (flag) => data.value = flag,
),
false.obs,
),
```
## Useful tips
`.obs`ervables (also known as _Rx_ Types) have a wide variety of internal methods and operators.
> Is very common to _believe_ that a property with `.obs` **IS** the actual value... but make no mistake!
> We avoid the Type declaration of the variable, because Dart's compiler is smart enough, and the code
> looks cleaner, but:
```dart
var message = 'Hello world'.obs;
print( 'Message "$message" has Type ${message.runtimeType}');
```
Even if `message` _prints_ the actual String value, the Type is **RxString**!
So, you can't do `message.substring( 0, 4 )`.
You have to access the real `value` inside the _observable_:
The most "used way" is `.value`, but, did you know that you can also use...
```dart
final name = 'GetX'.obs;
// only "updates" the stream, if the value is different from the current one.
name.value = 'Hey';
// All Rx properties are "callable" and returns the new value.
// but this approach does not accepts `null`, the UI will not rebuild.
name('Hello');
// is like a getter, prints 'Hello'.
name() ;
/// numbers:
final count = 0.obs;
// You can use all non mutable operations from num primitives!
count + 1;
// Watch out! this is only valid if `count` is not final, but var
count += 1;
// You can also compare against values:
count > 2;
/// booleans:
final flag = false.obs;
// switches the value between true/false
flag.toggle();
/// all types:
// Sets the `value` to null.
flag.nil();
// All toString(), toJson() operations are passed down to the `value`
print( count ); // calls `toString()` inside for RxInt
final abc = [0,1,2].obs;
// Converts the value to a json Array, prints RxList
// Json is supported by all Rx types!
print('json: ${jsonEncode(abc)}, type: ${abc.runtimeType}');
// RxMap, RxList and RxSet are special Rx types, that extends their native types.
// but you can work with a List as a regular list, although is reactive!
abc.add(12); // pushes 12 to the list, and UPDATES the stream.
abc[3]; // like Lists, reads the index 3.
// equality works with the Rx and the value, but hashCode is always taken from the value
final number = 12.obs;
print( number == 12 ); // prints > true
/// Custom Rx Models:
// toJson(), toString() are deferred to the child, so you can implement override on them, and print() the observable directly.
class User {
String name, last;
int age;
User({this.name, this.last, this.age});
@override
String toString() => '$name $last, $age years old';
}
final user = User(name: 'John', last: 'Doe', age: 33).obs;
// `user` is "reactive", but the properties inside ARE NOT!
// So, if we change some variable inside of it...
user.value.name = 'Roi';
// The widget will not rebuild!,
// `Rx` don't have any clue when you change something inside user.
// So, for custom classes, we need to manually "notify" the change.
user.refresh();
// or we can use the `update()` method!
user.update((value){
value.name='Roi';
});
print( user );
```
## StateMixin
Another way to handle your `UI` state is use the `StateMixin<T>` .
To implement it, use the `with` to add the `StateMixin<T>`
to your controller which allows a T model.
```dart
class Controller extends GetController with StateMixin<User>{}
```
The `change()` method change the State whenever we want.
Just pass the data and the status in this way:
```dart
change(data, status: RxStatus.success());
```
RxStatus allow these status:
```dart
RxStatus.loading();
RxStatus.success();
RxStatus.empty();
RxStatus.error('message');
```
To represent it in the UI, use:
```dart
class OtherClass extends GetView<Controller> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: controller.obx(
(state)=>Text(state.name),
// here you can put your custom loading indicator, but
// by default would be Center(child:CircularProgressIndicator())
onLoading: CustomLoadingIndicator(),
onEmpty: Text('No data found'),
// here also you can set your own error widget, but by
// default will be an Center(child:Text(error))
onError: (error)=>Text(error),
),
);
}
```
#### GetView
I love this Widget, is so simple, yet, so useful!
Is a `const Stateless` Widget that has a getter `controller` for a registered `Controller`, that's all.
```dart
class AwesomeController extends GetController {
final String title = 'My Awesome View';
}
// ALWAYS remember to pass the `Type` you used to register your controller!
class AwesomeView extends GetView<AwesomeController> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(20),
child: Text(controller.title), // just call `controller.something`
);
}
}
```
#### GetResponsiveView
Extend this widget to build responsive view.
this widget contains the `screen` property that have all
information about the screen size and type.
##### How to use it
You have two options to build it.
- with `builder` method you return the widget to build.
- with methods `desktop`, `tablet`,`phone`, `watch`. the specific
method will be built when the screen type matches the method
when the screen is [ScreenType.Tablet] the `tablet` method
will be exuded and so on.
**Note:** If you use this method please set the property `alwaysUseBuilder` to `false`
With `settings` property you can set the width limit for the screen types.
![example](https://github.com/SchabanBo/get_page_example/blob/master/docs/Example.gif?raw=true)
Code to this screen
[code](https://github.com/SchabanBo/get_page_example/blob/master/lib/pages/responsive_example/responsive_view.dart)
#### GetWidget
Most people have no idea about this Widget, or totally confuse the usage of it.
The use case is very rare, but very specific: It `caches` a Controller.
Because of the _cache_, can't be a `const Stateless`.
> So, when do you need to "cache" a Controller?
If you use, another "not so common" feature of **GetX**: `Get.create()`.
`Get.create(()=>Controller())` will generate a new `Controller` each time you call
`Get.find<Controller>()`,
That's where `GetWidget` shines... as you can use it, for example,
to keep a list of Todo items. So, if the widget gets "rebuilt", it will keep the same controller instance.
#### GetxService
This class is like a `GetxController`, it shares the same lifecycle ( `onInit()`, `onReady()`, `onClose()`).
But has no "logic" inside of it. It just notifies **GetX** Dependency Injection system, that this subclass
**can not** be removed from memory.
So is super useful to keep your "Services" always reachable and active with `Get.find()`. Like:
`ApiService`, `StorageService`, `CacheService`.
```dart
Future<void> main() async {
await initServices(); /// AWAIT SERVICES INITIALIZATION.
runApp(SomeApp());
}
/// Is a smart move to make your Services intiialize before you run the Flutter app.
/// as you can control the execution flow (maybe you need to load some Theme configuration,
/// apiKey, language defined by the User... so load SettingService before running ApiService.
/// so GetMaterialApp() doesnt have to rebuild, and takes the values directly.
void initServices() async {
print('starting services ...');
/// Here is where you put get_storage, hive, shared_pref initialization.
/// or moor connection, or whatever that's async.
await Get.putAsync(() => DbService().init());
await Get.putAsync(SettingsService()).init();
print('All services started...');
}
class DbService extends GetxService {
Future<DbService> init() async {
print('$runtimeType delays 2 sec');
await 2.delay();
print('$runtimeType ready!');
return this;
}
}
class SettingsService extends GetxService {
void init() async {
print('$runtimeType delays 1 sec');
await 1.delay();
print('$runtimeType ready!');
}
}
```
The only way to actually delete a `GetxService`, is with `Get.reset()` which is like a
"Hot Reboot" of your app. So remember, if you need absolute persistence of a class instance during the
lifetime of your app, use `GetxService`.
### Tests
You can test your controllers like any other class, including their lifecycles:
```dart
class Controller extends GetxController {
@override
void onInit() {
super.onInit();
//Change value to name2
name.value = 'name2';
}
@override
void onClose() {
name.value = '';
super.onClose();
}
final name = 'name1'.obs;
void changeName() => name.value = 'name3';
}
void main() {
test('''
Test the state of the reactive variable "name" across all of its lifecycles''',
() {
/// You can test the controller without the lifecycle,
/// but it's not recommended unless you're not using
/// GetX dependency injection
final controller = Controller();
expect(controller.name.value, 'name1');
/// If you are using it, you can test everything,
/// including the state of the application after each lifecycle.
Get.put(controller); // onInit was called
expect(controller.name.value, 'name2');
/// Test your functions
controller.changeName();
expect(controller.name.value, 'name3');
/// onClose was called
Get.delete<Controller>();
expect(controller.name.value, '');
});
}
```
#### Tips
##### Mockito or mocktail
If you need to mock your GetxController/GetxService, you should extend GetxController, and mixin it with Mock, that way
```dart
class NotificationServiceMock extends GetxService with Mock implements NotificationService {}
```
##### Using Get.reset()
If you are testing widgets, or test groups, use Get.reset at the end of your test or in tearDown to reset all settings from your previous test.
##### Get.testMode
if you are using your navigation in your controllers, use `Get.testMode = true` at the beginning of your main.
# Breaking changes from 2.0
1- Rx types:
| Before | After |
| ------- | ---------- |
| StringX | `RxString` |
| IntX | `RxInt` |
| MapX | `RxMap` |
| ListX | `RxList` |
| NumX | `RxNum` |
| DoubleX | `RxDouble` |
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.
2- NamedRoutes
Before:
```dart
GetMaterialApp(
namedRoutes: {
'/': GetRoute(page: Home()),
}
)
```
Now:
```dart
GetMaterialApp(
getPages: [
GetPage(name: '/', page: () => Home()),
]
)
```
Why this change?
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.
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:
```dart
GetStorage box = GetStorage();
GetMaterialApp(
getPages: [
GetPage(name: '/', page:(){
return box.hasData('token') ? Home() : Login();
})
]
)
```
# Why Getx?
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.
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.
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.
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.
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.
This library will always be updated and implementing new features. Feel free to offer PRs and contribute to them.
# Community
## Community channels
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.
| **Slack** | **Discord** | **Telegram** |
| :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| [![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](https://communityinviter.com/apps/getxworkspace/getx) | [![Discord Shield](https://img.shields.io/discord/722900883784073290.svg?logo=discord)](https://discord.com/invite/9Hpt99N) | [![Telegram](https://img.shields.io/badge/chat-on%20Telegram-blue.svg)](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g) |
## How to contribute
_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._
- Helping to translate the readme into other languages.
- Adding documentation to the readme (a lot of Get's functions haven't been documented yet).
- Write articles or make videos teaching how to use Get (they will be inserted in the Readme and in the future in our Wiki).
- Offering PRs for code/tests.
- Including new functions.
Any contribution is welcome!
## Articles and videos
- [Flutter Getx EcoSystem package for arabic people](https://www.youtube.com/playlist?list=PLV1fXIAyjeuZ6M8m56zajMUwu4uE3-SL0) - Tutorial by [Pesa Coder](https://github.com/UsamaElgendy).
- [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).
- [Complete GetX™ Navigation](https://www.youtube.com/watch?v=RaqPIoJSTtI) - Route management video by Amateur Coder.
- [Complete GetX State Management](https://www.youtube.com/watch?v=CNpXbeI_slw) - State management video by Amateur Coder.
- [GetX™ Other Features](https://youtu.be/ttQtlX_Q0eU) - Utils, storage, bindings and other features video by Amateur Coder.
- [Firestore User with GetX | Todo App](https://www.youtube.com/watch?v=BiV0DcXgk58) - Video by Amateur Coder.
- [Firebase Auth with GetX | Todo App](https://www.youtube.com/watch?v=-H-T_BSgfOE) - Video by Amateur Coder.
- [The Flutter GetX™ Ecosystem ~ State Management](https://medium.com/flutter-community/the-flutter-getx-ecosystem-state-management-881c7235511d) - State management by [Aachman Garg](https://github.com/imaachman).
- [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).
- [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.
- [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.
- [GetX Flutter Firebase Auth Example](https://medium.com/@jeffmcmorris/getx-flutter-firebase-auth-example-b383c1dd1de2) - Article by Jeff McMorris.
- [Flutter State Management with GetX – Complete App](https://www.appwithflutter.com/flutter-state-management-with-getx/) - by App With Flutter.
- [Flutter Routing with Animation using Get Package](https://www.appwithflutter.com/flutter-routing-using-get-package/) - by App With Flutter.
- [A minimal example on dartpad](https://dartpad.dev/2b3d0d6f9d4e312c5fdbefc414c1727e?) - by [Roi Peker](https://github.com/roipeker)
</div>
... ...
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png)
[![pub package](https://img.shields.io/pub/v/get.svg?label=get&color=blue)](https://pub.dev/packages/get)
[![likes](https://badges.bar/get/likes)](https://pub.dev/packages/get/score)
![building](https://github.com/jonataslaw/get/workflows/build/badge.svg)
[![style: effective dart](https://img.shields.io/badge/style-effective_dart-40c4ff.svg)](https://pub.dev/packages/effective_dart)
[![Discord Shield](https://img.shields.io/discord/722900883784073290.svg?logo=discord)](https://discord.com/invite/9Hpt99N)
[![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](https://communityinviter.com/apps/getxworkspace/getx)
[![Telegram](https://img.shields.io/badge/chat-on%20Telegram-blue.svg)](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g)
<a href="https://github.com/Solido/awesome-flutter">
<img alt="Awesome Flutter" src="https://img.shields.io/badge/Awesome-Flutter-blue.svg?longCache=true&style=flat-square" />
</a>
<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>
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png)
<div align="center">
**言語**
[![英語](https://img.shields.io/badge/Language-English-blueviolet?style=for-the-badge)](README.md)
[![ベトナム語](https://img.shields.io/badge/Language-Vietnamese-blueviolet?style=for-the-badge)](README-vi.md)
[![インドネシア語](https://img.shields.io/badge/Language-Indonesian-blueviolet?style=for-the-badge)](README.id-ID.md)
[![ウルドゥー語](https://img.shields.io/badge/Language-Urdu-blueviolet?style=for-the-badge)](README.ur-PK.md)
[![中国語](https://img.shields.io/badge/Language-Chinese-blueviolet?style=for-the-badge)](README.zh-cn.md)
[![ポルトガル語](https://img.shields.io/badge/Language-Portuguese-blueviolet?style=for-the-badge)](README.pt-br.md)
[![スペイン語](https://img.shields.io/badge/Language-Spanish-blueviolet?style=for-the-badge)](README-es.md)
[![ロシア語](https://img.shields.io/badge/Language-Russian-blueviolet?style=for-the-badge)](README.ru.md)
[![ポーランド語](https://img.shields.io/badge/Language-Polish-blueviolet?style=for-the-badge)](README.pl.md)
[![韓国語](https://img.shields.io/badge/Language-Korean-blueviolet?style=for-the-badge)](README.ko-kr.md)
[![フランス語](https://img.shields.io/badge/Language-French-blueviolet?style=for-the-badge)](README-fr.md)
[![日本語](https://img.shields.io/badge/Language-Japanese-blueviolet?style=for-the-badge)](README-ja.md)
</div>
- [Getとは](#Getとは)
- [インストール方法](#インストール方法)
- [GetXによるカウンターアプリ](#GetXによるカウンターアプリ)
- [三本柱](#三本柱)
- [状態管理](#状態管理)
- [リアクティブな状態管理](#リアクティブな状態管理)
- [状態管理に関する詳細ドキュメント](#状態管理に関する詳細ドキュメント)
- [Route管理](#Route管理)
- [Route管理に関する詳細ドキュメント](#Route管理に関する詳細ドキュメント)
- [依存オブジェクト管理](#依存オブジェクト管理)
- [依存オブジェクト管理に関する詳細ドキュメント](#依存オブジェクト管理に関する詳細ドキュメント)
- [ユーティリティ](#ユーティリティ)
- [多言語対応](#多言語対応)
- [翻訳ファイル](#翻訳ファイル)
- [翻訳ファイルの利用](#翻訳ファイルの利用)
- [ロケール](#ロケール)
- [ロケールの変更](#ロケールの変更)
- [システムのロケールを読み込む](#システムのロケールを読み込む)
- [Themeの変更](#Themeの変更)
- [GetConnect](#getconnect)
- [デフォルト設定](#デフォルト設定)
- [カスタム設定](#カスタム設定)
- [GetPageにミドルウェアを設定](#GetPageにミドルウェアを設定)
- [実行優先度](#実行優先度)
- [redirect](#redirect)
- [onPageCalled](#onpagecalled)
- [onBindingsStart](#onbindingsstart)
- [onPageBuildStart](#onpagebuildstart)
- [onPageBuilt](#onpagebuilt)
- [onPageDispose](#onpagedispose)
- [その他API](#その他API)
- [オプションのグローバル設定と手動設定](#オプションのグローバル設定と手動設定)
- [ローカルステートWidget](#ローカルステートWidget)
- [ValueBuilder](#valuebuilder)
- [ObxValue](#obxvalue)
- [お役立ちTIPS](#お役立ちTIPS)
- [StateMixin](#statemixin)
- [GetView](#getview)
- [GetResponsiveView](#getresponsiveview)
- [使い方](#使い方])
- [GetWidget](#getwidget)
- [GetxService](#getxservice)
- [テストの実行](#テストの実行)
- [mockitoやmocktailを使う場合](#mockitoやmocktailを使う場合)
- [Get.reset()](#Get.reset())
- [Get.testMode](#Get.testMode)
- [バージョン2.0からの破壊的変更](#バージョン2.0からの破壊的変更)
- [なぜGetXなのか](#なぜGetXなのか)
- [コミュニティ](#コミュニティ)
- [コミュニティチャンネル](#コミュニティチャンネル)
- [コントリビュート方法](#コントリビュート方法)
- [GetXに関する記事と動画](#GetXに関する記事と動画)
# Getとは
- GetXはFlutterのための超軽量でパワフルなソリューションです。高パフォーマンスな状態管理機能、インテリジェントな依存オブジェクト管理機能、そしてRoute管理機能の三本柱を軽量かつ実用的な形で組み合わせています。
- GetXは3つの基本原則を念頭に開発されています。 **【生産性、パフォーマンス、コードの分離性】** これらはライブラリ内のすべてのリソースに優先適用されている原則です。
- **パフォーマンス:** GetXは高いパフォーマンスと最小限のリソース消費を目標にしています。GetXはでは Stream および ChangeNotifier を利用しなくて済みます。
- **生産性:** GetXはシンプルで使い心地のいいシンタックスを採用しています。あなたの実現したい機能がどんなものであれ、GetXを使えばより簡単に実現できる方法が見つかるでしょう。開発にかかる時間を短縮し、あなたのアプリケーションのパフォーマンスを最大限引き出してくれます。
開発者はメモリリソースの管理に気を配るのが常です。しかしGetXでは、リソースが使用されていないときはメモリから削除されるのがデフォルト動作のため、過度に気にかける必要はありません。(逆にメモリに残しておきたい場合は、依存オブジェクトをインスタンス化するメソッドを使う際に「permanent: true」と宣言してください)これにより時間が節約できますし、不要な依存オブジェクトがメモリ上に残るリスクも少なくなります。メモリへの読み込みについてもデフォルトは遅延読み込みであり、使用するときに初めてメモリ上に読み込まれます。
- **コードの分離性:** GetXを使うと、ビュー、プレゼンテーションロジック、ビジネスロジック、依存オブジェクトの注入、およびナビゲーション周りのコードを書き分けやすくなります。Routeのナビゲーションにはcontextを必要としないため、Widgetツリーに依存することはありません。ロジックについてもInheritedWidget経由でController/BLoCにアクセスする際のcontextは必要ありません。プレゼンテーションロジックとビジネスロジックをUIクラスから完全に切り離すことができます。また、Controller/モデル/BLoCのクラスを、`MultiProvider`を使ってWidgetツリーに注入する必要もありません。GetXでは独自の依存オブジェクト注入機能を使用し、ビュークラスからビューとは無関係なコードをなくすことができるのです。
GetXを使うことでアプリケーションの各機能がどこにあるのかがわかりやすくなり、自然と見やすいコードになります。メンテナンスが容易になるだけでなく、それまでのFlutterでは考えられなかったモジュール共有が簡単に実現できるようになりました。
BLoCはこの分野におけるFlutterの出発点と言えるものでしたが、GetXはこれを正統進化させており、ビジネスロジックのみならずプレゼンテーションロジックも分離することができます。そのほかデータレイヤーはもちろん、依存オブジェクトやRouteの注入に関するコードも。どこに何が配置されているのか全体の見通しがしやすくなり、Hello Worldを表示させるかのように簡単にアプリの機能を利用できるようになるでしょう。
Flutterアプリを作るならGetXは最も簡単で実用的、かつスケーラブルなソリューションです。強力なエコシステムも存在があるため、初心者にはわかりやすさ、プロには正確性を提供することができます。そしてFlutter SDKにはない幅広い種類のAPIを提供し、セキュアで安定的な環境を構築します。
- GetXは肥大化したライブラリではありません。何も気にせずすぐに開発を始められるよう多数の機能を標準で備えていますが、それぞれの機能は個別にコンテナに入っており、使用してはじめて起動します。状態管理機能しか利用していない場合はその機能だけがコンパイルされます。Route管理機能だけを利用していれば、状態管理機能がコンパイルされることはありません。
- GetXには巨大なエコシステム、コミュニティ、コラボレーターの存在があるため、Flutterが存在する限りメンテナンスされ続けます。またGetXもFlutterと同様にAndroid、iOS、Web、Mac、Linux、Windows、そしてあなたのサーバー上で、単一のコードから実行することができます。
**[Get Server](https://github.com/jonataslaw/get_server)を使うことで、フロントエンドで作成したコードをバックエンドで再利用することが可能です。**
**さらに、[Get CLI](https://github.com/jonataslaw/get_cli)を使えば、サーバー側でもフロントエンド側でも開発プロセス全体を自動化することができます。**
**また、生産性をさらに高めるためのツールとして、[VSCode用の拡張機能](https://marketplace.visualstudio.com/items?itemName=get-snippets.get-snippets) と [Android Studio/Intellij用の拡張機能](https://plugins.jetbrains.com/plugin/14975-getx-snippets)があります。**
# インストール方法
Getパッケージを pubspec.yaml に追加します:
```yaml
dependencies:
get:
```
使用するときはこのようにインポートしてください:
```dart
import 'package:get/get.dart';
```
# GetXによるカウンターアプリ
Flutterで新規プロジェクトを作成する際に表示されるカウンターアプリは、コメントを含めると100行以上あります。Getの実力を示すため、このカウンターアプリを可読性を重視した形で、コメントを含めてわずか26行のコードで作成する方法を紹介します。
- ステップ1:
MaterialAppの前に「Get」を足して、GetMaterialAppにします。
```dart
void main() => runApp(GetMaterialApp(home: Home()));
```
- 注1: GetMaterialAppはFlutterのMaterialAppに手を加えたものではありません。MaterialAppをchildに持ち、諸々の追加設定をしてくれるWidgetに過ぎません。この設定は手動でも可能ですが、その必要はありません。GetMaterialAppは、Routeの作成・注入、言語翻訳の注入など、ナビゲーションに必要なものをすべて注入してくれます。Getを状態管理や依存オブジェクト管理に限定して使用する場合は、GetMaterialAppを使用する必要はありません。GetMaterialAppは、Route、SnackBar、多言語対応、BottomSheet、Dialog、contextなしの高レベルAPIを利用する場合に必要です。
- 注2: このステップは、Route管理機能(`Get.to()`や`Get.back()`など)を使用しない場合は、必要ありません。
- ステップ2:
ビジネスロジッククラスを作成し、そこに必要な変数、メソッド、コントローラをすべて配置します。
変数に ".obs" を付け足すことで、その変数の値の変化を監視することが可能になります。
```dart
class Controller extends GetxController{
var count = 0.obs;
increment() => count++;
}
```
- ステップ3:
ビューを作成します。StatelessWidgetを使用することでRAMが節約できます。GetではStatefulWidgetを使用する必要がなくなるかもしれません。
```dart
class Home extends StatelessWidget {
@override
Widget build(context) {
// Get.put()を使ってクラスをインスタンス化することですべての子Routeで利用できるようになります。
final Controller c = Get.put(Controller());
return Scaffold(
// countが変わるたびにTextを更新するにはObx(()=>)を使ってください。
appBar: AppBar(title: Obx(() => Text("Clicks: ${c.count}"))),
// 8行使っていたNavigator.pushの代わりに短い Get.to()を使ってください。context不要です。
body: Center(child: ElevatedButton(
child: Text("Go to Other"), onPressed: () => Get.to(Other()))),
floatingActionButton:
FloatingActionButton(child: Icon(Icons.add), onPressed: c.increment));
}
}
class Other extends StatelessWidget {
// 他のページで使われているコントローラーを見つけてきてくれます。
final Controller c = Get.find();
@override
Widget build(context){
// 最新のcount変数の値にアクセス
return Scaffold(body: Center(child: Text("${c.count}")));
}
}
```
Result:
![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif)
これはシンプルな例ですが、すでにGetがいかに強力であるかがわかると思います。プロジェクトが大きければ大きいほど、この差はもっと開くでしょう。
Getはチームでの作業を想定して設計されていますが、個人開発者の仕事もシンプルにしてくれます。
パフォーマンスを落とさず納期までにすべて納品。Getはすべての人に向いているわけではありませんが、このフレーズにぴんと来た人には確実に向いています!
# 三本柱
## 状態管理
Getの状態管理には、非リアクティブ(GetBuilder)と、リアクティブ(GetX/Obx)の2つのアプローチがあります。
### リアクティブな状態管理
リアクティブプログラミングは複雑であると言われ、多くの人に敬遠されています。GetXは、リアクティブプログラミングをシンプルなものに変えます:
* StreamControllerを作る必要はありません。
* 変数ごとにStreamBuilderをセットする必要はありません。
* 状態ごとにクラスを作る必要はありません。
* 初期値のためにgetを準備する必要はありません。
- コードの自動生成をする必要がありません。
GetにおけるリアクティブプログラミングはsetStateと同じように簡単です。
例えば、名前の変数があって、それを変更するたびに、その名前を使っているすべてのWidgetを自動で更新したい場合。
```dart
var name = 'Jonatas Borges';
```
このnameをObservable(監視可能)にするには, ".obs"を値の末尾に付けるだけです。
```dart
var name = 'Jonatas Borges'.obs;
```
UIでその値を表示し、値が変わるたびに内容を更新したい場合は次のようにします。
```dart
Obx(() => Text("${controller.name}"));
```
以上です。こんなに簡単なんですよ。
### 状態管理に関する詳細ドキュメント
**状態管理に関するより詳細な説明を知りたい方は[こちらの日本語ドキュメント](./documentation/ja_JP/state_management.md)をご覧ください。多くの事例や、非リアクティブな状態管理とリアクティブな状態管理の違いについても説明されています。**
GetXパワーがもたらす利点をより理解していただけると思います。
## Route管理
GetXはcontextなしでRoute/SnackBar/Dialog/BottomSheetを使用することができます。具体的に見ていきましょう。
いつものMaterialAppの前に「Get」を付け足して、GetMaterialAppにしましょう。
```dart
GetMaterialApp( // MaterialApp の前に Get
home: MyHome(),
)
```
新しいRouteに画面遷移するにはこのシンタックス。
```dart
Get.to(NextScreen());
```
名前付きRouteに画面遷移するにはこのシンタックス。名前付きRouteの詳細は[こちらの日本語ドキュメント](./documentation/ja_JP/route_management.md#navigation-with-named-routes)
```dart
Get.toNamed('/details');
```
SnackBar、Dialog、BottomSheetなど、Navigator.pop(context)で閉じられるRouteはこれで閉じます。
```dart
Get.back();
```
次の画面に移動した後、前の画面に戻れないようにする場合(スプラッシュスクリーンやログイン画面など)はこちら。
```dart
Get.off(NextScreen());
```
次の画面に進み、前のRouteをすべてキャンセルする場合(ショッピングカート、アンケート、テストなど)はこちら。
```dart
Get.offAll(NextScreen());
```
以上、contextを一度も使わなかったことに気付きましたか?これがGetでRoute管理を行う最大のメリットのひとつです。contextを使わないので、たとえばcontrollerクラスの中でも、これらのメソッドを実行することができます。
### Route管理に関する詳細ドキュメント
**Getは名前付きRouteでも動作し、Routeの下位レベルの制御も可能です。詳細なドキュメントは[こちらの日本語ドキュメント](./documentation/ja_JP/route_management.md)にあります。**
## 依存オブジェクト管理
Getにはシンプルで強力な依存オブジェクト注入機能があります。わずか1行のコードで、Provider contextやinheritedWidgetも使わず、BLoCやControllerのようなクラスのインスタンスを取得することができます。
```dart
Controller controller = Get.put(Controller()); // controller = Controller() とする代わりに
```
- 注: Getの状態管理機能を使用している場合は、Bindings APIにもご注目を。BindingsはビューとControllerを結びつけるのをより便利にしてくれます。
一つのクラスの中でControllerクラスをインスタンス化するのではなく、Getインスタンスの中でインスタンス化することで、アプリ全体でControllerが利用できるようになります。
**ヒント:** Getの依存オブジェクト注入機能の部分は、パッケージ全体の中でも他の部分と切り離されているので、たとえば、あなたのアプリがすでに状態管理機能を一部で使用していたとしても、それらを書き直す必要はなく、この依存オブジェクト注入機能をそのまま使用することができます。
```dart
controller.fetchApi();
```
色々なRouteを行き来した後に、あるControllerクラスのデータにアクセスする必要が生じたとしましょう。ProviderやGet_itなら再びそのクラスに依存オブジェクトを注入する必要がありますよね?Getの場合は違います。Getでは「find」と依頼するだけで、追加の依存オブジェクトの注入は必要ありません。
```dart
Controller controller = Get.find();
//マジックみたいですね。Getは正しいcontrollerをきちんと探してきてくれますよ。100万のcontrollerのインスタンスがあっても、Getは必ず正しいcontrollerを探し当てます。
```
そして、findで取得したコントローラーのデータをこのように呼び出すことができます。
```dart
Text(controller.textFromApi);
```
### 依存オブジェクト管理に関する詳細ドキュメント
**依存オブジェクト管理に関するより詳細な説明は[こちらの日本語ドキュメント](./documentation/ja_JP/dependency_management.md)をご覧ください。**
# ユーティリティ
## 多言語対応
### 翻訳ファイル
翻訳ファイルはシンプルなキーと値のMapとして保持されます。
翻訳を追加するには、クラスを作成して `Translations` を継承します。
```dart
import 'package:get/get.dart';
class Messages extends Translations {
@override
Map<String, Map<String, String>> get keys => {
'en_US': {
'hello': 'Hello World',
},
'de_DE': {
'hello': 'Hallo Welt',
}
};
}
```
#### 翻訳ファイルの利用
指定されたキーに `.tr` (translateのtr)を追加するだけで、`Get.locale` と `Get.fallbackLocale` の現在の値をに沿って適切な言語に翻訳されます。
```dart
Text('title'.tr);
```
#### 単数系と複数形に対応
```dart
var products = [];
Text('singularKey'.trPlural('pluralKey', products.length, Args));
```
#### パラメーターに対応
```dart
import 'package:get/get.dart';
Map<String, Map<String, String>> get keys => {
'en_US': {
'logged_in': 'logged in as @name with email @email',
},
'es_ES': {
'logged_in': 'iniciado sesión como @name con e-mail @email',
}
};
Text('logged_in'.trParams({
'name': 'Jhon',
'email': 'jhon@example.com'
}));
```
### ロケール
ロケールと翻訳を定義するため、`GetMaterialApp`にパラメータを渡します。
```dart
return GetMaterialApp(
translations: Messages(), // Translationsを継承したクラスのインスタンス
locale: Locale('en', 'US'), // このロケール設定に沿って翻訳が表示される
fallbackLocale: Locale('en', 'UK'), // 無効なロケールだったときのフォールバックを指定
);
```
#### ロケールの変更
ロケールを変更するには、`Get.updateLocale(locale)`を呼び出します。翻訳は新しいロケールに沿ってなされます。
```dart
var locale = Locale('en', 'US');
Get.updateLocale(locale);
```
#### システムのロケールを読み込む
システムのロケールを読み込むには、`Get.deviceLocale`を使用します。
```dart
return GetMaterialApp(
locale: Get.deviceLocale,
);
```
## Themeの変更
`GetMaterialApp`より上位のWidgetを使ってThemeを変更しないでください。Keyの重複を引き起こす可能性があります。アプリのThemeを変更するためには「ThemeProvider」Widgetを作成するという前時代的なアプローチが採られることが多いですが、**GetX™**ではこのようなことは必要ありません。
カスタムのThemeDataを作成したら、それを`Get.changeTheme`内に追加するだけです。
```dart
Get.changeTheme(ThemeData.light());
```
もし、`onTap`でThemeを変更するボタンを作りたいのであれば、以下の2つの**GetX™** APIを組み合わせることができます。
- Dark Theme が使われているかどうかをチェックするAPI
- Theme を変えるAPI(ボタンの`onPressed`の中に設置できます)
```dart
Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark());
```
Darkモードが有効であれば、_light theme_に切り替わり、Lightモードが有効なら、_dark theme_に切り替わります。
## GetConnect
GetConnect は、http または websocket を使用してバックエンドとフロントエンド間の通信を行う機能です。
### デフォルト設定
GetConnectを拡張することで、GET/POST/PUT/DELETE/SOCKETメソッドを使用して、Rest APIやウェブソケットと通信することができます。
```dart
class UserProvider extends GetConnect {
// Get リクエスト
Future<Response> getUser(int id) => get('http://youapi/users/$id');
// Post リクエスト
Future<Response> postUser(Map data) => post('http://youapi/users', body: data);
// File付き Post リクエスト
Future<Response<CasesModel>> postCases(List<int> image) {
final form = FormData({
'file': MultipartFile(image, filename: 'avatar.png'),
'otherFile': MultipartFile(image, filename: 'cover.png'),
});
return post('http://youapi/users/upload', form);
}
GetSocket userMessages() {
return socket('https://yourapi/users/socket');
}
}
```
### カスタム設定
GetConnect は高度なカスタマイズが可能です。ベースUrlの定義はもちろん、リクエストヘッダーを足したり、レスポンスボディに変更を加えたり、認証情報を追加したり、認証回数の制限を設けたりすることができるほか、リクエストをModelに変換するデコーダを定義することもできます。
```dart
class HomeProvider extends GetConnect {
@override
void onInit() {
// デフォルトデコーダーをセット
httpClient.defaultDecoder = CasesModel.fromJson;
httpClient.baseUrl = 'https://api.covid19api.com';
// baseUrlをセット
// リクエストヘッダーに 'apikey' プロパティを付け足しています。
httpClient.addRequestModifier((request) {
request.headers['apikey'] = '12345678';
return request;
});
// サーバーが"Brazil"を含むデータを送ってきてもユーザーに表示されることはありません。
// レスポンスがUIレイヤーに届けられる前にデータが取り除かれているからです。
httpClient.addResponseModifier<CasesModel>((request, response) {
CasesModel model = response.body;
if (model.countries.contains('Brazil')) {
model.countries.remove('Brazilll');
}
});
httpClient.addAuthenticator((request) async {
final response = await get("http://yourapi/token");
final token = response.body['token'];
// ヘッダーをセット
request.headers['Authorization'] = "$token";
return request;
});
// HttpStatus が HttpStatus.unauthorized である限り、
// 3回まで認証が試みられます。
httpClient.maxAuthRetries = 3;
}
}
@override
Future<Response<CasesModel>> getCases(String path) => get(path);
}
```
## GetPageにミドルウェアを設定
GetPageに新しいプロパティが追加され、GetMiddleWareのListを設定することができるようになりました。GetMiddleWareは設定した任意の順序で実行されます。
**注**: GetPageにミドルウェアを設定すると、そのページの子ページはすべて同じミドルウェアを自動的に持つことになります。
### 実行優先度
GetMiddlewareに設定したpriority(優先度)の若い順にミドルウェアが実行されます。
```dart
final middlewares = [
GetMiddleware(priority: 2),
GetMiddleware(priority: 5),
GetMiddleware(priority: 4),
GetMiddleware(priority: -8),
];
```
この場合の実行順序は **-8 => 2 => 4 => 5**
### redirect
redirect関数は、Routeを呼び出してページが検索されると実行されます。リダイレクト先のRouteSettingsが戻り値となります。もしくはnullを与えれば、リダイレクトは行われません。
```dart
RouteSettings redirect(String route) {
final authService = Get.find<AuthService>();
return authService.authed.value ? null : RouteSettings(name: '/login')
}
```
### onPageCalled
onPageCalled関数は、ページが呼び出された直後に実行されます。
この関数を使ってページの内容を変更したり、新しいページを作成したりすることができます。
```dart
GetPage onPageCalled(GetPage page) {
final authService = Get.find<AuthService>();
return page.copyWith(title: 'Welcome ${authService.UserName}');
}
```
### onBindingsStart
onBindingsStart関数は、Bindingsが初期化される直前に実行されます。
たとえば、ページのBindingsを変更することもできます。
```dart
List<Bindings> onBindingsStart(List<Bindings> bindings) {
final authService = Get.find<AuthService>();
if (authService.isAdmin) {
bindings.add(AdminBinding());
}
return bindings;
}
```
### onPageBuildStart
onPageBuildStart関数は、Bindingsが初期化された直後、ページWidgetが作成される前に実行されます。
```dart
GetPageBuilder onPageBuildStart(GetPageBuilder page) {
print('bindings are ready');
return page;
}
```
### onPageBuilt
onPageBuilt関数は、GetPage.page(ページのビルダー)が呼び出された直後に実行され、表示されるWidgetを結果として受け取ることができます。
### onPageDispose
onPageDispose関数は、ページに関するすべてのオブジェクト(Controller、ビューなど)が破棄された直後に実行されます。
## その他API
```dart
// 現在の画面に渡されているargs(引数)を取得
Get.arguments
// 直前のRouteの名前("/" など)を取得
Get.previousRoute
// 現在のRouteオブジェクトを取得
Get.rawRoute
// GetObserverからRoutingを取得
Get.routing
// SnackBarが開いているかチェック
Get.isSnackbarOpen
// Dialogが開いているかチェック
Get.isDialogOpen
// BottomSheetが開いているかチェック
Get.isBottomSheetOpen
// Routeを削除
Get.removeRoute()
// 引数のRoutePredicateがtrueを返すまで画面を戻る
Get.until()
// 引数で指定したRouteに進み、RoutePredicateがtrueを返すまで画面を戻る
Get.offUntil()
// 引数で指定した名前付きRouteに進み、RoutePredicateがtrueを返すまで画面を戻る
Get.offNamedUntil()
// アプリがどのプラットフォームで実行されているかのチェック
GetPlatform.isAndroid
GetPlatform.isIOS
GetPlatform.isMacOS
GetPlatform.isWindows
GetPlatform.isLinux
GetPlatform.isFuchsia
// アプリがどのデバイスで実行されているかのチェック
GetPlatform.isMobile
GetPlatform.isDesktop
// プラットフォームとデバイスのチェックは独立
// 同じOSでもウェブで実行されているのか、ネイティブで実行されているのか区別
GetPlatform.isWeb
// MediaQuery.of(context).size.height と同じ
// ただしimmutable
Get.height
Get.width
// Navigatorの現在のcontextを取得
Get.context
// SnackBar/Dialog/BottomSheet などフォアグラウンドのcontextを取得
Get.overlayContext
// 注: 以降のメソッドはcontextの拡張メソッドです。
// contextと同じくUIのどこからでもアクセスできます。
// ウィンドウサイズの変更などに合わせて変わる height/width を取得
context.width
context.height
// 画面の半分のサイズ,1/3のサイズなどを取得
// レスポンシブなデザインの場合に便利
// オプションのパラメーター dividedBy で割る数を指定
// オプションのパラメーター reducedBy でパーセンテージを指定
context.heightTransformer()
context.widthTransformer()
/// MediaQuery.of(context).size とほぼ同じ
context.mediaQuerySize()
/// MediaQuery.of(context).padding とほぼ同じ
context.mediaQueryPadding()
/// MediaQuery.of(context).viewPadding とほぼ同じ
context.mediaQueryViewPadding()
/// MediaQuery.of(context).viewInsets とほぼ同じ
context.mediaQueryViewInsets()
/// MediaQuery.of(context).orientation とほぼ同じ
context.orientation()
/// デバイスがランドスケープ(横長)モードかどうかチェック
context.isLandscape()
/// デバイスがポートレート(縦長)モードかどうかチェック
context.isPortrait()
/// MediaQuery.of(context).devicePixelRatio とほぼ同じ
context.devicePixelRatio()
/// MediaQuery.of(context).textScaleFactor とほぼ同じ
context.textScaleFactor()
/// 画面の短辺の長さを取得
context.mediaQueryShortestSide()
/// 画面の横幅が800より大きい場合にtrueを返す
context.showNavbar()
/// 画面の短辺が600より小さい場合にtrueを返す
context.isPhone()
/// 画面の短辺が600より小さい場合にtrueを返す
context.isSmallTablet()
/// 画面の短辺が720より大きい場合にtrueを返す
context.isLargeTablet()
/// デバイスがタブレットの場合にtrueを返す
context.isTablet()
/// 画面サイズに合わせて value<T> を返す
/// たとえば:
/// 短辺が300より小さい → watchパラメーターの値を返す
/// 短辺が600より小さい → mobileパラメーターの値を返す
/// 短辺が1200より小さい → tabletパラメーターの値を返す
/// 横幅が1200より大きい → desktopパラメーターの値を返す
context.responsiveValue<T>()
```
### オプションのグローバル設定と手動設定
GetMaterialApp はすべてあなたの代わりに設定してくれますが、手動で設定を施したい場合は MaterialApp の navigatorKey と navigatorObservers の値を指定してください。
```dart
MaterialApp(
navigatorKey: Get.key,
navigatorObservers: [GetObserver()],
);
```
`GetObserver`内で独自のミドルウェアを使用することもできます。これは他に影響を及ぼすことはありません。
```dart
MaterialApp(
navigatorKey: Get.key,
navigatorObservers: [
GetObserver(MiddleWare.observer) // ここ
],
);
```
`Get` クラスに_グローバル設定_を施すことができます。Routeをプッシュする前のコードに `Get.config` を追加するだけです。もしくは、`GetMaterialApp` 内で直接設定することもできます。
```dart
GetMaterialApp(
enableLog: true,
defaultTransition: Transition.fade,
opaqueRoute: Get.isOpaqueRouteDefault,
popGesture: Get.isPopGestureEnable,
transitionDuration: Get.defaultDurationTransition,
defaultGlobalState: Get.defaultGlobalState,
);
Get.config(
enableLog = true,
defaultPopGesture = true,
defaultTransition = Transitions.cupertino
)
```
オプションで、すべてのログメッセージを `Get` からリダイレクトさせることができます。
お好みのロギングパッケージを使ってログを取得したい場合はこのようにしてください。
```dart
GetMaterialApp(
enableLog: true,
logWriterCallback: localLogWriter,
);
void localLogWriter(String text, {bool isError = false}) {
// ここでお好みのロギングパッケージにメッセージを渡してください
// enableLog: false にしても、ログメッセージはこのコールバックでプッシュされる点ご注意を
// ログが有効かどうかのチェックは Get.isLogEnable で可能
}
```
### ローカルステートWidget
ローカルステートWidgetは、1つの変数の状態を一時的かつローカルに管理したい場合に便利です。
シンプルなValueBuilderとリアクティブなObxValueの2種類があります。
たとえば、`TextField` Widgetの obscureText プロパティを切り替えたり、折りたたみ可能なパネルをカスタムで作成したり、`BottomNavigation` の現在のインデックス値を変更して内容を変更したりといった用途に最適です。
#### ValueBuilder
setStateでお馴染みの `StatefulWidget` をシンプルにしたビルダーWidgetです。
```dart
ValueBuilder<bool>(
initialValue: false,
builder: (value, updateFn) => Switch(
value: value,
onChanged: updateFn, // ( newValue ) => updateFn( newValue ) も可
),
// builderメソッドの外で何か実行する場合
onUpdate: (value) => print("Value updated: $value"),
onDispose: () => print("Widget unmounted"),
),
```
#### ObxValue
[`ValueBuilder`](#valuebuilder)に似ていますが、これはそのリアクティブバージョンです。Rxインスタンス(.obsを付けたときに戻る値です)を渡すと自動で更新されます。すごいでしょ?
```dart
ObxValue((data) => Switch(
value: data.value,
onChanged: data,
// Rxには_呼び出し可能な_関数が備わっているのでこれだけでOK
// (flag) => data.value = flag も可能
),
false.obs,
),
```
## お役立ちTIPS
`.obs`が付いた型(_Rx_型とも呼ばれる)には、さまざまな内部メソッドや演算子が用意されています。
> `.obs`が付いたプロパティが **実際の値** だと信じてしまいがちですが...間違えないように!
> 我々がcontrollerにおける変数の型宣言を省略してvarとしているのはDartのコンパイラが賢い上に、
> そのほうがコードがすっきる見えるからですが…
```dart
var message = 'Hello world'.obs;
print( 'Message "$message" has Type ${message.runtimeType}');
```
`message`を _print_ することで実際の文字列が取り出されはしますが、型は **RxString** です!
そのため `message.substring( 0, 4 )` などといったことはできません。
Stringのメソッドにアクセスするには _observable_ の中にある実際の値 `value` にアクセスします。
アクセスには `.value`を使うのが通常ですが、他の方法もあるのでご紹介します。
```dart
final name = 'GetX'.obs;
// 新しい値が現在のものと異なる場合のみ Stream が更新されます。
name.value = 'Hey';
// すべてのRxプロパティは「呼び出し可能」で、valueを返してくれます。
// ただし `null` は受付不可。nullの場合はUIが更新されない。
name('Hello');
// これはgetterみたいなものです。'Hello' を返します。
name() ;
/// num型の場合
final count = 0.obs;
// num型の非破壊的な演算子はすべて使えます。
count + 1;
// 注意! この場合は`count`がfinalなら有効ではないです。varなら有効。
count += 1;
// 比較演算子も使用可能
count > 2;
/// bool型の場合
final flag = false.obs;
// true/false を入れ替えることができます。
flag.toggle();
/// すべての型
// `value` を null にセット。
flag.nil();
// toString(), toJson() などの操作はすべて `value` が対象になります。
print( count ); // RxIntの `toString()` が呼び出されて数字がprintされる。
final abc = [0,1,2].obs;
// json配列に変換した値と、'RxList' がprintされます。
// JsonはすべてのRx型でサポートされています!
print('json: ${jsonEncode(abc)}, type: ${abc.runtimeType}');
// RxMap、RxList、RxSetはそれぞれの元の型を拡張した特別なRx型です。
// たとえばRxListは通常のListとして扱うことができる上にリアクティブです。
abc.add(12); // 12をListにプッシュし、Streamを更新してくれます。
abc[3]; // Listと同様にインデックス番号3の値を取得してくれます。
// 等価演算子はRx型と元の型でも動作しますが、.hashCode は常にvalueから取得します。
final number = 12.obs;
print( number == 12 ); // true
/// カスタムのRxモデル
// toJson()やtoString()をモデルクラスに設定すれば、.obsからでもprintされるように実装可能。
class User {
String name, last;
int age;
User({this.name, this.last, this.age});
@override
String toString() => '$name $last, $age years old';
}
final user = User(name: 'John', last: 'Doe', age: 33).obs;
// `user` 自体はリアクティブですが、その中のプロパティはリアクティブではありません。
// そのため、このようにプロパティの値を変更してもWidgetは更新されません。
user.value.name = 'Roi';
// `Rx` には自ら変更を検知する手段がないからです。
// そのため、カスタムクラスの場合はこのようにWidgetに変更を知らせる必要があります。
user.refresh();
// もしくは `update()` メソッドを使用してください。
user.update((value){
value.name='Roi';
});
print( user );
```
#### StateMixin
`UI`の状態を管理するもう一つの手法として、`StateMixin<T>`を利用する方法があります。
controllerクラスに`with`を使って`StateMixin<T>`を追加することで実装可能です。
``` dart
class Controller extends GetController with StateMixin<User>{}
```
`change()`メソッドにより好きなタイミングで状態を変更することができます。
このようにデータと状態を渡すだけです。
```dart
change(data, status: RxStatus.success());
```
RxStatus には以下のステータスが存在します。
``` dart
RxStatus.loading();
RxStatus.success();
RxStatus.empty();
RxStatus.error('message');
```
ステータスごとにUIを設定するにはこのようにします。
```dart
class OtherClass extends GetView<Controller> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: controller.obx(
(state)=>Text(state.name),
// ローディング中はカスタムのインジケーターの設定も可能ですが、
// デフォルトで Center(child:CircularProgressIndicator()) となります。
onLoading: CustomLoadingIndicator(),
onEmpty: Text('No data found'),
// 同様にエラーWidgetはカスタム可能ですが、
// デフォルトは Center(child:Text(error)) です。
onError: (error)=>Text(error),
),
);
}
```
#### GetView
このWidgetは私のお気に入りです。とてもシンプルで扱いやすいですよ!
このWidgetを一言で表現すると、「controllerをgetterに持つ `const` な StatelessWidget」です。
```dart
class AwesomeController extends GetController {
final String title = 'My Awesome View';
}
// controllerの `型` を渡すのを忘れずに!
class AwesomeView extends GetView<AwesomeController> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(20),
child: Text(controller.title), // `controller.なんとか` でアクセス
);
}
}
```
#### GetResponsiveView
GetViewをレスポンシブデザインに対応させたい場合はこのWidgetを継承してください。
画面サイズやデバイスタイプなどの情報を持つ `screen` プロパティを保持しています。
##### 使い方
Widgetをビルドする方法は2つあります。
- `builder` メソッドを使う。
- `desktop`, `tablet`, `phone`, `watch` メソッドを使う。
画面サイズ、デバイスタイプに応じたWidgetがビルドされます。
たとえば画面が [ScreenType.Tablet] なら `tablet` メソッドが実行されます。
**注:** `alwaysUseBuilder` プロパティをfalseにする必要があります。
`settings` プロパティでブレイクポイントを設定することもできます。
![](https://github.com/SchabanBo/get_page_example/blob/master/docs/Example.gif?raw=true)
この画面のコード
[コード](https://github.com/SchabanBo/get_page_example/blob/master/lib/pages/responsive_example/responsive_view.dart)
#### GetWidget
このWidgetはあまり知られておらず、使用するケースは稀です。
GetViewとの違いは、Controllerを`キャッシュ`してくれる点です。
このキャッシュがあるため `const` にはできません。
> それでは一体いつControllerをキャッシュする必要があるのかって?
それは **GetX** のこれまた使う機会の少ない `Get.create()` を使うときです。
`Get.create(()=>Controller())` は `Get.find<Controller>()` を実行するたびに
新しいControllerインスタンスを生成します。
そこで `GetWidget` の出番です。たとえば、Todoアイテムのリスト内容を保持したいとき。
Widgetが更新されてもアイテムはControllerのキャッシュを参照してくれます。
#### GetxService
このクラスは `GetxController` に似ており、同様のライフサイクル(`onInit()`, `onReady()`, `onClose()`)を共有しますが、そこに「ロジック」はありません。**GetX**の依存オブジェクト注入システムに、このサブクラスがメモリから **削除できない** ということを知らせるだけです。
そのため `Get.find()` で `ApiService`, `StorageService`, `CacheService` のようなサービス系クラスにいつでもアクセスできるようにしておくと非常に便利です。
```dart
Future<void> main() async {
await initServices(); /// サービスクラスの初期化をawait
runApp(SomeApp());
}
/// Flutterアプリ実行前にサービスクラスを初期化してフローをコントロールするのは賢いやり方です。
/// たとえば GetMaterialAppを更新する必要がないようにUser別の
/// Theme、apiKey、言語設定などをApiサービス実行前にロードしたり。
void initServices() async {
print('starting services ...');
/// get_storage, hive, shared_pref の初期化はここで行います。
/// あるいは moor の connection など非同期のメソッドならなんでも。
await Get.putAsync(() => DbService().init());
await Get.putAsync(SettingsService()).init();
print('All services started...');
}
class DbService extends GetxService {
Future<DbService> init() async {
print('$runtimeType delays 2 sec');
await 2.delay();
print('$runtimeType ready!');
return this;
}
}
class SettingsService extends GetxService {
void init() async {
print('$runtimeType delays 1 sec');
await 1.delay();
print('$runtimeType ready!');
}
}
```
`GetxService` を破棄する唯一の方法は `Get.reset()` メソッドを使うことです。
これはアプリにおける「ホットリブート」のようなものです。あるクラスのインスタンスを
ライフサイクルの間ずっと残しておきたい場合は `GetxService` を使うというのを覚えておいてください。
## テストの実行
Controllerのライフサイクル含め、他のクラスと同様にテストを実行することができます。
```dart
class Controller extends GetxController {
@override
void onInit() {
super.onInit();
// 値を name2 に変更
name.value = 'name2';
}
@override
void onClose() {
name.value = '';
super.onClose();
}
final name = 'name1'.obs;
void changeName() => name.value = 'name3';
}
void main() {
test('''
Test the state of the reactive variable "name" across all of its lifecycles''',
() {
/// ライフサイクルごとのテストは必ずしも行う必要はありませんが、
/// GetXの依存オブジェクト注入機能を使用しているのであれば実行をおすすめします。
final controller = Controller();
expect(controller.name.value, 'name1');
/// このようにライフサイクル経過ごとの状態をテスト可能です。
Get.put(controller); // onInit が実行される
expect(controller.name.value, 'name2');
/// 関数もテストしましょう
controller.changeName();
expect(controller.name.value, 'name3');
/// onClose が実行される
Get.delete<Controller>();
expect(controller.name.value, '');
});
}
```
#### mockitoやmocktailを使う場合
GetxController/GetxService をモックする場合 Mock をミックスインしてください。
```dart
class NotificationServiceMock extends GetxService with Mock implements NotificationService {}
```
#### Get.reset()
WidgetやGroupのテスト時に、テストの最後かtearDownの中で Get.reset() を実行することで設定をリセットすることができます。
#### Get.testMode
Controllerの中でナビゲーションを使用している場合は、`Get.testMode = true`をmainの開始で実行してください。
# バージョン2.0からの破壊的変更
1- Rx型の名称
| 変更前 | 変更後 |
| ------- | ---------- |
| StringX | `RxString` |
| IntX | `RxInt` |
| MapX | `RxMap` |
| ListX | `RxList` |
| NumX | `RxNum` |
| DoubleX | `RxDouble` |
RxControllerとGetBuilderが統合され、Controllerにどれを使うか覚えておく必要がなくなりました。GetxControllerを使うだけで、リアクティブと非リアクティブな状態管理の両方に対応できるようになりました。
2- 名前付きRoute
変更前:
```dart
GetMaterialApp(
namedRoutes: {
'/': GetRoute(page: Home()),
}
)
```
変更後:
```dart
GetMaterialApp(
getPages: [
GetPage(name: '/', page: () => Home()),
]
)
```
変更の効果:
ページ表示にはパラメータやログイントークンを起点にする方法もありますが、以前のアプローチではこれができず、柔軟性に欠けていました。
ページを関数から取得するよう変更したことで、このようなアプローチを可能にし、アプリ起動直後にRouteがメモリに割り当てられることもないため、RAMの消費量を大幅に削減することもできました。
```dart
GetStorage box = GetStorage();
GetMaterialApp(
getPages: [
GetPage(name: '/', page:(){
return box.hasData('token') ? Home() : Login();
})
]
)
```
# なぜGetXなのか
1- Flutterのアップデートが重なると、依存パッケージがうまく動かなくなることがあります。コンパイルエラーを起こしたり、その時点で解決方法がないようなエラーが発生したり。開発者はそのエラーを追跡し、該当リポジトリにissueを提起し、問題が解決されるのを待つ必要があります。Getは開発に必要な主要リソース(状態管理、依存オブジェクト管理、Route管理)を一元化し、Pubspecにパッケージを1つ追加するだけでコーディングを開始することができます。Flutterがアップデートしたときに必要なことは、Getも併せてアップデートすることだけです。それですぐに作業を再開できます。またGetはパッケージ間の互換性の問題も解消します。互いに依存するパッケージAの最新バージョンとBの最新バージョンの間に互換性がない、ということが何度あったでしょうか。Getを使えばすべてが同じパッケージ内にあるため、互換性の心配はありません。
2- Flutterは手軽で素晴らしいフレームワークですが、`Navigator.of(context).push (context, builder [...]`のように、ほとんどの開発者にとって不要な定型文が一部にあります。Getを使えばそのような定型文を簡素化できます。Routeを呼ぶためだけに8行のコードを書く代わりに、`Get.to(Home())`を実行すれば、次の画面に遷移することができるのです。またウェブURLを動的なものにすることは現在Flutterでは本当に骨の折れる作業ですが、GetXを使えば非常に簡単です。そしてFlutterにおける状態管理と依存オブジェクト管理については、たくさんのパターンやパッケージがあるので多くの議論を生んでいます。しかしGetXのアプローチは大変シンプルです。これは一例ですが、変数の最後に「.obs」を追加して「Obx()」の中にWidgetを配置するだけで、その変数の状態変化が自動でWidgetに反映されます。
3- GetXではパフォーマンスのことをあまり気にせず開発ができます。Flutterのパフォーマンスはそれだけで素晴らしいものですが、状態管理と併せて BLoC / データストア / Controller などを届けるためのサービスロケーターを使用することを想像してみてください。そのインスタンスが必要ないときはリソースを解放するイベントを明示的に呼び出さなければなりません。そんなとき、使用されなくなったら自動でメモリから削除してくれればいいのに、と考えたことはありませんか?それを実現してくれるのがGetXです。SmartManagement機能により未使用のリソースはすべて自動でメモリから破棄されるので、本来の開発作業に集中することができます。メモリ管理のためのロジックを作らなくても、常に必要最小限のリソースを使っていることが保証されるのです。
4- コードのデカップリング(分離)がしやすい。「ビューをビジネスロジックから分離する」というコンセプトを聞いたことがあるかもしれません。これはなにもBLoC、MVC、MVVMに限ったことではなく、どのアーキテクチャパターンもこのコンセプトが考え方の基本にあると言っていいでしょう。しかし、Flutterではcontextの使用によりこのコンセプトが薄まってしまいがちです。
InheritedWidgetを参照するためにcontextが必要なとき、ビューの中でそれを使用するか、引数としてcontextを渡しますよね?私はこの方法は美しくないと感じます。常にビュー内のビジネスロジックに依存しなければならないのは、特にチームで仕事をする場面においては不便だと感じます。GetXによるアプローチでは、StatefulWidgetやinitStateなどの使用を禁止しているわけではありませんが、それらよりもずっとスッキリ書けるようになっています。Controller自体にライフサイクルがあるため、たとえばREST APIのリクエストを行うときも、ビューの中の何かに依存するということがありません。Controllerのライフサイクルの一つである onInit を使用してhttpを呼び出し、データが到着すると変数にセットされます。GetXはリアクティブな変数を扱うことができるので、インスタンス変数が変わりし次第、その変数に依存するWidgetがすべて自動更新されます。これによりUIの担当者はWidgetの見た目に注力することができ、ボタンクリックなどのユーザーイベント以外のものをビジネスロジックに渡す必要がなくなります。その一方でビジネスロジックの担当者はビジネスロジックだけに集中し、個別のテストを簡単に行うことができます。
GetXライブラリは今後も更新され続け、新しい機能を実装していきます。気軽にプルリクエストを出していただき、ライブラリの成長に貢献していただけるとうれしいです。
# コミュニティ
## コミュニティチャンネル
GetXコミュニティは非常に活発で有益な情報であふれています。ご質問がある場合や、このフレームワークの使用に関して支援が必要な場合は、ぜひコミュニティチャンネルにご参加ください。このリポジトリは、issueの提起およびリクエスト専用ですが、気軽にコミュニティにご参加いただければ幸いです。
| **Slack** | **Discord** | **Telegram** |
| :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| [![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](https://communityinviter.com/apps/getxworkspace/getx) | [![Discord Shield](https://img.shields.io/discord/722900883784073290.svg?logo=discord)](https://discord.com/invite/9Hpt99N) | [![Telegram](https://img.shields.io/badge/chat-on%20Telegram-blue.svg)](https://t.me/joinchat/PhdbJRmsZNpAqSLJL6bH7g) |
## コントリビュート方法
_GetXプロジェクトに貢献してみませんか?あなたをコントリビューターの一人としてご紹介できるのを楽しみにしています。GetおよびFlutterをより良いものにするためのコントリビュート例をご紹介します。_
- Readmeの多言語対応。
- Readmeの追加ドキュメント執筆 (ドキュメントで触れられていない機能がまだまだたくさんあります)。
- Getの使い方を紹介する記事やビデオの作成(Readmeに掲載させていただきます。将来的にWikiができればそこにも掲載予定)。
- コードやテストのプルリクエスト。
- 新機能の提案。
どのような形の貢献であれ歓迎しますので、ぜひコミュニティにご参加ください!
## GetXに関する記事と動画
- [Flutter Getx EcoSystem package for arabic people](https://www.youtube.com/playlist?list=PLV1fXIAyjeuZ6M8m56zajMUwu4uE3-SL0) - Tutorial by [Pesa Coder](https://github.com/UsamaElgendy).
- [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).
- [Complete GetX™ Navigation](https://www.youtube.com/watch?v=RaqPIoJSTtI) - Route management video by Amateur Coder.
- [Complete GetX State Management](https://www.youtube.com/watch?v=CNpXbeI_slw) - State management video by Amateur Coder.
- [GetX™ Other Features](https://youtu.be/ttQtlX_Q0eU) - Utils, storage, bindings and other features video by Amateur Coder.
- [Firestore User with GetX | Todo App](https://www.youtube.com/watch?v=BiV0DcXgk58) - Video by Amateur Coder.
- [Firebase Auth with GetX | Todo App](https://www.youtube.com/watch?v=-H-T_BSgfOE) - Video by Amateur Coder.
- [The Flutter GetX™ Ecosystem ~ State Management](https://medium.com/flutter-community/the-flutter-getx-ecosystem-state-management-881c7235511d) - State management by [Aachman Garg](https://github.com/imaachman).
- [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).
- [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.
- [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.
- [GetX Flutter Firebase Auth Example](https://medium.com/@jeffmcmorris/getx-flutter-firebase-auth-example-b383c1dd1de2) - Article by Jeff McMorris.
- [Flutter State Management with GetX – Complete App](https://www.appwithflutter.com/flutter-state-management-with-getx/) - by App With Flutter.
- [Flutter Routing with Animation using Get Package](https://www.appwithflutter.com/flutter-routing-using-get-package/) - by App With Flutter.
- [A minimal example on dartpad](https://dartpad.dev/2b3d0d6f9d4e312c5fdbefc414c1727e?) - by [Roi Peker](https://github.com/roipeker)
... ...
... ... @@ -31,6 +31,8 @@
[![Polish](https://img.shields.io/badge/Language-Polish-blueviolet?style=for-the-badge)](README.pl.md)
[![Korean](https://img.shields.io/badge/Language-Korean-blueviolet?style=for-the-badge)](README.ko-kr.md)
[![French](https://img.shields.io/badge/Language-French-blueviolet?style=for-the-badge)](README-fr.md)
[![Japanese](https://img.shields.io/badge/Language-Japanese-blueviolet?style=for-the-badge)](README.ja-JP.md)
</div>
... ...
# Dependency Management
- [Dependency Management](#dependency-management)
- [Instancing methods](#instancing-methods)
- [Get.put()](#getput)
- [Get.lazyPut](#getlazyput)
- [Get.putAsync](#getputasync)
- [Get.create](#getcreate)
- [Using instantiated methods/classes](#using-instantiated-methodsclasses)
- [Specifying an alternate instance](#specifying-an-alternate-instance)
- [Differences between methods](#differences-between-methods)
- [Bindings](#bindings)
- [Bindings class](#bindings-class)
- [BindingsBuilder](#bindingsbuilder)
- [SmartManagement](#smartmanagement)
- [How to change](#how-to-change)
- [SmartManagement.full](#smartmanagementfull)
- [SmartManagement.onlyBuilders](#smartmanagementonlybuilders)
- [SmartManagement.keepFactory](#smartmanagementkeepfactory)
- [How bindings work under the hood](#how-bindings-work-under-the-hood)
- [Notes](#notes)
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:
```dart
Controller controller = Get.put(Controller()); // Rather Controller controller = Controller();
```
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.
So you can use your controller (or Bloc class) normally
- Note: If you are using Get's State Manager, pay more attention to the [Bindings](#bindings) api, which will make easier to connect your view to your controller.
- Note²: Get dependency management is decloupled 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 change that, you can use this dependency injection manager with no problems at all
## Instancing methods
The methods and it's configurable parameters are:
### Get.put()
The most common way of inserting a dependency. Good for the controllers of your views for example.
```dart
Get.put<SomeClass>(SomeClass());
Get.put<LoginController>(LoginController(), permanent: true);
Get.put<ListItemController>(ListItemController, tag: "some unique string");
```
This is all options you can set when using put:
```dart
Get.put<S>(
// mandatory: the class that you want to get to save, like a controller or anything
// note: "S" means that it can be a class of any type
S dependency
// optional: this is for when you want multiple classess that are of the same type
// since you normally get a class by using Get.find<Controller>(),
// you need to use tag to tell which instance you need
// must be unique string
String tag,
// optional: by default, get will dispose instances after they are not used anymore (example,
// the controller of a view that is closed), but you might need that the instance
// to be kept there throughout the entire app, like an instance of sharedPreferences or something
// so you use this
// defaults to false
bool permanent = false,
// optional: allows you after using an abstract class in a test, replace it with another one and follow the test.
// defaults to false
bool overrideAbstract = false,
// optional: allows you to create the dependency using function instead of the dependency itself.
// this one is not commonly used
InstanceBuilderCallback<S> builder,
)
```
### Get.lazyPut
It is possible to lazyLoad a dependency so that it will be instantiated only when is used. Very useful for computational expensive classes or if you want to instantiate several classes in just one place (like in a Bindings class) and you know you will not gonna use that class at that time.
```dart
/// ApiMock will only be called when someone uses Get.find<ApiMock> for the first time
Get.lazyPut<ApiMock>(() => ApiMock());
Get.lazyPut<FirebaseAuth>(
() {
// ... some logic if needed
return FirebaseAuth();
},
tag: Math.random().toString(),
fenix: true
)
Get.lazyPut<Controller>( () => Controller() )
```
This is all options you can set when using lazyPut:
```dart
Get.lazyPut<S>(
// mandatory: a method that will be executed when your class is called for the first time
InstanceBuilderCallback builder,
// optional: same as Get.put(), it is used for when you want multiple different instance of a same class
// must be unique
String tag,
// optional: It is similar to "permanent", the difference is that the instance is discarded when
// is not being used, but when it's use is needed again, Get will recreate the instance
// just the same as "SmartManagement.keepFactory" in the bindings api
// defaults to false
bool fenix = false
)
```
### Get.putAsync
If you want to register an asynchronous instance, you can use `Get.putAsync`:
```dart
Get.putAsync<SharedPreferences>(() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('counter', 12345);
return prefs;
});
Get.putAsync<YourAsyncClass>( () async => await YourAsyncClass() )
```
This is all options you can set when using putAsync:
```dart
Get.putAsync<S>(
// mandatory: an async method that will be executed to instantiate your class
AsyncInstanceBuilderCallback<S> builder,
// optional: same as Get.put(), it is used for when you want multiple different instance of a same class
// must be unique
String tag,
// optional: same as in Get.put(), used when you need to maintain that instance alive in the entire app
// defaults to false
bool permanent = false
)
```
### Get.create
This one is tricky. A detailed explanation of what this is and the differences between the other one can be found on [Differences between methods:](#differences-between-methods) section
```dart
Get.Create<SomeClass>(() => SomeClass());
Get.Create<LoginController>(() => LoginController());
```
This is all options you can set when using create:
```dart
Get.create<S>(
// required: a function that returns a class that will be "fabricated" every
// time `Get.find()` is called
// Example: Get.create<YourClass>(() => YourClass())
FcBuilderFunc<S> builder,
// optional: just like Get.put(), but it is used when you need multiple instances
// of a of a same class
// Useful in case you have a list that each item need it's own controller
// needs to be a unique string. Just change from tag to name
String name,
// optional: just like int`Get.put()`, it is for when you need to keep the
// instance alive thoughout the entire app. The difference is in Get.create
// permanent is true by default
bool permanent = true
```
## Using instantiated methods/classes
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:
```dart
final controller = Get.find<Controller>();
// OR
Controller controller = Get.find();
// 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.
```
And then you will be able to recover your controller data that was obtained back there:
```dart
Text(controller.textFromApi);
```
Since the returned value is a normal class, you can do anything you want:
```dart
int count = Get.find<SharedPreferences>().getInt('counter');
print(count); // out: 12345
```
To remove an instance of Get:
```dart
Get.delete<Controller>(); //usually you don't need to do this because GetX already delete unused controllers
```
## Specifying an alternate instance
A currently inserted instance can be replaced with a similar or extended class instance by using the `replace` or `lazyReplace` method. This can then be retrieved by using the original class.
```dart
abstract class BaseClass {}
class ParentClass extends BaseClass {}
class ChildClass extends ParentClass {
bool isChild = true;
}
Get.put<BaseClass>(ParentClass());
Get.replace<BaseClass>(ChildClass());
final instance = Get.find<BaseClass>();
print(instance is ChildClass); //true
class OtherClass extends BaseClass {}
Get.lazyReplace<BaseClass>(() => OtherClass());
final instance = Get.find<BaseClass>();
print(instance is ChildClass); // false
print(instance is OtherClass); //true
```
## Differences between methods
First, let's of the `fenix` of Get.lazyPut and the `permanent` of the other methods.
The fundamental difference between `permanent` and `fenix` is how you want to store your instances.
Reinforcing: by default, GetX deletes instances when they are not in use.
It means that: If screen 1 has controller 1 and screen 2 has controller 2 and you remove the first route from stack, (like if you use `Get.off()` or `Get.offNamed()`) the controller 1 lost its use so it will be erased.
But if you want to opt for using `permanent:true`, then the controller will not be lost in this transition - which is very useful for services that you want to keep alive throughout the entire application.
`fenix` in the other hand is for services that you don't worry in losing between screen changes, but when you need that service, you expect that it is alive. So basically, it will dispose the unused controller/service/class, but when you need it, it will "recreate from the ashes" a new instance.
Proceeding with the differences between methods:
- Get.put and Get.putAsync follows the same creation order, with the difference that the second uses an asynchronous method: those two methods creates and initializes the instance. That one is inserted directly in the memory, using the internal method `insert` with the parameters `permanent: false` and `isSingleton: true` (this isSingleton parameter only purpose is to tell if it is to use the dependency on `dependency` or if it is to use the dependency on `FcBuilderFunc`). After that, `Get.find()` is called that immediately initialize the instances that are on memory.
- Get.create: As the name implies, it will "create" your dependency! Similar to `Get.put()`, it also calls the internal method `insert` to instancing. But `permanent` became true and `isSingleton` became false (since we are "creating" our dependency, there is no way for it to be a singleton instace, that's why is false). And because it has `permanent: true`, we have by default the benefit of not losing it between screens! Also, `Get.find()` is not called immediately, it wait to be used in the screen to be called. It is created this way to make use of the parameter `permanent`, since then, worth noticing, `Get.create()` was made with the goal of create not shared instances, but don't get disposed, like for example a button in a listView, that you want a unique instance for that list - because of that, Get.create must be used together with GetWidget.
- Get.lazyPut: As the name implies, it is a lazy proccess. The instance is create, but it is not called to be used immediately, it remains waiting to be called. Contrary to the other methods, `insert` is not called here. Instead, the instance is inserted in another part of the memory, a part responsible to tell if the instance can be recreated or not, let's call it "factory". If we want to create something to be used later, it will not be mix with things been used right now. And here is where `fenix` magic enters: if you opt to leaving `fenix: false`, and your `smartManagement` are not `keepFactory`, then when using `Get.find` the instance will change the place in the memory from the "factory" to common instance memory area. Right after that, by default it is removed from the "factory". Now, if you opt for `fenix: true`, the instance continues to exist in this dedicated part, even going to the common area, to be called again in the future.
## Bindings
One of the great differentials of this package, perhaps, is the possibility of full integration of the routes, state manager and dependency manager.
When a route is removed from the Stack, all controllers, variables, and instances of objects related to it are removed from memory. If you are using streams or timers, they will be closed automatically, and you don't have to worry about any of that.
In version 2.10 Get completely implemented the Bindings API.
Now you no longer need to use the init method. You don't even have to type your controllers if you don't want to. You can start your controllers and services in the appropriate place for that.
The Binding class is a class that will decouple dependency injection, while "binding" routes to the state manager and dependency manager.
This allows Get to know which screen is being displayed when a particular controller is used and to know where and how to dispose of it.
In addition, the Binding class will allow you to have SmartManager configuration control. You can configure the dependencies to be arranged when removing a route from the stack, or when the widget that used it is laid out, or neither. You will have intelligent dependency management working for you, but even so, you can configure it as you wish.
### Bindings class
- Create a class and implements Binding
```dart
class HomeBinding implements Bindings {}
```
Your IDE will automatically ask you to override the "dependencies" method, and you just need to click on the lamp, override the method, and insert all the classes you are going to use on that route:
```dart
class HomeBinding implements Bindings {
@override
void dependencies() {
Get.lazyPut<HomeController>(() => HomeController());
Get.put<Service>(()=> Api());
}
}
class DetailsBinding implements Bindings {
@override
void dependencies() {
Get.lazyPut<DetailsController>(() => DetailsController());
}
}
```
Now you just need to inform your route, that you will use that binding to make the connection between route manager, dependencies and states.
- Using named routes:
```dart
getPages: [
GetPage(
name: '/',
page: () => HomeView(),
binding: HomeBinding(),
),
GetPage(
name: '/details',
page: () => DetailsView(),
binding: DetailsBinding(),
),
];
```
- Using normal routes:
```dart
Get.to(Home(), binding: HomeBinding());
Get.to(DetailsView(), binding: DetailsBinding())
```
There, you don't have to worry about memory management of your application anymore, Get will do it for you.
The Binding class is called when a route is called, you can create an "initialBinding in your GetMaterialApp to insert all the dependencies that will be created.
```dart
GetMaterialApp(
initialBinding: SampleBind(),
home: Home(),
);
```
### BindingsBuilder
The default way of creating a binding is by creating a class that implements Bindings.
But alternatively, you can use `BindingsBuilder` callback so that you can simply use a function to instantiate whatever you desire.
Example:
```dart
getPages: [
GetPage(
name: '/',
page: () => HomeView(),
binding: BindingsBuilder(() {
Get.lazyPut<ControllerX>(() => ControllerX());
Get.put<Service>(()=> Api());
}),
),
GetPage(
name: '/details',
page: () => DetailsView(),
binding: BindingsBuilder(() {
Get.lazyPut<DetailsController>(() => DetailsController());
}),
),
];
```
That way you can avoid to create one Binding class for each route making this even simpler.
Both ways of doing work perfectly fine and we want you to use what most suit your tastes.
### SmartManagement
GetX by default disposes unused controllers from memory, even if a failure occurs and a widget that uses it is not properly disposed.
This is what is called the `full` mode of dependency management.
But if you want to change the way GetX controls the disposal of classes, you have `SmartManagement` class that you can set different behaviors.
#### How to change
If you want to change this config (which you usually don't need) this is the way:
```dart
void main () {
runApp(
GetMaterialApp(
smartManagement: SmartManagement.onlyBuilders //here
home: Home(),
)
)
}
```
#### SmartManagement.full
It is the default one. Dispose classes that are not being used and were not set to be permanent. In the majority of the cases you will want to keep this config untouched. If you new to GetX then don't change this.
#### SmartManagement.onlyBuilders
With this option, only controllers started in `init:` or loaded into a Binding with `Get.lazyPut()` will be disposed.
If you use `Get.put()` or `Get.putAsync()` or any other approach, SmartManagement will not have permissions to exclude this dependency.
With the default behavior, even widgets instantiated with "Get.put" will be removed, unlike SmartManagement.onlyBuilders.
#### SmartManagement.keepFactory
Just like SmartManagement.full, it will remove it's dependencies when it's not being used anymore. However, it will keep their factory, which means it will recreate the dependency if you need that instance again.
### How bindings work under the hood
Bindings creates transitory factories, which are created the moment you click to go to another screen, and will be destroyed as soon as the screen-changing animation happens.
This happens so fast that the analyzer will not even be able to register it.
When you navigate to this screen again, a new temporary factory will be called, so this is preferable to using SmartManagement.keepFactory, but if you don't want to create Bindings, or want to keep all your dependencies on the same Binding, it will certainly help you.
Factories take up little memory, they don't hold instances, but a function with the "shape" of that class you want.
This has a very low cost in memory, but since the purpose of this lib is to get the maximum performance possible using the minimum resources, Get removes even the factories by default.
Use whichever is most convenient for you.
## Notes
- DO NOT USE SmartManagement.keepFactory if you are using multiple Bindings. It was designed to be used without Bindings, or with a single Binding linked in the GetMaterialApp's initialBinding.
- Using Bindings is completely optional, if you want you can use `Get.put()` and `Get.find()` on classes that use a given controller without any problem.
However, if you work with Services or any other abstraction, I recommend using Bindings for a better organization.
... ...
- [Route Management](#route-management)
- [How to use](#how-to-use)
- [Navigation without named routes](#navigation-without-named-routes)
- [Navigation with named routes](#navigation-with-named-routes)
- [Send data to named Routes](#send-data-to-named-routes)
- [Dynamic urls links](#dynamic-urls-links)
- [Middleware](#middleware)
- [Navigation without context](#navigation-without-context)
- [SnackBars](#snackbars)
- [Dialogs](#dialogs)
- [BottomSheets](#bottomsheets)
- [Nested Navigation](#nested-navigation)
# Route Management
This is the complete explanation of all there is to Getx when the matter is route management.
## How to use
Add this to your pubspec.yaml file:
```yaml
dependencies:
get:
```
If you are going to use routes/snackbars/dialogs/bottomsheets without context, or use the high-level Get APIs, you need to simply add "Get" before your MaterialApp, turning it into GetMaterialApp and enjoy!
```dart
GetMaterialApp( // Before: MaterialApp(
home: MyHome(),
)
```
## Navigation without named routes
To navigate to a new screen:
```dart
Get.to(NextScreen());
```
To close snackbars, dialogs, bottomsheets, or anything you would normally close with Navigator.pop(context);
```dart
Get.back();
```
To go to the next screen and no option to go back to the previous screen (for use in SplashScreens, login screens and etc.)
```dart
Get.off(NextScreen());
```
To go to the next screen and cancel all previous routes (useful in shopping carts, polls, and tests)
```dart
Get.offAll(NextScreen());
```
To navigate to the next route, and receive or update data as soon as you return from it:
```dart
var data = await Get.to(Payment());
```
on other screen, send a data for previous route:
```dart
Get.back(result: 'success');
```
And use it:
ex:
```dart
if(data == 'success') madeAnything();
```
Don't you want to learn our syntax?
Just change the Navigator (uppercase) to navigator (lowercase), and you will have all the functions of the standard navigation, without having to use context
Example:
```dart
// Default Flutter navigator
Navigator.of(context).push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return HomePage();
},
),
);
// Get using Flutter syntax without needing context
navigator.push(
MaterialPageRoute(
builder: (_) {
return HomePage();
},
),
);
// Get syntax (It is much better, but you have the right to disagree)
Get.to(HomePage());
```
## Navigation with named routes
- If you prefer to navigate by namedRoutes, Get also supports this.
To navigate to nextScreen
```dart
Get.toNamed("/NextScreen");
```
To navigate and remove the previous screen from the tree.
```dart
Get.offNamed("/NextScreen");
```
To navigate and remove all previous screens from the tree.
```dart
Get.offAllNamed("/NextScreen");
```
To define routes, use GetMaterialApp:
```dart
void main() {
runApp(
GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage()),
GetPage(name: '/second', page: () => Second()),
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.zoom
),
],
)
);
}
```
To handle navigation to non-defined routes (404 error), you can define an unknownRoute page in GetMaterialApp.
```dart
void main() {
runApp(
GetMaterialApp(
unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage()),
GetPage(name: '/second', page: () => Second()),
],
)
);
}
```
### Send data to named Routes
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.
```dart
Get.toNamed("/NextScreen", arguments: 'Get is the best');
```
on your class or controller:
```dart
print(Get.arguments);
//print out: Get is the best
```
### Dynamic urls links
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.
```dart
Get.offAllNamed("/NextScreen?device=phone&id=354&name=Enzo");
```
on your controller/bloc/stateful/stateless class:
```dart
print(Get.parameters['id']);
// out: 354
print(Get.parameters['name']);
// out: Enzo
```
You can also receive NamedParameters with Get easily:
```dart
void main() {
runApp(
GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(
name: '/',
page: () => MyHomePage(),
),
GetPage(
name: '/profile/',
page: () => MyProfile(),
),
//You can define a different page for routes with arguments, and another without arguments, but for that you must use the slash '/' on the route that will not receive arguments as above.
GetPage(
name: '/profile/:user',
page: () => UserProfile(),
),
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.cupertino
),
],
)
);
}
```
Send data on route name
```dart
Get.toNamed("/profile/34954");
```
On second screen take the data by parameter
```dart
print(Get.parameters['user']);
// out: 34954
```
or send multiple parameters like this
```dart
Get.toNamed("/profile/34954?flag=true&country=italy");
```
or
```dart
var parameters = <String, String>{"flag": "true","country": "italy",};
Get.toNamed("/profile/34954", parameters: parameters);
```
On second screen take the data by parameters as usually
```dart
print(Get.parameters['user']);
print(Get.parameters['flag']);
print(Get.parameters['country']);
// out: 34954 true italy
```
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
### Middleware
If you want to listen Get events to trigger actions, you can to use routingCallback to it
```dart
GetMaterialApp(
routingCallback: (routing) {
if(routing.current == '/second'){
openAds();
}
}
)
```
If you are not using GetMaterialApp, you can use the manual API to attach Middleware observer.
```dart
void main() {
runApp(
MaterialApp(
onGenerateRoute: Router.generateRoute,
initialRoute: "/",
navigatorKey: Get.key,
navigatorObservers: [
GetObserver(MiddleWare.observer), // HERE !!!
],
),
);
}
```
Create a MiddleWare class
```dart
class MiddleWare {
static observer(Routing routing) {
/// You can listen in addition to the routes, the snackbars, dialogs and bottomsheets on each screen.
///If you need to enter any of these 3 events directly here,
///you must specify that the event is != Than you are trying to do.
if (routing.current == '/second' && !routing.isSnackbar) {
Get.snackbar("Hi", "You are on second route");
} else if (routing.current =='/third'){
print('last route called');
}
}
}
```
Now, use Get on your code:
```dart
class First extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
onPressed: () {
Get.snackbar("hi", "i am a modern snackbar");
},
),
title: Text('First Route'),
),
body: Center(
child: ElevatedButton(
child: Text('Open route'),
onPressed: () {
Get.toNamed("/second");
},
),
),
);
}
}
class Second extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
onPressed: () {
Get.snackbar("hi", "i am a modern snackbar");
},
),
title: Text('second Route'),
),
body: Center(
child: ElevatedButton(
child: Text('Open route'),
onPressed: () {
Get.toNamed("/third");
},
),
),
);
}
}
class Third extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Third Route"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Get.back();
},
child: Text('Go back!'),
),
),
);
}
}
```
## Navigation without context
### SnackBars
To have a simple SnackBar with Flutter, you must get the context of Scaffold, or you must use a GlobalKey attached to your Scaffold
```dart
final snackBar = SnackBar(
content: Text('Hi!'),
action: SnackBarAction(
label: 'I am a old and ugly snackbar :(',
onPressed: (){}
),
);
// Find the Scaffold in the widget tree and use
// it to show a SnackBar.
Scaffold.of(context).showSnackBar(snackBar);
```
With Get:
```dart
Get.snackbar('Hi', 'i am a modern snackbar');
```
With Get, all you have to do is call your Get.snackbar from anywhere in your code or customize it however you want!
```dart
Get.snackbar(
"Hey i'm a Get SnackBar!", // title
"It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!", // message
icon: Icon(Icons.alarm),
shouldIconPulse: true,
onTap:(){},
barBlur: 20,
isDismissible: true,
duration: Duration(seconds: 3),
);
////////// ALL FEATURES //////////
// Color colorText,
// Duration duration,
// SnackPosition snackPosition,
// Widget titleText,
// Widget messageText,
// bool instantInit,
// Widget icon,
// bool shouldIconPulse,
// double maxWidth,
// EdgeInsets margin,
// EdgeInsets padding,
// double borderRadius,
// Color borderColor,
// double borderWidth,
// Color backgroundColor,
// Color leftBarIndicatorColor,
// List<BoxShadow> boxShadows,
// Gradient backgroundGradient,
// TextButton mainButton,
// OnTap onTap,
// bool isDismissible,
// bool showProgressIndicator,
// AnimationController progressIndicatorController,
// Color progressIndicatorBackgroundColor,
// Animation<Color> progressIndicatorValueColor,
// SnackStyle snackStyle,
// Curve forwardAnimationCurve,
// Curve reverseAnimationCurve,
// Duration animationDuration,
// double barBlur,
// double overlayBlur,
// Color overlayColor,
// Form userInputForm
///////////////////////////////////
```
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
`Get.rawSnackbar();` which provides the RAW API on which Get.snackbar was built.
### Dialogs
To open dialog:
```dart
Get.dialog(YourDialogWidget());
```
To open default dialog:
```dart
Get.defaultDialog(
onConfirm: () => print("Ok"),
middleText: "Dialog made in 3 lines of code"
);
```
You can also use Get.generalDialog instead of showGeneralDialog.
For all other Flutter dialog widgets, including cupertinos, you can use Get.overlayContext instead of context, and open it anywhere in your code.
For widgets that don't use Overlay, you can use Get.context.
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.
### BottomSheets
Get.bottomSheet is like showModalBottomSheet, but don't need of context.
```dart
Get.bottomSheet(
Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.music_note),
title: Text('Music'),
onTap: () {}
),
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video'),
onTap: () {},
),
],
),
)
);
```
## Nested Navigation
Get made Flutter's nested navigation even easier.
You don't need the context, and you will find your navigation stack by Id.
- 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.
See how simple it is:
```dart
Navigator(
key: Get.nestedKey(1), // create a key by index
initialRoute: '/',
onGenerateRoute: (settings) {
if (settings.name == '/') {
return GetPageRoute(
page: () => Scaffold(
appBar: AppBar(
title: Text("Main"),
),
body: Center(
child: TextButton(
color: Colors.blue,
onPressed: () {
Get.toNamed('/second', id:1); // navigate by your nested route by index
},
child: Text("Go to second"),
),
),
),
);
} else if (settings.name == '/second') {
return GetPageRoute(
page: () => Center(
child: Scaffold(
appBar: AppBar(
title: Text("Main"),
),
body: Center(
child: Text("second")
),
),
),
);
}
}
),
```
... ...
* [State Management](#state-management)
+ [Reactive State Manager](#reactive-state-manager)
- [Advantages](#advantages)
- [Maximum performance:](#maximum-performance)
- [Declaring a reactive variable](#declaring-a-reactive-variable)
- [Having a reactive state, is easy.](#having-a-reactive-state-is-easy)
- [Using the values in the view](#using-the-values-in-the-view)
- [Conditions to rebuild](#conditions-to-rebuild)
- [Where .obs can be used](#where-obs-can-be-used)
- [Note about Lists](#note-about-lists)
- [Why i have to use .value](#why-i-have-to-use-value)
- [Obx()](#obx)
- [Workers](#workers)
+ [Simple State Manager](#simple-state-manager)
- [Advantages](#advantages-1)
- [Usage](#usage)
- [How it handles controllers](#how-it-handles-controllers)
- [You won't need StatefulWidgets anymore](#you-wont-need-statefulwidgets-anymore)
- [Why it exists](#why-it-exists)
- [Other ways of using it](#other-ways-of-using-it)
- [Unique IDs](#unique-ids)
+ [Mixing the two state managers](#mixing-the-two-state-managers)
+ [GetBuilder vs GetX vs Obx vs MixinBuilder](#getbuilder-vs-getx-vs-obx-vs-mixinbuilder)
# State Management
GetX does not use Streams or ChangeNotifier like other state managers. Why? In addition to building applications for android, iOS, web, linux, macos and linux, with GetX you can build server applications with the same syntax as Flutter/GetX. In order to improve response time and reduce RAM consumption, we created GetValue and GetStream, which are low latency solutions that deliver a lot of performance, at a low operating cost. We use this base to build all of our resources, including state management.
* _Complexity_: Some state managers are complex and have a lot of boilerplate. With GetX you don't have to define a class for each event, the code is highly clean and clear, and you do a lot more by writing less. Many people have given up on Flutter because of this topic, and they now finally have a stupidly simple solution for managing states.
* _No code generators_: You spend half your development time writing your application logic. Some state managers rely on code generators to have minimally readable code. Changing a variable and having to run build_runner can be unproductive, and often the waiting time after a flutter clean will be long, and you will have to drink a lot of coffee.
With GetX everything is reactive, and nothing depends on code generators, increasing your productivity in all aspects of your development.
* _It does not depend on context_: You probably already needed to send the context of your view to a controller, making the View's coupling with your business logic high. You have probably had to use a dependency for a place that has no context, and had to pass the context through various classes and functions. This just doesn't exist with GetX. You have access to your controllers from within your controllers without any context. You don't need to send the context by parameter for literally nothing.
* _Granular control_: most state managers are based on ChangeNotifier. ChangeNotifier will notify all widgets that depend on it when notifyListeners is called. If you have 40 widgets on one screen, which have a variable of your ChangeNotifier class, when you update one, all of them will be rebuilt.
With GetX, even nested widgets are respected. If you have Obx watching your ListView, and another watching a checkbox inside the ListView, when changing the CheckBox value, only it will be updated, when changing the List value, only the ListView will be updated.
* _It only reconstructs if its variable REALLY changes_: GetX has flow control, that means if you display a Text with 'Paola', if you change the observable variable to 'Paola' again, the widget will not be reconstructed. That's because GetX knows that 'Paola' is already being displayed in Text, and will not do unnecessary reconstructions.
Most (if not all) current state managers will rebuild on the screen.
## Reactive State Manager
Reactive programming can alienate many people because it is said to be complicated. GetX turns reactive programming into something quite simple:
* You won't need to create StreamControllers.
* You won't need to create a StreamBuilder for each variable
* You will not need to create a class for each state.
* You will not need to create a get for an initial value.
Reactive programming with Get is as easy as using setState.
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.
This is your count variable:
``` dart
var name = 'Jonatas Borges';
```
To make it observable, you just need to add ".obs" to the end of it:
``` dart
var name = 'Jonatas Borges'.obs;
```
That's all. It's *that* simple.
From now on, we might refer to this reactive-".obs"(ervables) variables as _Rx_.
What did we do under the hood? We created a `Stream` of `String` s, assigned the initial value `"Jonatas Borges"` , we notified all widgets that use `"Jonatas Borges"` that they now "belong" to this variable, and when the _Rx_ value changes, they will have to change as well.
This is the **magic of GetX**, thanks to Dart's capabilities.
But, as we know, a `Widget` can only be changed if it is inside a function, because static classes do not have the power to "auto-change".
You will need to create a `StreamBuilder` , subscribe to this variable to listen for changes, and create a "cascade" of nested `StreamBuilder` if you want to change several variables in the same scope, right?
No, you don't need a `StreamBuilder` , but you are right about static classes.
Well, in the view, we usually have a lot of boilerplate when we want to change a specific Widget, that's the Flutter way.
With **GetX** you can also forget about this boilerplate code.
`StreamBuilder( … )` ? `initialValue: …` ? `builder: …` ? Nope, you just need to place this variable inside an `Obx()` Widget.
``` dart
Obx (() => Text (controller.name));
```
_What do you need to memorize?_ Only `Obx(() =>` .
You are just passing that Widget through an arrow-function into an `Obx()` (the "Observer" of the _Rx_).
`Obx` is pretty smart, and will only change if the value of `controller.name` changes.
If `name` is `"John"` , and you change it to `"John"` ( `name.value = "John"` ), as it's the same `value` as before, nothing will change on the screen, and `Obx` , to save resources, will simply ignore the new value and not rebuild the Widget. **Isn't that amazing?**
> So, what if I have 5 _Rx_ (observable) variables within an `Obx` ?
It will just update when **any** of them changes.
> And if I have 30 variables in a class, when I update one, will it update **all** the variables that are in that class?
Nope, just the **specific Widget** that uses that _Rx_ variable.
So, **GetX** only updates the screen, when the _Rx_ variable changes it's value.
```
final isOpen = false.obs;
// NOTHING will happen... same value.
void onButtonTap() => isOpen.value=false;
```
### Advantages
**GetX()** helps you when you need **granular** control over what's being updated.
If you do not need `unique IDs` , because all your variables will be modified when you perform an action, then use `GetBuilder` ,
because it's a Simple State Updater (in blocks, like `setState()` ), made in just a few lines of code.
It was made simple, to have the least CPU impact, and just to fulfill a single purpose (a _State_ rebuild) and spend the minimum resources possible.
If you need a **powerful** State Manager, you can't go wrong with **GetX**.
It doesn't work with variables, but __flows__, everything in it are `Streams` under the hood.
You can use _rxDart_ in conjunction with it, because everything are `Streams`,
you can listen to the `event` of each "_Rx_ variable",
because everything in it are `Streams`.
It is literally a _BLoC_ approach, easier than _MobX_, and without code generators or decorations.
You can turn **anything** into an _"Observable"_ with just a `.obs` .
### Maximum performance:
In addition to having a smart algorithm for minimal rebuilds, **GetX** uses comparators
to make sure the State has changed.
If you experience any errors in your app, and send a duplicate change of State,
**GetX** will ensure it will not crash.
With **GetX** the State only changes if the `value` change.
That's the main difference between **GetX**, and using _ `computed` from MobX_.
When joining two __observables__, and one changes; the listener of that _observable_ will change as well.
With **GetX**, if you join two variables, `GetX()` (similar to `Observer()` ) will only rebuild if it implies a real change of State.
### Declaring a reactive variable
You have 3 ways to turn a variable into an "observable".
1 - The first is using **`Rx{Type}`**.
``` dart
// initial value is recommended, but not mandatory
final name = RxString('');
final isLogged = RxBool(false);
final count = RxInt(0);
final balance = RxDouble(0.0);
final items = RxList<String>([]);
final myMap = RxMap<String, int>({});
```
2 - The second is to use **`Rx`** and use Darts Generics, `Rx<Type>`
``` dart
final name = Rx<String>('');
final isLogged = Rx<Bool>(false);
final count = Rx<Int>(0);
final balance = Rx<Double>(0.0);
final number = Rx<Num>(0);
final items = Rx<List<String>>([]);
final myMap = Rx<Map<String, int>>({});
// Custom classes - it can be any class, literally
final user = Rx<User>();
```
3 - The third, more practical, easier and preferred approach, just add **`.obs`** as a property of your `value` :
``` dart
final name = ''.obs;
final isLogged = false.obs;
final count = 0.obs;
final balance = 0.0.obs;
final number = 0.obs;
final items = <String>[].obs;
final myMap = <String, int>{}.obs;
// Custom classes - it can be any class, literally
final user = User().obs;
```
##### Having a reactive state, is easy.
As we know, _Dart_ is now heading towards _null safety_.
To be prepared, from now on, you should always start your _Rx_ variables with an **initial value**.
> Transforming a variable into an _observable_ + _initial value_ with **GetX** is the simplest, and most practical approach.
You will literally add a " `.obs` " to the end of your variable, and **that’s it**, you’ve made it observable,
and its `.value` , well, will be the _initial value_).
### Using the values in the view
``` dart
// controller file
final count1 = 0.obs;
final count2 = 0.obs;
int get sum => count1.value + count2.value;
```
``` dart
// view file
GetX<Controller>(
builder: (controller) {
print("count 1 rebuild");
return Text('${controller.count1.value}');
},
),
GetX<Controller>(
builder: (controller) {
print("count 2 rebuild");
return Text('${controller.count2.value}');
},
),
GetX<Controller>(
builder: (controller) {
print("count 3 rebuild");
return Text('${controller.sum}');
},
),
```
If we increment `count1.value++` , it will print:
* `count 1 rebuild`
* `count 3 rebuild`
because `count1` has a value of `1` , and `1 + 0 = 1` , changing the `sum` getter value.
If we change `count2.value++` , it will print:
* `count 2 rebuild`
* `count 3 rebuild`
because `count2.value` changed, and the result of the `sum` is now `2` .
* NOTE: By default, the very first event will rebuild the widget, even if it is the same `value`.
This behavior exists due to Boolean variables.
Imagine you did this:
``` dart
var isLogged = false.obs;
```
And then, you checked if a user is "logged in" to trigger an event in `ever` .
``` dart
@override
onInit() async {
ever(isLogged, fireRoute);
isLogged.value = await Preferences.hasToken();
}
fireRoute(logged) {
if (logged) {
Get.off(Home());
} else {
Get.off(Login());
}
}
```
if `hasToken` was `false` , there would be no change to `isLogged` , so `ever()` would never be called.
To avoid this type of behavior, the first change to an _observable_ will always trigger an event,
even if it contains the same `.value` .
You can remove this behavior if you want, using:
`isLogged.firstRebuild = false;`
### Conditions to rebuild
In addition, Get provides refined state control. You can condition an event (such as adding an object to a list), on a certain condition.
``` dart
// First parameter: condition, must return true or false.
// Second parameter: the new value to apply if the condition is true.
list.addIf(item < limit, item);
```
Without decorations, without a code generator, without complications :smile:
Do you know Flutter's counter app? Your Controller class might look like this:
``` dart
class CountController extends GetxController {
final count = 0.obs;
}
```
With a simple:
``` dart
controller.count.value++
```
You could update the counter variable in your UI, regardless of where it is stored.
### Where .obs can be used
You can transform anything on obs. Here are two ways of doing it:
* You can convert your class values to obs
``` dart
class RxUser {
final name = "Camila".obs;
final age = 18.obs;
}
```
* or you can convert the entire class to be an observable
``` dart
class User {
User({String name, int age});
var name;
var age;
}
// when instantianting:
final user = User(name: "Camila", age: 18).obs;
```
### Note about Lists
Lists are completely observable as are the objects within it. That way, if you add a value to a list, it will automatically rebuild the widgets that use it.
You also don't need to use ".value" with lists, the amazing dart api allowed us to remove that.
Unfortunaly primitive types like String and int cannot be extended, making the use of .value mandatory, but that won't be a problem if you work with gets and setters for these.
``` dart
// On the controller
final String title = 'User Info:'.obs
final list = List<User>().obs;
// on the view
Text(controller.title.value), // String need to have .value in front of it
ListView.builder (
itemCount: controller.list.length // lists don't need it
)
```
When you are making your own classes observable, there is a different way to update them:
``` dart
// on the model file
// we are going to make the entire class observable instead of each attribute
class User() {
User({this.name = '', this.age = 0});
String name;
int age;
}
// on the controller file
final user = User().obs;
// when you need to update the user variable:
user.update( (user) { // this parameter is the class itself that you want to update
user.name = 'Jonny';
user.age = 18;
});
// an alternative way of update the user variable:
user(User(name: 'João', age: 35));
// on view:
Obx(()=> Text("Name ${user.value.name}: Age: ${user.value.age}"))
// you can also access the model values without the .value:
user().name; // notice that is the user variable, not the class (variable has lowercase u)
```
You don't have to work with sets if you don't want to. you can use the "assign 'and" assignAll "api.
The "assign" api will clear your list, and add a single object that you want to start there.
The "assignAll" api will clear the existing list and add any iterable objects that you inject into it.
### Why i have to use .value
We could remove the obligation to use 'value' to `String` and `int` with a simple decoration and code generator, but the purpose of this library is precisely avoid external dependencies. We want to offer an environment ready for programming, involving the essentials (management of routes, dependencies and states), in a simple, lightweight and performant way, without a need of an external package.
You can literally add 3 letters to your pubspec (get) and a colon 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.
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.
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.
### Obx()
Typing in Get using Bindings is unnecessary. you can use the Obx widget instead of GetX which only receives the anonymous function that creates a widget.
Obviously, if you don't use a type, you will need to have an instance of your controller to use the variables, or use `Get.find<Controller>()` .value or Controller.to.value to retrieve the value.
### Workers
Workers will assist you, triggering specific callbacks when an event occurs.
``` dart
/// Called every time `count1` changes.
ever(count1, (_) => print("$_ has been changed"));
/// Called only first time the variable $_ is changed
once(count1, (_) => print("$_ was changed once"));
/// Anti DDos - Called every time the user stops typing for 1 second, for example.
debounce(count1, (_) => print("debouce$_"), time: Duration(seconds: 1));
/// Ignore all changes within 1 second.
interval(count1, (_) => print("interval $_"), time: Duration(seconds: 1));
```
All workers (except `debounce` ) have a `condition` named parameter, which can be a `bool` or a callback that returns a `bool` .
This `condition` defines when the `callback` function executes.
All workers returns a `Worker` instance, that you can use to cancel ( via `dispose()` ) the worker.
* **`ever`**
is called every time the _Rx_ variable emits a new value.
* **`everAll`**
Much like `ever` , but it takes a `List` of _Rx_ values Called every time its variable is changed. That's it.
* **`once`**
'once' is called only the first time the variable has been changed.
* **`debounce`**
'debounce' is very useful in search functions, where you only want the API to be called when the user finishes typing. If the user types "Jonny", you will have 5 searches in the APIs, by the letter J, o, n, n, and y. With Get this does not happen, because you will have a "debounce" Worker that will only be triggered at the end of typing.
* **`interval`**
'interval' is different from the debouce. debouce if the user makes 1000 changes to a variable within 1 second, he will send only the last one after the stipulated timer (the default is 800 milliseconds). Interval will instead ignore all user actions for the stipulated period. If you send events for 1 minute, 1000 per second, debounce will only send you the last one, when the user stops strafing events. interval will deliver events every second, and if set to 3 seconds, it will deliver 20 events that minute. This is recommended to avoid abuse, in functions where the user can quickly click on something and get some advantage (imagine that the user can earn coins by clicking on something, if he clicked 300 times in the same minute, he would have 300 coins, using interval, you you can set a time frame for 3 seconds, and even then clicking 300 or a thousand times, the maximum he would get in 1 minute would be 20 coins, clicking 300 or 1 million times). The debounce is suitable for anti-DDos, for functions like search where each change to onChange would cause a query to your api. Debounce will wait for the user to stop typing the name, to make the request. If it were used in the coin scenario mentioned above, the user would only win 1 coin, because it is only executed, when the user "pauses" for the established time.
* NOTE: Workers should always be used when starting a Controller or Class, so it should always be on onInit (recommended), Class constructor, or the initState of a StatefulWidget (this practice is not recommended in most cases, but it shouldn't have any side effects).
## Simple State Manager
Get has a state manager that is extremely light and easy, which does not use ChangeNotifier, will meet the need especially for those new to Flutter, and will not cause problems for large applications.
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.
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.
### Advantages
1. Update only the required widgets.
2. Does not use changeNotifier, it is the state manager that uses less memory (close to 0mb).
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.
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.
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.
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.
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).
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.
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.
### Usage
``` dart
// Create controller class and extends GetxController
class Controller extends GetxController {
int counter = 0;
void increment() {
counter++;
update(); // use update() to update counter variable on UI when increment be called
}
}
// On your Stateless/Stateful class, use GetBuilder to update Text when increment be called
GetBuilder<Controller>(
init: Controller(), // INIT IT ONLY THE FIRST TIME
builder: (_) => Text(
'${_.counter}',
),
)
//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.
```
**Done!**
* You have already learned how to manage states with Get.
* 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.
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):
``` dart
class OtherClass extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GetBuilder<Controller>(
builder: (s) => Text('${s.counter}'),
),
),
);
}
```
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>()` )
``` dart
class Controller extends GetxController {
/// You do not need that. I recommend using it just for ease of syntax.
/// with static method: Controller.to.increment();
/// with no static method: Get.find<Controller>().increment();
/// 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.
static Controller get to => Get.find(); // add this line
int counter = 0;
void increment() {
counter++;
update();
}
}
```
And then you can access your controller directly, that way:
``` dart
FloatingActionButton(
onPressed: () {
Controller.to.increment(),
} // This is incredibly simple!
child: Text("${Controller.to.counter}"),
),
```
When you press FloatingActionButton, all widgets that are listening to the 'counter' variable will be updated automatically.
### How it handles controllers
Let's say we have this:
`Class a => Class B (has controller X) => Class C (has controller X)`
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.
### You won't need StatefulWidgets anymore
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/GetX/Obx, which will be another StatefulWidget.
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!
Unless you need to use a mixin, like TickerProviderStateMixin, it will be totally unnecessary to use a StatefulWidget with Get.
You can call all methods of a StatefulWidget directly from a GetBuilder.
If you need to call initState() or dispose() method for example, you can call them directly;
``` dart
GetBuilder<Controller>(
initState: (_) => Controller.to.fetchApi(),
dispose: (_) => Controller.to.closeStreams(),
builder: (s) => Text('${s.username}'),
),
```
A much better approach than this is to use the onInit() and onClose() method directly from your controller.
``` dart
@override
void onInit() {
fetchApi();
super.onInit();
}
```
* 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.
### Why it exists
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.
So to simplify this:
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.
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.
Do not call a dispose method inside GetxController, 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:
``` dart
class Controller extends GetxController {
StreamController<User> user = StreamController<User>();
StreamController<String> name = StreamController<String>();
/// close stream = onClose method, not dispose.
@override
void onClose() {
user.close();
name.close();
super.onClose();
}
}
```
Controller life cycle:
* onInit() where it is created.
* onClose() where it is closed to make any changes in preparation for the delete method
* 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.
### Other ways of using it
You can use Controller instance directly on GetBuilder value:
``` dart
GetBuilder<Controller>(
init: Controller(),
builder: (value) => Text(
'${value.counter}', //here
),
),
```
You may also need an instance of your controller outside of your GetBuilder, and you can use these approaches to achieve this:
``` dart
class Controller extends GetxController {
static Controller get to => Get.find();
[...]
}
// on you view:
GetBuilder<Controller>(
init: Controller(), // use it only first time on each controller
builder: (_) => Text(
'${Controller.to.counter}', //here
)
),
```
or
``` dart
class Controller extends GetxController {
// static Controller get to => Get.find(); // with no static get
[...]
}
// on stateful/stateless class
GetBuilder<Controller>(
init: Controller(), // use it only first time on each controller
builder: (_) => Text(
'${Get.find<Controller>().counter}', //here
),
),
```
* 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:
``` dart
Controller controller = Controller();
[...]
GetBuilder<Controller>(
init: controller, //here
builder: (_) => Text(
'${controller.counter}', // here
),
),
```
### Unique IDs
If you want to refine a widget's update control with GetBuilder, you can assign them unique IDs:
``` dart
GetBuilder<Controller>(
id: 'text'
init: Controller(), // use it only first time on each controller
builder: (_) => Text(
'${Get.find<Controller>().counter}', //here
),
),
```
And update it this form:
``` dart
update(['text']);
```
You can also impose conditions for the update:
``` dart
update(['text'], counter < 10);
```
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).
## Mixing the two state managers
Some people opened a feature request, as they wanted to use only one type of reactive variable, and the other mechanics, and needed to insert an Obx into a GetBuilder for this. Thinking about it MixinBuilder was created. It allows both reactive changes by changing ".obs" variables, and mechanical updates via update(). However, of the 4 widgets he is the one that consumes the most resources, since in addition to having a Subscription to receive change events from his children, he subscribes to the update method of his controller.
Extending GetxController is important, as they have life cycles, and can "start" and "end" events in their onInit() and onClose() methods. You can use any class for this, but I strongly recommend you use the GetxController class to place your variables, whether they are observable or not.
## StateMixin
Another way to handle your `UI` state is use the `StateMixin<T>` .
To implement it, use the `with` to add the `StateMixin<T>`
to your controller which allows a T model.
``` dart
class Controller extends GetController with StateMixin<User>{}
```
The `change()` method change the State whenever we want.
Just pass the data and the status in this way:
```dart
change(data, status: RxStatus.success());
```
RxStatus allow these status:
``` dart
RxStatus.loading();
RxStatus.success();
RxStatus.empty();
RxStatus.error('message');
```
To represent it in the UI, use:
```dart
class OtherClass extends GetView<Controller> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: controller.obx(
(state)=>Text(state.name),
// here you can put your custom loading indicator, but
// by default would be Center(child:CircularProgressIndicator())
onLoading: CustomLoadingIndicator(),
onEmpty: Text('No data found'),
// here also you can set your own error widget, but by
// default will be an Center(child:Text(error))
onError: (error)=>Text(error),
),
);
}
```
## GetBuilder vs GetX vs Obx vs MixinBuilder
In a decade working with programming I was able to learn some valuable lessons.
My first contact with reactive programming was so "wow, this is incredible" and in fact reactive programming is incredible.
However, it is not suitable for all situations. Often all you need is to change the state of 2 or 3 widgets at the same time, or an ephemeral change of state, in which case reactive programming is not bad, but it is not appropriate.
Reactive programming has a higher RAM consumption that can be compensated for by the individual workflow, which will ensure that only one widget is rebuilt and when necessary, but creating a list with 80 objects, each with several streams is not a good one idea. Open the dart inspect and check how much a StreamBuilder consumes, and you'll understand what I'm trying to tell you.
With that in mind, I created the simple state manager. It is simple, and that is exactly what you should demand from it: updating state in blocks in a simple way, and in the most economical way.
GetBuilder is very economical in RAM, and there is hardly a more economical approach than him (at least I can't imagine one, if it exists, please let us know).
However, GetBuilder is still a mechanical state manager, you need to call update() just like you would need to call Provider's notifyListeners().
There are other situations where reactive programming is really interesting, and not working with it is the same as reinventing the wheel. With that in mind, GetX was created to provide everything that is most modern and advanced in a state manager. It updates only what is necessary and when necessary, if you have an error and send 300 state changes simultaneously, GetX will filter and update the screen only if the state actually changes.
GetX is still more economical than any other reactive state manager, but it consumes a little more RAM than GetBuilder. Thinking about it and aiming to maximize the consumption of resources that Obx was created. Unlike GetX and GetBuilder, you will not be able to initialize a controller inside an Obx, it is just a Widget with a StreamSubscription that receives change events from your children, that's all. It is more economical than GetX, but loses to GetBuilder, which was to be expected, since it is reactive, and GetBuilder has the most simplistic approach that exists, of storing a widget's hashcode and its StateSetter. With Obx you don't need to write your controller type, and you can hear the change from multiple different controllers, but it needs to be initialized before, either using the example approach at the beginning of this readme, or using the Bindings class.
... ...
... ... @@ -14,7 +14,7 @@
- [SmartManagement](#smartmanagement)
- [How to change](#how-to-change)
- [SmartManagement.full](#smartmanagementfull)
- [SmartManagement.onlyBuilders](#smartmanagementonlybuilders)
- [SmartManagement.onlyBuilder](#smartmanagementonlybuilder)
- [SmartManagement.keepFactory](#smartmanagementkeepfactory)
- [How bindings work under the hood](#how-bindings-work-under-the-hood)
- [Notes](#notes)
... ... @@ -372,7 +372,7 @@ If you want to change this config (which you usually don't need) this is the way
void main () {
runApp(
GetMaterialApp(
smartManagement: SmartManagement.onlyBuilders //here
smartManagement: SmartManagement.onlyBuilder //here
home: Home(),
)
)
... ... @@ -383,12 +383,12 @@ void main () {
It is the default one. Dispose classes that are not being used and were not set to be permanent. In the majority of the cases you will want to keep this config untouched. If you new to GetX then don't change this.
#### SmartManagement.onlyBuilders
#### SmartManagement.onlyBuilder
With this option, only controllers started in `init:` or loaded into a Binding with `Get.lazyPut()` will be disposed.
If you use `Get.put()` or `Get.putAsync()` or any other approach, SmartManagement will not have permissions to exclude this dependency.
With the default behavior, even widgets instantiated with "Get.put" will be removed, unlike SmartManagement.onlyBuilders.
With the default behavior, even widgets instantiated with "Get.put" will be removed, unlike SmartManagement.onlyBuilder.
#### SmartManagement.keepFactory
... ...
... ... @@ -40,8 +40,7 @@ Pour accéder à un nouvel écran:
Get.to(NextScreen());
```
To close snackbars, dialogs, bottomsheets, or anything you would normally close with Navigator.pop(context);
Pour fermer les snackbars, dialogs, bottomsheets ou tout ce que vous fermez normalement avec Navigator.pop (context);
Pour fermer les snackbars, dialogs, bottomsheets ou tout ce que vous fermez normalement avec Navigator.pop(context);
```dart
Get.back();
... ...
# 依存オブジェクト管理
- [依存オブジェクト管理](#依存オブジェクト管理)
- [インスタンス化に使用するメソッド](#インスタンス化に使用するメソッド)
- [Get.put()](#getput)
- [Get.lazyPut()](#getlazyput)
- [Get.putAsync()](#getputasync)
- [Get.create()](#getcreate)
- [インスタンス化したクラスを使う](#インスタンス化したクラスを使う)
- [依存オブジェクトの置換](#依存オブジェクトの置換)
- [各メソッドの違い](#各メソッドの違い)
- [Bindings(Routeと依存オブジェクトの結束)](#Bindings(Routeと依存オブジェクトの結束))
- [Bindingsクラス](#bindingsクラス)
- [BindingsBuilder](#bindingsbuilder)
- [SmartManagement](#smartmanagement)
- [設定の変更方法](#設定の変更方法)
- [SmartManagement.full](#smartmanagementfull)
- [SmartManagement.onlyBuilder](#smartmanagementonlybuilder)
- [SmartManagement.keepFactory](#smartmanagementkeepfactory)
- [Bindingsの仕組み](#Bindingsの仕組み)
- [補足](#補足)
Getにはシンプルで強力な依存オブジェクト管理機能があります。たった1行のコードで、Provider contextやinheritedWidgetを使うことなく、BlocもしくはControllerのインスタンスを取得することができます。
```dart
Controller controller = Get.put(Controller()); // Controller controller = Controller() の代わりに
```
UIクラスの中でControllerクラスをインスタンス化する代わりに、Getインスタンスの中でインスタンス化することで、アプリ全体でControllerを利用できるようになります。
- 注: Getの状態管理機能を使用する場合は、[Bindings](#bindings)の使用も検討してください。Bindingsを使うことでビューにControllerを結合させることができます。
- 注²: Getの依存オブジェクト管理機能は、パッケージの他の部分から独立しています。そのため、たとえばあなたのアプリが既に他の状態管理ライブラリを使用している場合(どんなものでも)、何の問題もなく2つを組み合わせることができます。
## インスタンス化に使用するメソッド
Controllerを初期化するのに使用するメソッドとその設定パラメーターについてご説明します。
### Get.put()
依存オブジェクトを注入するための最も基本のメソッド。たとえば、ビューで使用するControllerに使います。
```dart
Get.put<SomeClass>(SomeClass());
Get.put<LoginController>(LoginController(), permanent: true);
Get.put<ListItemController>(ListItemController, tag: "some unique string");
```
以下が put() を使用する際に設定できるパラメーターです。
```dart
Get.put<S>(
// 必須。インスタンスを保存しておきたいControllerなどを設定
// 注: "S" 型はジェネリクスで、どんな型でもOK
S dependency
// オプション。これは同じ型のControllerインスタンスが複数存在する場合に、
// タグIDにより識別したい場合に使用します。
// Get.find<Controller>(tag: ) でこのputで設定したインスタンスを探します。
// tag はユニークなStringである必要があります。
String tag,
// オプション。デフォルトでは使用されなくなったインスタンスは破棄されますが、
// (たとえばビューが閉じられた場合など) SharedPreferencesのインスタンスなど、
// アプリ全体を通して生かしておきたい場合があるかと思います。
// その場合はこれをtrueにしてください。デフォルトはfalseです。
bool permanent = false,
// オプション。テストで抽象クラスを使用した後、別クラスに置換してテストを追うことができます。
// デフォルトはfalseです。
bool overrideAbstract = false,
// オプション: 依存オブジェクトを関数を使って作ることができます。
// 使用頻度は低いと思います。
InstanceBuilderCallback<S> builder,
)
```
### Get.lazyPut()
依存オブジェクトをすぐにロードする代わりに、lazy(遅延、消極的)ロードすることができます。実際に使用されるときに初めてインスタンス化されます。計算量の多いクラスや、Bindingsを使って複数のControllerをまとめてインスタンス化したいが、その時点ではすぐにそれらを使用しないことがわかっている場合などに非常に便利です。
```dart
/// この場合のApiMockは Get.find<ApiMock> を使用した時点でインスタンス化されます。
Get.lazyPut<ApiMock>(() => ApiMock());
Get.lazyPut<FirebaseAuth>(
() {
// 必要ならここに何かのロジック
return FirebaseAuth();
},
tag: Math.random().toString(),
fenix: true
)
Get.lazyPut<Controller>( () => Controller() )
```
これが .lazyPut で設定できるパラメーターです。
```dart
Get.lazyPut<S>(
// 必須。クラスSが初めてfindの対象になったときに実行されるメソッド
InstanceBuilderCallback builder,
// オプション。Get.put()のtagと同様に同じクラスの異なるインスタンスが必要なときに使用
// ユニークな値を指定
String tag,
// オプション。"permanent" に似ていますが、使用されていないときはインスタンスが
// 破棄され、再び使用するときにGetがインスタンスを再び作成する点が異なります。
// Bindings APIの "SmartManagement.keepFactory " と同じです。
// デフォルトはfalse
bool fenix = false
)
```
### Get.putAsync()
SharedPreferencesなど、非同期のインスタンスを登録したいときに使います。
```dart
Get.putAsync<SharedPreferences>(() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('counter', 12345);
return prefs;
});
Get.putAsync<YourAsyncClass>( () async => await YourAsyncClass() )
```
これが .putAsync で設定できるパラメーターです。
```dart
Get.putAsync<S>(
// 必須。クラスをインスタンス化するための非同期メソッドを指定
AsyncInstanceBuilderCallback<S> builder,
// オプション。Get.put() と同じです。同じクラスの異なるインスタンスを作りたいときに使用
// ユニークな値を指定
String tag,
// オプション。Get.put() と同じです。アプリ全体を通して生かしておきたい場合に使用
// デフォルトはfalse
bool permanent = false
)
```
### Get.create()
これは使いどころに迷うかもしれません。他のものとの違いなど詳細な説明は「[各メソッドの違い](#各メソッドの違い)」のセクションをご一読ください。
```dart
Get.Create<SomeClass>(() => SomeClass());
Get.Create<LoginController>(() => LoginController());
```
これが .create で設定できるパラメーターです。
```dart
Get.create<S>(
// 必須。Get.find() が呼ばれるたびにインスタンスがこの関数で新たに組み立てられる。
// 例: Get.create<YourClass>(() => YourClass())
FcBuilderFunc<S> builder,
// オプション。Get.put() のtagと同様で、同じクラスによる
// 複数インスタンスを扱うときに使用します。
// リストのアイテムにそれぞれコントローラが必要な場合に便利です。
// 文字列はユニークである必要があります。
String name,
// オプション。Get.put() と同様アプリ全体でインスタンスを維持するときに使用。
// 唯一の違いは Get.create() のpermanentはデフォルトでtrueということだけです。
bool permanent = true
```
## インスタンス化したクラスを使う
いくつかのRouteを渡り歩いた後、以前のControllerに残してきたデータが必要になったとしたら、Provider や Get_it と組み合わせる必要がありますよね?Getの場合は違います。GetにControllerの「検索」を依頼するだけで追加の依存オブジェクトの注入は必要ありません。
```dart
final controller = Get.find<Controller>();
// もしくは
Controller controller = Get.find();
// マジックみたいですよね。でも実際にGetはControllerのインスタンスを探して届けてくれます。
// 100万ものControllerをインスタンス化していても、Getは常に正しいControllerを探してくれます。
```
そしてそのControllerが以前取得したデータをあなたは復元することができます。
```dart
Text(controller.textFromApi);
```
戻り値は通常のクラスなので、そのクラスで可能なことは何でもできます。
```dart
int count = Get.find<SharedPreferences>().getInt('counter');
print(count); // 出力: 12345
```
インスタンスを明示的に削除したい場合はこのようにしてください。
```dart
Get.delete<Controller>(); // 通常であれば、GetXは未使用Controllerを自動削除するので、この作業は必要ありません。
```
## 依存オブジェクトの置換
注入されている依存オブジェクトは `replace` または `lazyReplace` メソッドを使って、子クラスなど関連クラスのインスタンスに置き換えることができます。これは元の抽象クラスを型指定することで取得することができます。
```dart
abstract class BaseClass {}
class ParentClass extends BaseClass {}
class ChildClass extends ParentClass {
bool isChild = true;
}
Get.put<BaseClass>(ParentClass());
Get.replace<BaseClass>(ChildClass());
final instance = Get.find<BaseClass>();
print(instance is ChildClass); //true
class OtherClass extends BaseClass {}
Get.lazyReplace<BaseClass>(() => OtherClass());
final instance = Get.find<BaseClass>();
print(instance is ChildClass); // false
print(instance is OtherClass); //true
```
## Differences between methods
まずは Get.lazyPut の `fenix` プロパティと、他メソッドの `permanent` プロパティの違いについてご説明します。
`permanent` と `fenix` の根本的な違いは、インスタンスをどのように保持したいかという点に尽きます。
しつこいようですが、GetXでは使われていないインスタンスは削除されるのがデフォルトの動作です。
これはもし画面AがController A、画面BがController Bを持っている場合において、画面Bに遷移するときに画面Aをスタックから削除した場合(`Get.off()` や `Get.offNamed()` を使うなどして)、Controller Aは消えてなくなるということです。
しかし Get.put() する際に `permanent:true` としていれば、Controller Aはこの画面削除により失われることはありません。これはアプリケーション全体を通してControllerを残しておきたい場合に大変便利です。
一方の `fenix` は、画面削除に伴っていったんはControllerが消去されますが、再び使いたいと思ったときに復活させることができます。つまり基本的には未使用の Controller / サービス / その他クラス は消去されますが、必要なときは新しいインスタンスを「燃えカス」から作り直すことができるのです。
各メソッドを使用する際のプロセスの違いをご説明します。
- Get.put と Get.putAsync はインスタンスを作成して初期化するプロセスは同じですが、後者は非同期メソッドを使用するという違いがあります。この2つのメソッドは内部に保有するメソッド `insert` に `permanent: false` と `isSingleton: true` という引数を渡して、メモリに直接インスタンスを挿入します (この isSingleton が行っていることは、依存オブジェクトを `dependency` と `builder` プロパティのどちらから拝借するかを判断することだけです)。その後に `Get.find()` が呼ばれると、メモリ上にあるインスタンスを即座に初期化するというプロセスをたどります。
- Get.create はその名の通り、依存オブジェクトを「クリエイト」します。Get.put() と同様に内部メソッドである `insert` を呼び出してインスタンス化します。違いは `permanent: true` で `isSingleton: false` である点です (依存オブジェクトを「クリエイト」しているため、シングルトンにはなりません。それが false になっている理由です)。また `permanent: true` となっているので、デフォルトでは画面の破棄などでインスタンスを失わないというメリットがあります。また `Get.find()` はすぐに呼ばれず、画面内で実際に使用されてから呼ばれます。これは `permanent` の特性を活かすための設計ですが、それゆえ `Get.create()` は共有しないけど破棄もされないインスタンスを作成する目的で作られたと言えます。たとえば、ListViewの中のボタンアイテムに使うControllerインスタンスのように、そのリスト内でしか使わないけどリストアイテムごとに固有のインスタンスが必要なケースなどが考えられます。そのため、Get.create は GetWidget との併用がマストです。
- Get.lazyPut は初期化をlazy(遅延、消極的)に行います。実行されるとインスタンスは作成されますが、すぐに使用できるように初期化はされず、待機状態になります。また他のメソッドと異なり `insert` メソッドは呼び出されません。その代わり、インスタンスはメモリの別の部分に挿入されます。この部分を「ファクトリー」と呼ぶことにしましょう。「ファクトリー」は、そのインスタンスが再生成できるかどうかを決める役割を持っています。これは後で使う予定のものを、現在進行形で使われているものと混ざらないようにするための工夫です。ここで `fenix` によるマジックが登場します。デフォルトの `fenix: false` のままにしており、かつ `SmartManagement` が `keepFactory` ではない場合において `Get.find` を使用すると、インスタンスは「ファクトリー」から共有メモリ領域に移動します。その直後にインスタンスは「ファクトリー」から削除されます。しかし `fenix: true` としていた場合、インスタンスは「ファクトリー」に残るため、共有メモリ領域から削除されても再び呼び出すことができるのです。
## Bindings(Routeと依存オブジェクトの結束)
このパッケージの一番の差別化要素は、Route管理 / 状態管理 / 依存オブジェクト管理 を統合したことにあると思っています。
スタックからRouteが削除されれば、関係するController、変数、オブジェクトのインスタンスがすべてメモリから削除されます。たとえばStreamやTimerを使用している場合も同様ですので、開発者は何も心配する必要はありません。
Getはバージョン2.10からBindings APIをフル実装しました。
Bindingsを使用すれば init でControllerを起動する必要はありません。またControllerの型を指定する必要もありません。Controllerやサービスは各々適切な場所で起動することができるようになりました。
Bindingsは依存オブジェクトの注入をビューから切り離すことができるクラスです。それに加え、状態と依存オブジェクトの管理機能をRouteに「結束(bind)」してくれます。
これによりGetは、あるControllerが使用されたときにどの画面UIが表示されているかを知ることができます。つまり、そのControllerをどのタイミングでどう処分するかを判断することができるということです。
さらにBindingsでは SmartManager の制御により、依存オブジェクトをどのタイミング(スタックからRouteを削除したときか、それに依存するWidgetを表示したときか、いずれでもないか)で整理するかを設定することができます。インテリジェントな依存オブジェクトの自動管理機能を持ちつつ、自分の好きなように設定できるのです。
### Bindingsクラス
- Bindings機能を実装したクラスを作成することができます。
```dart
class HomeBinding implements Bindings {}
```
"dependencies" メソッドをオーバーライドするようIDEに自動で指摘されます。表示をクリックしてメソッドを override し、そのRoute内で使用するすべてのクラスを挿入してください。
```dart
class HomeBinding implements Bindings {
@override
void dependencies() {
Get.lazyPut<HomeController>(() => HomeController());
Get.put<Service>(()=> Api());
}
}
class DetailsBinding implements Bindings {
@override
void dependencies() {
Get.lazyPut<DetailsController>(() => DetailsController());
}
}
```
Bindingsを設定したら、このクラスが Route管理 / 依存オブジェクト管理 / 状態管理 を互いに接続する目的で使用されるものだということをRouteに知らせてあげます。
- 名前付きRouteを使う場合
```dart
getPages: [
GetPage(
name: '/',
page: () => HomeView(),
binding: HomeBinding(),
),
GetPage(
name: '/details',
page: () => DetailsView(),
binding: DetailsBinding(),
),
];
```
- 通常のRouteを使う場合
```dart
Get.to(Home(), binding: HomeBinding());
Get.to(DetailsView(), binding: DetailsBinding())
```
これでアプリケーションのメモリ管理を気にする必要がなくなります。Getがすべてやってくれます。
BindingsクラスはRouteの呼び出しと同時に呼び出されます。また、すべてに共通の依存オブジェクトを挿入するためには GetMaterialApp の initialBinding プロパティを使用してください。
```dart
GetMaterialApp(
initialBinding: SampleBind(),
home: Home(),
);
```
### BindingsBuilder
Bindingsを作成する一般的な方法は Bindings を実装したクラスを作成することですが、`BindingsBuilder` コールバックを使う方法もあります。
Example:
```dart
getPages: [
GetPage(
name: '/',
page: () => HomeView(),
binding: BindingsBuilder(() {
Get.lazyPut<ControllerX>(() => ControllerX());
Get.put<Service>(()=> Api());
}),
),
GetPage(
name: '/details',
page: () => DetailsView(),
binding: BindingsBuilder(() {
Get.lazyPut<DetailsController>(() => DetailsController());
}),
),
];
```
この方法ならRouteごとにBindingsクラスを作る必要はありません。
どちらの方法でも効果は変わりませんのでお好みの方法を使ってください。
### SmartManagement
エラーが発生してControllerを使用するWidgetが正しく破棄されなかった場合でも、Controllerが未使用になればGetXはデフォルトの動作通りそれをメモリから削除します。
これがいわゆる依存オブジェクト管理機能の `full` モードと呼ばれるものです。
しかしもしGetXによるオブジェクト破棄の方法をコントロールしたい場合は、`SmartManagement`クラスを使って設定してください。
#### 設定の変更方法
この設定は通常変更する必要はありませんが、変更されたい場合はこのようにしてください。
```dart
void main () {
runApp(
GetMaterialApp(
smartManagement: SmartManagement.onlyBuilder // ここで設定
home: Home(),
)
)
}
```
#### SmartManagement.full
これがデフォルトのモードです。使用されていない、かつ `permanent: true` が設定されていないオブジェクトを自動で破棄してくれます。特殊な事情がない限り、この設定は触らない方がいいでしょう。GetXを使って間がない場合は特に。
#### SmartManagement.onlyBuilder
`init:` もしくはBindings内で `Get.lazyPut()` により設定したビルダー製のオブジェクトだけを破棄するモードです。
もしそれが `Get.put()` や `Get.putAsync()` などのアプローチで生成したオブジェクトだとしたら、SmartManagement は勝手にメモリから除外することはできません。
それに対してデフォルトのモードでは `Get.put()` で生成したオブジェクトも破棄します。
#### SmartManagement.keepFactory
SmartManagement.full と同じように、オブジェクトが使用されていない状態になれば破棄します。ただし、前述の「ファクトリー」に存在するものだけは残します。つまりそのインスタンスが再び必要になった際は依存オブジェクトを再度生成するということです。
### Bindingsの仕組み
Bindingsは「一過性のファクトリー」のようなものを作成します。これはそのRouteに画面遷移した瞬間に作成され、そこから画面移動するアニメーションが発生した瞬間に破棄されます。
この動作は非常に高速で行われるので、アナライザーでは捕捉できないほどです。
再び元の画面に戻ると新しい「一過性のファクトリー」が呼び出されます。そのためこれは SmartManagement.keepFactory を使用するよりも多くの場合好ましいですが、Bindingsを作成したくない場合やすべての依存オブジェクトを同じBindingsに持っておきたい場合は SmartManagement.keepFactory を使うといいでしょう。
ファクトリーのメモリ使用量は少なく、インスタンスを保持することはありません。その代わりにそのクラスのインスタンスを形作る関数を保持します。
メモリコストは非常に低いのですが、最小リソースで最大パフォーマンスを得ることが目的のGetではデフォルトでファクトリーを削除します。
どちらか都合に合う方ををお使いいただければと思います。
## 補足
- 複数のBindingsを使う場合は SmartManagement.keepFactory は**使わない**でください。これは Bindings を使わないケースや、GetMaterialAppのinitialBindingに設定された単独のBindingと一緒に使うケースを想定されて作られました。
- Bindingsを使うことは必須ではありません。`Get.put()` と `Get.find()` だけでも全く問題ありません。
ただし、サービスやその他抽象度の高いクラスをアプリに取り入れる場合はコード整理のために使うことをおすすめします。
... ...
- [Route管理](#Route管理)
- [使い方](#使い方)
- [通常Routeによるナビゲーション](#通常Routeによるナビゲーション)
- [名前付きRouteによるナビゲーション](#名前付きRouteによるナビゲーション)
- [名前付きRouteにデータを送る](#名前付きRouteにデータを送る)
- [動的URLの生成](#動的URLの生成)
- [ミドルウェアの使用](#ミドルウェアの使用)
- [contextを使わないナビゲーション](#contextを使わないナビゲーション)
- [SnackBar](#snackbar)
- [Dialog](#dialog)
- [BottomSheet](#bottomsheet)
- [ネスト構造のナビゲーション](#ネスト構造のナビゲーション)
# Route管理
このドキュメントではGetXにおけるRoute管理のすべてをご説明します。
## How to use
次の3文字を pubspec.yaml ファイルに追加してください。
```yaml
dependencies:
get:
```
Route / SnackBar / Dialog / BottomSheet をcontextなしで、あるいは高レベルのGet APIを使用するには MaterialApp の前に「Get」を追加してください。それだけで GetMaterialApp の機能が使用できます。
```dart
GetMaterialApp( // 変更前: MaterialApp(
home: MyHome(),
)
```
## 名前付きRouteによる画面遷移
次の画面に遷移するには Get.to を使ってください。
```dart
Get.to(NextScreen());
```
SnackBar / Dialog / BottomSheet など Navigator.pop(context) で閉じるものと同じものを閉じるには Get.back を使います。
```dart
Get.back();
```
次の画面に遷移しつつ、前の画面に戻れないようにするには Get.off を使います(スプラッシュスクリーンやログイン画面などで使用)。
```dart
Get.off(NextScreen());
```
次の画面に遷移して、それ以前のRouteはすべて破棄するには Get.offAll を使います(ショッピングカート、投票、テストなどで使用)
```dart
Get.offAll(NextScreen());
```
次の画面に遷移して、戻ったらデータを受け取る方法はこちら。
```dart
var data = await Get.to(Payment());
```
次の画面では、このようにデータを前の画面に送る必要があります。
```dart
Get.back(result: 'success');
```
そして使いましょう。
ex:
```dart
if(data == 'success') madeAnything();
```
どのようなシンタックスがあるかもっと知りたいですか?
いつもの Navigator ではなく navigator と入れてみてください。通常のNavigatorで使えるプロパティがcontextなしで使えるようになっているかと思います。
```dart
// 通常のFlutterによるNavigator
Navigator.of(context).push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return HomePage();
},
),
);
// GetではFlutterのシンタックスをcontextなしで使えます
navigator.push(
MaterialPageRoute(
builder: (_) {
return HomePage();
},
),
);
// Getのシンタックス(上記よりかなり短いですね)
Get.to(HomePage());
```
## 名前付きRouteによる画面遷移
- Getは名前付きRouteによる遷移もサポートしています。
次の画面への遷移はこう。
```dart
Get.toNamed("/NextScreen");
```
Get.off の名前付きRoute版。
```dart
Get.offNamed("/NextScreen");
```
Get.offAll の名前付きRoute版。
```dart
Get.offAllNamed("/NextScreen");
```
Routeを定義するにはGetMaterialAppを使ってください。
```dart
void main() {
runApp(
GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage()),
GetPage(name: '/second', page: () => Second()),
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.zoom
),
],
)
);
}
```
未定義Route(404エラー)に遷移させるには、GetMaterialAppで unknownRoute を設定してください。
```dart
void main() {
runApp(
GetMaterialApp(
unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage()),
GetPage(name: '/second', page: () => Second()),
],
)
);
}
```
### 名前付きRouteにデータを送る
次の画面に渡すデータは arguments で引数を設定します。Getでは引数にどんなものでも指定できます。StringでもMapでもListでも、クラスのインスタンスでも大丈夫です。
```dart
Get.toNamed("/NextScreen", arguments: 'Get is the best');
```
ビュー側のクラスやControllerで値を使うにはこうしてください。
```dart
print(Get.arguments);
// Get is the best が表示される
```
### 動的URLの生成
Getはウェブのような高度な動的URLを提供します。ウェブ開発者はFlutterにこの機能が提供されることを待ち望んでいたことでしょう。この機能の提供を謳うパッケージは存在しますが、ウェブ上のURLとは全く異なるシンタックスが表示されているのを見たことがあるかもしれません。Getはこの点も解決します。
```dart
Get.offAllNamed("/NextScreen?device=phone&id=354&name=Enzo");
```
ビュー側のクラスやControllerで値を使う方法。
```dart
print(Get.parameters['id']);
// 出力: 354
print(Get.parameters['name']);
// 出力: Enzo
```
この名前付きパラメーターはこのように簡単に受け取ることもできます。
```dart
void main() {
runApp(
GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(
name: '/',
page: () => MyHomePage(),
),
GetPage(
name: '/profile/',
page: () => MyProfile(),
),
// 引数userを使う場合と使わない場合で別ページを定義することが可能です。
// ただ、そのためにはスラッシュ '/' をベースのRoute名の後に入れる必要があります。
GetPage(
name: '/profile/:user',
page: () => UserProfile(),
),
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.cupertino
),
],
)
);
}
```
Route名を使ってデータを送る方法。
```dart
Get.toNamed("/profile/34954");
```
次の画面でデータを受け取る方法。
```dart
print(Get.parameters['user']);
// out: 34954
```
複数のパラメーターを送信するにはこちら。
```dart
Get.toNamed("/profile/34954?flag=true&country=italy");
```
もしくは
```dart
var parameters = <String, String>{"flag": "true","country": "italy",};
Get.toNamed("/profile/34954", parameters: parameters);
```
次の画面でデータを受け取る方法。
```dart
print(Get.parameters['user']);
print(Get.parameters['flag']);
print(Get.parameters['country']);
// 出力: 34954 true italy
```
あとは Get.toNamed() を使い、名前付きRouteを指定するだけです(contextを使わないので BLoC や Controller から直接Routeを呼び出すことができます)。ウェブアプリとしてコンパイルされると、Routeが正しくURLに表示されます。
### ミドルウェアの使用
何かのアクションのトリガーとなるイベントを取得したい場合は、routingCallbackを使用してください。
```dart
GetMaterialApp(
routingCallback: (routing) {
if(routing.current == '/second'){
openAds();
}
}
)
```
GetMaterialAppを使用しない場合は、手動のAPIを使ってミドルウェアオブザーバーを設定してください。
```dart
void main() {
runApp(
MaterialApp(
onGenerateRoute: Router.generateRoute,
initialRoute: "/",
navigatorKey: Get.key,
navigatorObservers: [
GetObserver(MiddleWare.observer), // ここ
],
),
);
}
```
ミドルウェアクラスを作成する
```dart
class MiddleWare {
static observer(Routing routing) {
/// Routeの他に SnackBar / Dialog / BottomSheet のイベントも監視することができます。
/// また、ここで直接この3つのいずれかを表示したい場合は、
/// イベント自身が「それではない」ことを事前にチェックする必要があります。
if (routing.current == '/second' && !routing.isSnackbar) {
Get.snackbar("Hi", "You are on second route");
} else if (routing.current =='/third'){
print('last route called');
}
}
}
```
それではGetをコードで使ってみましょう。
```dart
class First extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
onPressed: () {
Get.snackbar("hi", "i am a modern snackbar");
},
),
title: Text('First Route'),
),
body: Center(
child: ElevatedButton(
child: Text('Open route'),
onPressed: () {
Get.toNamed("/second");
},
),
),
);
}
}
class Second extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
onPressed: () {
Get.snackbar("hi", "i am a modern snackbar");
},
),
title: Text('second Route'),
),
body: Center(
child: ElevatedButton(
child: Text('Open route'),
onPressed: () {
Get.toNamed("/third");
},
),
),
);
}
}
class Third extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Third Route"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Get.back();
},
child: Text('Go back!'),
),
),
);
}
}
```
## contextを使わないナビゲーション
### SnackBar
FlutterでシンプルなSnackBarを表示したいとき、Scaffoldのcontextか、GlobalKeyを取得する必要があります。
```dart
final snackBar = SnackBar(
content: Text('Hi!'),
action: SnackBarAction(
label: 'I am a old and ugly snackbar :(',
onPressed: (){}
),
);
// WidgetツリーでScaffoldを探し、それをSnackBar表示に使用します。
Scaffold.of(context).showSnackBar(snackBar);
```
Getならこうなります。
```dart
Get.snackbar('Hi', 'i am a modern snackbar');
```
コードのどこにいようと、Get.snackbar を呼ぶだけでいいのです。カスタマイズも自由自在です。
```dart
Get.snackbar(
"Hey i'm a Get SnackBar!", // タイトル
"It's unbelievable! I'm using SnackBar without context, without boilerplate, without Scaffold, it is something truly amazing!", // 本文
icon: Icon(Icons.alarm),
shouldIconPulse: true,
onTap:(){},
barBlur: 20,
isDismissible: true,
duration: Duration(seconds: 3),
);
////////// すべてのプロパティ //////////
// Color colorText,
// Duration duration,
// SnackPosition snackPosition,
// Widget titleText,
// Widget messageText,
// bool instantInit,
// Widget icon,
// bool shouldIconPulse,
// double maxWidth,
// EdgeInsets margin,
// EdgeInsets padding,
// double borderRadius,
// Color borderColor,
// double borderWidth,
// Color backgroundColor,
// Color leftBarIndicatorColor,
// List<BoxShadow> boxShadows,
// Gradient backgroundGradient,
// TextButton mainButton,
// OnTap onTap,
// bool isDismissible,
// bool showProgressIndicator,
// AnimationController progressIndicatorController,
// Color progressIndicatorBackgroundColor,
// Animation<Color> progressIndicatorValueColor,
// SnackStyle snackStyle,
// Curve forwardAnimationCurve,
// Curve reverseAnimationCurve,
// Duration animationDuration,
// double barBlur,
// double overlayBlur,
// Color overlayColor,
// Form userInputForm
///////////////////////////////////
```
従来の SnackBar がお好みの場合や、ゼロからカスタマイズしたい場合 (たとえば Get.snackbar ではタイトルと本文が必須項目となっています)は `Get.rawSnackbar();` を使ってください。SnackBarの元々のAPIを取得できます。
### Dialog
ダイアログを表示する方法。
```dart
Get.dialog(YourDialogWidget());
```
デフォルトのダイアログを表示する方法。
```dart
Get.defaultDialog(
onConfirm: () => print("Ok"),
middleText: "Dialog made in 3 lines of code"
);
```
また showGeneralDialog の代わりに Get.generalDialog が使えます。
Overlayを使用するCupertino含むその他のFlutterのダイアログについては、contextの代わりに Get.overlayContext を使うことでコードのどこでもダイアログを表示することができます。
Overlayを使わないWidgetについては、Get.context が使えます。
これら2つのcontextはほとんどのケースでUIのcontextを代替することができるでしょう。ただし、ナビゲーションのcontextを使用せずInheritedWidgetが使われているケースは例外です。
### BottomSheet
Get.bottomSheet は showModalBottomSheet に似ていますが、contextが不要です。
```dart
Get.bottomSheet(
Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.music_note),
title: Text('Music'),
onTap: () {}
),
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video'),
onTap: () {},
),
],
),
)
);
```
## ネスト構造のナビゲーション
GetはFlutterのネスト構造のナビゲーションの扱いも簡単にしてくれます。
contextを必要とせず、IDによりナビゲーションのスタックを見つけることができます。
- 注: 並列のナビゲーションスタックを作成することは危険です。ネスト構造のNavigatorを使用しないか、使用を控えめにするのが理想です。必要なら使っていただいても問題ありませんが、複数のナビゲーションのスタックを保持することはRAM消費の面で好ましくないということは覚えておいてください。
こんなに簡単にできます。
```dart
Navigator(
key: Get.nestedKey(1), // インデックス指定でkey作成
initialRoute: '/',
onGenerateRoute: (settings) {
if (settings.name == '/') {
return GetPageRoute(
page: () => Scaffold(
appBar: AppBar(
title: Text("Main"),
),
body: Center(
child: TextButton(
color: Colors.blue,
onPressed: () {
Get.toNamed('/second', id:1); // インデックス指定でネスト型Routeに遷移
},
child: Text("Go to second"),
),
),
),
);
} else if (settings.name == '/second') {
return GetPageRoute(
page: () => Center(
child: Scaffold(
appBar: AppBar(
title: Text("Main"),
),
body: Center(
child: Text("second")
),
),
),
);
}
}
),
```
... ...
* [状態管理](#状態管理)
+ [リアクティブな状態管理](#リアクティブな状態管理)
- [利点](#利点)
- [パフォーマンスの最大化](#パフォーマンスの最大化)
- [リアクティブな変数の宣言](#リアクティブな変数の宣言)
- [初期値の設定](#初期値の設定)
- [Observableの値をビュー内で使う](#Observableの値をビュー内で使う)
- [更新条件を設定](#更新条件を設定)
- [.obsの使いどころ](#.obsの使いどころ)
- [List(Rx)に関する補足](#List(Rx)に関する補足)
- [なぜ「.value」を使う必要があるのか](#なぜ「.value」を使う必要があるのか)
- [Obx()](#obx)
- [Worker](#worker)
+ [非リアクティブな状態管理](#非リアクティブな状態管理)
- [利点](#利点)
- [使用例](#使用例)
- [Controllerインスタンスの扱い](#Controllerインスタンスの扱い)
- [StatefulWidgetsはもういらない](#StatefulWidgetsはもういらない)
- [Getの目的](#Getの目的)
- [Controllerの様々な使用方法](#Controllerの様々な使用方法)
- [ユニークIDの設定](#ユニークIDの設定)
+ [状態管理ソリューションを混在させる](#状態管理ソリューションを混在させる)
+ [StateMixin](#StateMixin)
+ [GetBuilder VS GetX VS Obx VS MixinBuilder](#GetBuilder-VS-GetX-VS-Obx-VS-MixinBuilder)
# 状態管理
GetXは他の状態管理ライブラリのように Stream や ChangeNotifier を使用する必要がありません。なぜか?私たちは応答時間とRAM消費量を改善するために GetValueとGetStream という低遅延のソリューションを開発しましたが、状態管理機能を含むGetXのリソースはすべてこれをベースに作られているためです。このソリューションはより低い運用コストと高いパフォーマンスを実現します。GetXを使えばAndroid、iOS、Web、Linux、macOS用のアプリケーションを作成するだけでなく、Flutter/GetXと同じシンタックスでサーバーアプリケーションを作ることができます。
* _バカみたいにシンプル_: 他の状態管理アプローチの中には、複雑で多くのボイラープレートコードを書かなければいけないものもあります。この問題により少なくない人たちがFlutterを見限りましたが、今ようやく、バカみたいにシンプルなソリューションを手に入れることができました。GetXを使えば、非常にすっきりとした、記述量の少ないコードでより多くのことができるようになります。イベントごとにクラスを定義する必要もありません。
* _コード生成にサヨナラ_: 開発時間の半分はアプリケーションロジックの作成に費やします。それにも関わらず、状態管理ライブラリの中には、ミニマルなコードを作るためにコード生成ツールに依存しているものがあります。変数を変更して build_runner を実行するのは非生産的ですし、flutter clean 後の待ち時間もコーヒーをたくさん飲まなければならないほど長くなることもあります。
GetXはすべてがリアクティブであり、コード生成ツールに依存しないため、開発のあらゆる面において生産性が向上します。
* _context依存にサヨナラ_: ビューとビジネスロジックを連携させるため、ビューのcontextをControllerに送る必要に迫られた。contextがないところで依存オブジェクトの注入をする必要があり、contextを方々のクラスや関数からなんとか渡した。これらの経験、誰もが通ってきた道かと思います。しかし、GetXではこのような経験をすることはありません。contextなしで、Controllerの中から別のControllerにアクセスすることができます。パラメーターを通じて無駄にcontextを送る必要はもうありません。
* _細かいコントロール_: 多くの状態管理ソリューションは、ChangeNotifierをベースにしています。ChangeNotifierは、notifyListenerが呼ばれたときに、依存するすべてのWidgetに通知します。画面に40個のWidgetがあるとしましょう。それらがすべてChangeNotifierの変数に依存している場合、変数を1つでも更新すれば、すべてのWidgetが更新されます。
GetXを使えばネストされたWidgetさえも的確にビルドを処理することができます。ListViewを担当するObxと、ListViewの中のチェックボックスを担当するObxがあれば、チェックボックスの値を変更した場合はチェックボックスWidgetだけが更新され、Listの値を変更した場合はListViewだけが更新されます。
* _変数が本当に変わったときだけ更新する_: GetXはデータの流れをコントロールします。つまり、Textに紐づいたObservable(監視可能)変数の値 'Paola' を、同じ 'Paola' に変更してもWidgetは更新されません。これは、GetXがTextに'Paola'がすでに表示されていることをわかっているためです。
多くの状態管理ソリューションは、この場合更新を行います。
## リアクティブな状態管理
リアクティブプログラミングは複雑であると言われがちなためか、多くの人に敬遠されています。しかし、GetXはリアクティブプログラミングを非常にシンプルなものにしてくれます。
* StreamControllerを作る必要はありません。
* 変数ごとにStreamBuilderをセットする必要はありません。
* 状態ごとにクラスを作る必要はありません。
* 初期値のためにgetを準備する必要はありません。
Getによるリアクティブプログラミングは、setState並に簡単です。
たとえば name という変数があり、それを変更するたびに変数に依存するすべてのWidgetを自動更新したいとします。
これがその name 変数です。
``` dart
var name = 'Jonatas Borges';
```
これをObservable(監視可能)にするには、値の末尾に ".obs" を付け足すだけです。
``` dart
var name = 'Jonatas Borges'.obs;
```
これで終わりです。*こんなに* 簡単なんですよ。
(以後、このリアクティブな ".obs" 変数、Observable(監視可能)を _Rx_ と呼ぶことがあります。)
内部ではこのような処理を行っています: `String`の`Stream`を作成し、初期値`"Jonatas Borges"`を割り当て、`"Jonatas Borges"`に依存するすべてのWidgetに、あなたは今この変数の影響下にあるから、_Rx_の値が変更されたときには、あなたも同様に変更する必要がある旨を通知。
これがDartの機能のおかげで実現できた **GetX マジック** です。
しかし皆さんご存知の通り、`Widget` は関数の中にいなければ自らを更新できません。静的クラスには「自動更新」の機能がないからです。
それなら、同じスコープ内で複数の変数に依存してWidgetをビルドする場合は、複数の `StreamBuilder` をネストして変数の変化を監視する必要がありますね。
いいえ、**GetX** なら `StreamBuilder` すら不要です。
またWidgetを更新する際のボイラープレートコードについても、**GetX**では忘れてください。
`StreamBuilder( ... )` ? `initialValue: ...` ? `builder: ...` ? これらはすべて不要で、対象のWidgetを `Obx()` の中に入れるだけです。
``` dart
Obx (() => Text (controller.name));
```
_覚えること?_ それは `Obx(() =>` だけです。
そのWidgetをアロー関数を通じて `Obx()`(_Rx_のObserver(監視者))に渡すだけです。
`Obx` は非常に賢く、`controller.name` の値が本当に変わったときにのみ、Widgetの更新をかけます。
`name` が `"John"` だとして、それを `"John"` ( `name.value = "John"` ) に変更しても、以前と同じ `value` のため画面上では何も変化しません。`Obx` はリソースを節約するために値を無視し、Widgetを更新しません。**すごいでしょ?**
> では、もしも `Obx` の中に_Rx_(Observable)変数が5つあったらどうでしょう?
5つの**いずれかに**値の変化があればWidgetは更新されます。
> また、1つのControllerクラスに30もの変数がある場合、1つの変数を更新したら変数に関わるWidgetが**すべて**更新されてしまうのでしょうか?
いいえ、_Rx_ 変数を使う特定のWidgetだけが更新されます。
言い換えるなら、**GetX**は _Rx_ 変数の値が変化したときだけ画面更新をしてくれるということです。
```dart
final isOpen = false.obs;
// 同じ値なので何も起きません。
void onButtonTap() => isOpen.value=false;
```
### 利点
**GetX()**は何を更新して何をしないのか、の**細かい**コントロールが可能です。
すべての更新するのでそのようなコントロールが不要な場合は、`GetBuilder` を検討してください。
これはわずか数行のコードで作られた、状態更新のためのシンプルなビルダーです。(`setState()`のようにブロックで)
CPUへの影響を最小限にするために作られており、単一の目的(_状態_ の再構築)を果たすため、可能な限りリソース消費を抑えました。
**強力な** 状態管理のソリューションを求めているなら、**GetX**で間違いはありません。
変数をそのまま扱うことはできませんが、内部では `Stream` としてデータが扱われています。
すべてが `Stream` なので、_RxDart_ を組み合わせることも可能ですし、
"_Rx_ 変数" のイベントや状態を監視することも可能です。
GetXは _MobX_ より簡単で、コード自動生成や記述量を減らした_BLoC_ 型アプローチと言えるかもしれません。
値の末尾に `.obs` を付けるだけで**なんでも** _"Observable(監視可能)"_ にできるのです。
### パフォーマンスの最大化
ビルドを最小限に抑えるための賢いアルゴリズムに加えて、
**GetX**はコンパレーターを使用して状態が変更されたことを確認します。
アプリでなにかしらのエラーが発生し、状態が変更された情報を
二重に送信してしまったとしても**GetX**はクラッシュを防いでくれます。
**GetX**では値が変化したときにはじめて「状態」が変化するためです。
これが **GetX** と _MobX の `computed`_ を使う際の主な違いです。
2つの __Observable__ を組み合わせて一つが変化したとき、それを監視しているオブジェクトも変化します。
これは `GetX()` (`Observer()`のようなもの) において2つの変数を組み合わせた場合においても、
それが本当に状態の変化を意味するときだけWidgetの更新が行われるということでもあります。
### リアクティブな変数の宣言
変数を "Observable" にする方法は3つあります。
1 - **`Rx{Type}`** を使用する
``` dart
// 初期値を入れることを推奨しますが、必須ではありません
final name = RxString('');
final isLogged = RxBool(false);
final count = RxInt(0);
final balance = RxDouble(0.0);
final items = RxList<String>([]);
final myMap = RxMap<String, int>({});
```
2 - **`Rx`** とジェネリクスによる型指定の組み合わせ
``` dart
final name = Rx<String>('');
final isLogged = Rx<Bool>(false);
final count = Rx<Int>(0);
final balance = Rx<Double>(0.0);
final number = Rx<Num>(0);
final items = Rx<List<String>>([]);
final myMap = Rx<Map<String, int>>({});
// 任意の型を指定可能 - どんなクラスでもOK
final user = Rx<User>();
```
3 - 最も実用的で簡単な方法として、**`.obs`** を値に付ける
``` dart
final name = ''.obs;
final isLogged = false.obs;
final count = 0.obs;
final balance = 0.0.obs;
final number = 0.obs;
final items = <String>[].obs;
final myMap = <String, int>{}.obs;
// カスタムクラスのインスタンスにも付けられます
final user = User().obs;
```
##### 初期値の設定
ご存知の通り、_Dart_ は現在 _null safety_ へ移行しているところです。
それに備えるために今後は _Rx_ 変数は常に**初期値**を設定してください。
> **GetX** で変数を _Observable_ にしつつ _初期値_ を設定するのはとても簡単です。
変数の末尾に `.obs` を付ける。**それだけ。**
めでたく Observable とそのプロパティ `.value` (つまり _初期値_)ができました。
### Observableの値をビュー内で使う
``` dart
// Controllerクラス
final count1 = 0.obs;
final count2 = 0.obs;
int get sum => count1.value + count2.value;
```
``` dart
// ビュークラス
GetX<Controller>(
builder: (controller) {
print("count 1 rebuild");
return Text('${controller.count1.value}');
},
),
GetX<Controller>(
builder: (controller) {
print("count 2 rebuild");
return Text('${controller.count2.value}');
},
),
GetX<Controller>(
builder: (controller) {
print("count 3 rebuild");
return Text('${controller.sum}');
},
),
```
`count1.value++` を実行すると、以下の通りprintされます。
* `count 1 rebuild`
* `count 3 rebuild`
なぜなら `count1` の値が `1` に変わり、それに伴ってgetter `sum` の値にも `1 + 0 = 1` と変化が起こるからです。
今度は `count2.value++` を実行してみましょう。
* `count 2 rebuild`
* `count 3 rebuild`
もうおわかりですね。これは `count2.value` が変わり、その結果 `sum` が `2` になったからです。
* 注: デフォルト仕様では、`value` に変化がなかったとしても、それが最初のイベントであればWidgetを更新します。
この仕様はbool変数の性質から来るものです。
たとえばこの場合を想像してみてください。
``` dart
var isLogged = false.obs;
```
そして、isLogged(ユーザーがログインしたかどうか)の変化をトリガーにever関数内のコールバックfireRouteを呼び出したいとします。
``` dart
@override
onInit() async {
// everは引数1が変化するたびに引数2を実行するリスナー
ever(isLogged, fireRoute);
isLogged.value = await Preferences.hasToken();
}
fireRoute(logged) {
if (logged) {
Get.off(Home());
} else {
Get.off(Login());
}
}
```
もし `hasToken` が `false` なら `isLogged` に変化はありません。すると `ever()` のコールバックは永遠に呼び出されないことになります。
このような挙動を防ぐために _Observable_ への最初の更新は、それがたとえ同じ `.value` だったとしても
常にイベントを引き起こすようにしています。
ご参考までに、この仕様は以下の設定で解除することができます。
`isLogged.firstRebuild = false;`
### 更新条件を設定
Getにはさらに洗練された「状態」のコントロール方法があります。イベント(Listへのオブジェクト追加など)に対して条件を付けることが可能です。
``` dart
// 引数1: Listにオブジェクトを加える条件。trueかfalseを返すこと
// 引数2: 条件がtrueの場合に加える新しいオブジェクト
list.addIf(item < limit, item);
```
最低限のコードで、コード生成ツールも使わず、とても簡単ですね :smile:
カウンターアプリもこのようにシンプルに実現できます。
``` dart
class CountController extends GetxController {
final count = 0.obs;
}
```
Controllerを設定して、下記を実行するだけ。
``` dart
controller.count.value++
```
UIの数字が置き換わりましたね。このようにアプリのどこであっても更新をかけることができます。
### .obsの使いどころ
.obs を使うことでどんなものもObservableにすることができます。方法は2つ。
* クラスのインスタンス変数をobsに変換する
``` dart
class RxUser {
final name = "Camila".obs;
final age = 18.obs;
}
```
* クラスのインスタンスを丸々obsに変換する
``` dart
class User {
User({String name, int age});
var name;
var age;
}
// インスタンス化の際
final user = User(name: "Camila", age: 18).obs;
```
### List(Rx)に関する補足
List(Rx)はその中のオブジェクトと同様、監視可能(Observable)です。そのためオブジェクトを追加すると、List(Rx)に依存するWidgetは自動更新されます。
またList(Rx)をListとするために ".value" を使う必要はありません。DartのAPIがこれを可能にしてくれました。ただ、残念ながら他のStringやintのようなプリミティブ型は拡張ができないため、.value を使う必要があります。getterやsetterを活用するのであればあまり問題になりませんが。
``` dart
// Controllerクラス
final String title = 'User Info:'.obs
final list = List<User>().obs;
// ビュークラス
Text(controller.title.value), // Stringの場合は .value が必要
ListView.builder (
itemCount: controller.list.length // Listの場合は不要
)
```
カスタムのクラスをObservableにした場合は、様々な方法で値を更新することができます。
``` dart
// モデルクラス
// 属性をobsにするやり方ではなく、クラス全体をobsにする方法を採ります
class User() {
User({this.name = '', this.age = 0});
String name;
int age;
}
// Controllerクラス
final user = User().obs;
// user変数を更新するときはこのようなメソッドを作ります
user.update( (user) { // このパラメーターは更新するオブジェクトそのもの
user.name = 'Jonny';
user.age = 18;
});
// あるいは、この方法でも。変数名は呼び出し可能です。
user(User(name: 'João', age: 35));
// ビュークラス
Obx(()=> Text("Name ${user.value.name}: Age: ${user.value.age}"))
// .value を使わずにモデルのプロパティにアクセスすることも可能です
user().name; // userがUserではないことに注目。user()でUserを受け取れます。
```
ListのsetAllやsetRangeメソッドの代わりに、"assign" "assignAll" APIを使っていただくことも可能です。
"assign" APIはListの内容をクリアした後に、指定した単独のオブジェクトを追加してくれます。
"assignAll" APIはそのIterable版です。
### なぜ「.value」を使う必要があるのか
ちょっとしたアノテーションとコード生成ツールを使って`String`や`int`で `.value` を使わなくて済むようにもすることはできますが、このライブラリの目的は「外部依存パッケージを減らす」ことです。私たちは、外部パッケージを必要としない、必須ツール(Route、依存オブジェクト、状態の管理)が揃った開発環境を軽量かつシンプルな方法で提供したいと考えています。
まさに pubspecに3文字(get)とコロンを加えて、プログラミングを始めることができるのです。Route管理から状態管理まで、必要なソリューションが標準装備されています。GetXはシンプルさ、生産性、高いパフォーマンスを目指します。
これほど多機能であるにも関わらず、このライブラリの総容量は他の多くの状態管理ライブラリよりも少ないです。その点をご理解いただけるとうれしいです。
`.value` が嫌でコード生成ツールを使いたいという方には、MobXは素晴らしいライブラリだと思いますし、Getと併用することもできます。逆に多くの外部パッケージに依存したくない方、パッケージ間の互換性を気にしたくない方、状態管理ツールや依存オブジェクトから状態更新エラーが出ているかどうかを気にせずプログラミングをしたい方、依存するControllerクラスのインスタンスがあるかどうかを都度都度心配したくない方にとってはGetはまさに最適です。
MobXのコード生成や、BLoCのボイラープレートコードが気にならないのであれば、Route管理にだけでもGetをお使いいただけるとうれしいです。GetのSEMとRSMは必要に迫られて生まれたものです。私の会社で以前、90以上のControllerを持つプロジェクトがあり、それなりの性能のマシンでflutter cleanを行った後でさえ、コード生成ツールがタスクを完了するのに30分以上かかりました。もしあなたが大きなプロジェクトに関わっており、コード生成ツールが問題になっているのであれば、Getを検討してみてください。
もちろん、コード生成ツールをGetXに導入したい方が実際にツールを作成してプロジェクトに貢献した場合は、このReadMeに代替ソリューションとして掲載させていただきます。私はすべての開発者のニーズをかなえたいわけではありませんが、今はこの質問に対しては、「すでにMobXのように同様のことを実現してくれる良いソリューションがある」とだけ言わせてください。
### Obx()
GetX()の代わりにObx()を使用することもできます。ObxはWidgetを生成する匿名関数をパラメーターに持ちます。複数のControllerに対応することができますが、自身はControllerのインスタンスを持たず、型指定もできません。そのため別途Controllerのインスタンスを作るか、`Get.find<Controller>()` でインスタンスを探しておく必要があります。
### Worker
Worker はイベント発生に伴って指定したコールバックを呼び出すことができます。
``` dart
/// `count1` が更新されるたびに第2引数のコールバックが実行される
ever(count1, (_) => print("$_ has been changed"));
/// `count1` の最初の更新時のみ実行される
once(count1, (_) => print("$_ was changed once"));
/// DDoS攻撃対策に最適。たとえば、ユーザーが打鍵やクリックを止めて1秒後に実行など
debounce(count1, (_) => print("debouce$_"), time: Duration(seconds: 1));
/// 1秒以内の連続更新はすべて無視して実行しない
interval(count1, (_) => print("interval $_"), time: Duration(seconds: 1));
```
すべてのWorker(`debounce` 以外) は `condition` パラメーターを持ちます。`condition` は `bool` でも `bool` を返すコールバックでも構いません。
この `condition` が Worker のコールバックを実行するかどうかを決めています。
また Worker は `Worker` インスタンスを返します。これは `dispose()` などを通じて Worker を破棄するときに使用します。
* **`ever`**
は _Rx_ 変数が新しい値になるたびに呼ばれます。
* **`everAll`**
`ever` とほぼ同じですが、_Rx_ 変数の `List` を受け取ります。いずれかの値が更新されれば、その更新後の値を受け取ってコールバックが実行されます。
* **`once`**
変数が最初に更新されたときのみに呼ばれます。
* **`debounce`**
'debounce' は検索機能などで導入するととても有益です。たとえば、ユーザーがタイピングを止めたときにのみAPIを呼び出したいときに使います。ユーザーが "Jonny" と入れたときに 5回も APIに問い合わせを行うのは避けたいですよね。Getなら "debounce" があるので大丈夫です。
* **`interval`**
`interval` は debounce とは異なります。ユーザーが1秒間に1000回変数に変更を加えた場合、debounceが一定期間経過後(デフォルトは800ミリ秒)に最後の変更イベントだけ送信するのに対して、intervalは代わりに一定期間の間のユーザーによるアクションをすべて無視します。intervalは1秒ごとにイベントを送信しており、3秒に設定した場合は1分間に20個のイベントを送信します。これはユーザーがキーやマウスを連打することで何かしらの報酬を得られる場合に、その悪用を避けるために使用できます(ユーザーが何かをクリックしてコインを獲得できるとします。たとえ何秒かかったとしても300回クリックすれば300枚のコインを得ることができてしまいます。intervalを使用してインターバルを3秒に設定した場合は、何回クリックしようが1分間で得られるコインの上限は20枚になります)。一方のdebounceはアンチDDosや、検索のように変更を加えるたびにonChangeからAPI問い合わせが発生するような機能に適しています。ユーザーが入力し終わるのを待ってリクエストを送信するのです。debounceを前述のコイン獲得のケースで使用した場合、ユーザーはコインを1枚しか獲得できません。これは指定した期間、ユーザーが動作を「一時停止」したときにのみ実行されるからです。
* 注: Workerを使用する場合は、Controllerなどを起動するときに次のいずれかの方法で登録する必要があります。onInit(推奨)内、クラスのコンストラクタ、またはStatefulWidgetのinitState内(この方法は推奨しませんが、副作用はないはずです)。
## 非リアクティブな状態管理
GetはChangeNotifierを使わない軽量かつシンプルな状態管理機能を有しています。特にFlutterに慣れていない方のニーズを満たし、大規模なアプリケーションでも問題を起こすことがないと信じています。
GetBuilderは複数の状態を扱う場面で使われることを想定して作られました。たとえばショッピングカートに30個の商品があるとします。そしてあなたが商品を一つ削除すると同時に、カートのリストが更新され、合計金額が更新され、アイテム数を示すバッジが更新されます。GetBuilderはこのようなユースケースに最適です。というのも、GetBuilderは状態をControllerで束ねてそのControllerに依存するすべてのWidgetを一度に更新させることができるからです。
それらとは独立したControllerが必要な場合は、GetBuilderのidプロパティに専用IDを割り当てるか、GetXを使ってください。ケースバイケースですが、そのような「独立した」Widetが多いほど GetX() のパフォーマンスが際立ち、複数の状態変化がありそれに伴うWidgetの更新が多いほど GetBuilder() のパフォーマンスが勝ることを覚えておいてください。
### 利点
1. 必要なWidgetのみ更新される。
2. ChangeNotifierを使わず、メモリ使用量が少ない。
3. StatefulWidgetのことはもう忘れましょう。Getでは必要ありません。他の状態管理ライブラリではStatefulWidgetを使用することがあるでしょう。しかしAppBarやScaffoldなどクラス内のほとんどのWidgetがStatelessであるにも関わらず、StatefulなWidgetの状態だけを保持する代わりに、クラス全体の状態を保持しているのはなぜでしょうか?Getならクラス全体をStatelessにすることができます。更新が必要なコンポーネントは GetBuilder などで囲むことで「状態」が保持されます。
4. プロジェクトを整理しましょう!ControllerはUIの中にあってはいけません。TextEditControllerなどの類はすべてControllerクラスに配置してしまいましょう。
5. Widgetのレンダリングが開始されると同時にイベントを実行してWidgetを更新させる必要がありますか?GetBuilderにはStatefulWidgetと同様の「initState」プロパティがあり、そこからControllerのイベントを直接呼び出すことができます。initStateを使用する必要はもうありません。
6. StreamやTimerのインスタンスを破棄したい場合はGetBuilderのdisposeプロパティを利用してください。Widgetが破棄されると同時にイベントを呼び出すことができます。
7. GetXとStreamController / StreamBuilderを組み合わせるなどしてStreamを普通に使っていただいても問題ありませんが、必要なときに限って使うことをおすすめします。Streamのメモリ消費は適度であり、リアクティブプログラミングは美しいですが、たとえば30ものStreamを同時に立ち上げることを考えてみてください。これはChangeNotifierを使うよりもよくないことのように思います。
8. 必要以上にRAMを使わずWidgetを更新します。GetはGetBuilderのクリエーターIDのみを保存し、必要に応じてGetBuilderを更新します。何千ものGetBuilderを作成したとしても、ID保存のためのメモリ消費量は非常に少ないです。GetBuilderを新規に作成するということは、実際にはクリエーターIDを持つ GetBuilder の状態を共有しているに過ぎないためです。GetBuilderごとに状態が新たに作成されるわけではないため、特に大規模なアプリケーションでは多くのRAMを節約できます。基本的にGetXで作成するアプリケーションは全体的にStatelessであり、いくつかのStatefulなWidget(GetBuilder内のWidget)は単一の状態を持っているため、一つを更新すればすべてが更新されます。
9. Getはアプリ全体の流れをよく把握しており、Controllerをメモリから破棄するタイミングを正確に知っています。実際の破棄はGetがやってくれるため、開発者が心配する必要はありません。
### 使用例
``` dart
// Controllerクラスを作成してGetxControllerを継承しましょう
class Controller extends GetxController {
int counter = 0;
void increment() {
counter++;
update();
// increment 実行時にcounter変数に依存するUIを更新。
// GetBuilderを使うWidgetの場合はupdate()が必要。
}
}
// ビュー側のクラスでGetBuilderを使ってcounter変数を組み込む
GetBuilder<Controller>(
init: Controller(), // 最初に使用するときのみ初期化
builder: (_) => Text(
'${_.counter}',
),
)
// Controllerの初期化は最初の1回だけ行ってください。同じControllerを再度 GetBuilder / GetX で使用する場合は初期化する必要はありません。コントローラは、それを「init」とマークしたウィジェットがデプロイされると同時に、自動的にメモリから削除されます。Getがすべて自動で行ってくれるので、何も心配することはありません。同じControllerを2つ立ち上げることがないよう、それだけご注意ください。
```
**最後に**
* 以上、Getを使った状態管理の手法をご説明させていただきました。
* 注: もっと柔軟に管理する手法として、initプロパティを使わない方法もあります。Bindingsを継承したクラスを作成し、dependenciesメソッドをoverrideしてその中でGet.put()でControllerを注入してください(複数可)。このクラスとUI側のクラスを紐づけることでControllerをそのRoute内で使用できます。そしてそのControllerを初めて使用するとき、Getはdependencies内を見て初期化を実行してくれます。このlazy(遅延、消極的)ロードを維持しつつ、不要になったControllerは破棄し続けます。具体的な仕組みについてはpub.devの例をご参照ください。
Routeを移動して以前使用したControllerのデータが必要になった場合は、再度GetBuilderを使用してください。initする必要はありません。
``` dart
class OtherClass extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GetBuilder<Controller>(
builder: (s) => Text('${s.counter}'),
),
),
);
}
```
GetBuilderの外でControllerを使用する場合は、Controller内にgetterを作成しておくと便利です。Controller.to で呼び出しましょう。(もしくは `Get.find<Controller>()` を使うのもありです)
``` dart
class Controller extends GetxController {
/// 記述量を省くためにstaticメソッドにすることをおすすめします。
/// staticメソッド使う場合 → Controller.to.increment();
/// 使わない場合 → Get.find<Controller>().increment();
/// どちらを使ってもパフォーマンスに影響があったり副作用が出たりはしません。前者は型の指定が不要という違いがあるだけです
static Controller get to => Get.find(); // これを追加
int counter = 0;
void increment() {
counter++;
update();
}
}
```
これで以下のようにControllerに直接アクセスできます。
``` dart
FloatingActionButton(
onPressed: () {
Controller.to.increment(),
} // とっても簡単ですね!
child: Text("${Controller.to.counter}"),
),
```
FloatingActionButton を押すと counter変数 に依存するWidgetがすべて自動的に更新されます。
### Controllerインスタンスの扱い
次のような画面の流れがあるとします。
`画面A => 画面B (Controller X を使用) => 画面C (Controller X を使用)`
画面Aの段階ではまだ未使用なので、Controllerはメモリにありません(Getは基本lazyロードなので)。画面Bに遷移すると、Controllerがメモリ内に保存されます。画面Cでは画面Bと同じControllerを使用しているため、GetはBとCでControllerの状態を共有し、同じControllerがメモリ内に引き続きいることになります。画面Cを閉じてさらに画面Bを閉じ、画面Aに戻ったとしましょう。そこではControllerが使われていないため、GetはControllerをメモリから出してリソースを解放します。そこで再度画面Bに遷移すると、Controllerは再度メモリに保存されます。そして今度は画面Cに行かずに画面Aに戻ります。Getは同様にControllerをメモリから破棄してくれます。また、仮に画面CがControllerを使っておらず画面Cにいたとして、画面BをRouteスタックから削除したとしましょう。するとControllerを使用している画面(クラス)はなくなりますので、同様にメモリから破棄されます。Getが正常動作しないと考えられる唯一の例外は、画面Cにいるときに画面Bを誤ってRouteスタックから削除してしまい、Controllerの使用を試みたときです。この場合は、画面Bで作成されたControllerのクリエーターIDが削除されてしまったことが原因です(GetはクリエーターIDのないControllerはメモリから破棄するようプログラムされています)。もし意図があってこの事例に対応したい場合は、画面BのGetBuilderに "autoRemove: false" フラグを追加した上で、CクラスのGetBuilderに "adoptID: true" を追加してください。
### StatefulWidgetsはもういらない
StatefulWidgetsを使用すると、画面全体の状態を不必要に保存することになります。ウィジェットを最小限に再構築する必要がある場合は、Consumer/Observer/BlocProvider/GetBuilder/GetX/Obxの中に埋め込むことになりますが、それは別のStatefulWidgetになります。
StatefulWidgetはStatelessWidgetよりも多くのRAMが割り当てられます。これは1つや2つのStatefulWidgetでは大きな違いは産まないかもしれませんが、それが100もあった場合は確実に違いが出ます。
TickerProviderStateMixinのようなMixinを使用する必要がない限り、GetでStatefulWidgetを使用する必要はありません。
たとえばinitState()やdispose()メソッドなど、StatefulWidgetのメソッドをGetBuilderから直接呼び出すことも可能です。
``` dart
GetBuilder<Controller>(
initState: (_) => Controller.to.fetchApi(),
dispose: (_) => Controller.to.closeStreams(),
builder: (s) => Text('${s.username}'),
),
```
しかし、これよりもベターなアプローチはControllerの中で直接 onInit() や onClose() メソッドを呼び出すことです。
``` dart
@override
void onInit() {
fetchApi();
super.onInit();
}
```
* 注: コンストラクタを通じてControllerを立ち上げる必要はありません。このようなプラクティスは、パフォーマンス重視であるGetのControllerの作成や割り当ての原理、考え方から外れてしまいます(コンストラクタ経由でインスタンスを作成すれば、実際に使用される前の段階でControllerを生成し、メモリを割り当てることになります)。onInit() と onClose() メソッドはこのために作られたもので、Controllerのインスタンスが作成されたとき、または初めて使用されたときに呼び出されます(Get.lazyPutを使用しているか否か次第)。たとえば、データを取得するためにAPIを呼び出したい場合は initState/dispose の代わりに onInit() を使用し、Streamを閉じるなどのコマンドを実行する必要がある場合は onClose() を使用してください。
### Getの目的
このパッケージの目的は、Routeのナビゲーション、依存オブジェクトと状態の管理のための完全なソリューションを、開発者が外部パッケージに極力依存せずに済むような形で提供し、高度なコード分離性(デカップリング)を実現することです。それを確実なものとするため、Getはあらゆる高レベルおよび低レベルのFlutter APIを取り込んでいます。これによりビューとロジックを切り分けることが容易になり、UIチームにはWidgetの構築に集中してもらい、ビジネスロジック担当チームにはロジックに集中してもらうことができます。Getを使うことでよりクリーンな作業環境を構築することができるのです。
要するに、initState内でメソッドを呼び出してパラメーターを通じてControllerにデータを送信する必要も、そのためにControllerのコンストラクタを使用する必要もありません。Getには必要なタイミングでサービスを呼び出してくれう onInit() メソッドがあります。
Controllerが不要になれば、onClose() メソッドがジャストなタイミングでメモリから破棄してくれます。これにより、ビューとビジネスロジックを分離することができるのです。
GetxController 内に dispose() メソッドがあっても何も起こらないので記述しないでください。ControllerはWidgetではないので「dispose」できません。たとえばController内でStreamを使用していてそれを閉じたい場合は、以下のように onClose() メソッドにコードを記述してください。
``` dart
class Controller extends GetxController {
StreamController<User> user = StreamController<User>();
StreamController<String> name = StreamController<String>();
/// Streamを閉じる場合は dispose() ではなく onClose()
@override
void onClose() {
user.close();
name.close();
super.onClose();
}
}
```
Controllerのライフサイクルについて。
* onInit() はControllerが作成されたタイミングで実行されます。
* onClose() は onDelete() メソッドが実行される直前のタイミングで実行されます。
* Controllerが削除されるとそのAPIにアクセスすることはできません。文字通りメモリからの削除だからです。削除のトレースログも残りません。
### Controllerの様々な使用方法
ControllerインスタンスはGetBuilderのvalueを通じて使用することができます。
``` dart
GetBuilder<Controller>(
init: Controller(),
builder: (value) => Text(
'${value.counter}', // ここ
),
),
```
GetBuilderの外でControllerインスタンスを使う場合は、このアプローチをおすすめします。
``` dart
class Controller extends GetxController {
static Controller get to => Get.find();
[...]
}
// ビュー側で
GetBuilder<Controller>(
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Controller.to.counter}', // ここ
)
),
```
もしくは
``` dart
class Controller extends GetxController {
// static get を省き、
[...]
}
// ビュー側で
GetBuilder<Controller>(
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Get.find<Controller>().counter}', // ここ
),
),
```
* get_it や modular など他の依存オブジェクト管理ライブラリを使用しているため、単にControllerのインスタンスを渡したいだけの場合は、このような「非正規」な方法もあります。
``` dart
Controller controller = Controller();
[...]
GetBuilder<Controller>(
init: controller, // ここ
builder: (_) => Text(
'${controller.counter}', // ここ
),
),
```
### ユニークIDの設定
GetBuilderを使ってWidgetの更新をコントロールしたい場合は、このようにユニークIDを振ってください。
``` dart
GetBuilder<Controller>(
id: 'text'
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Get.find<Controller>().counter}', // ここ
),
),
```
そして以下のようにWidgetを更新します。
``` dart
update(['text']);
```
さらに更新に条件を設けることができます。
``` dart
update(['text'], counter < 10);
```
GetXはこの更新を自動で行ってくれます。指定したIDを持ち、その変数に依存するWidgetのみを更新します。また変数を前の値と同じ値に変更しても、それが状態の変化を意味しない場合はメモリとCPUサイクルを節約するためにWidgetを更新しません (画面に 3 が表示されているときに、変数を再び 3 に変更したとします。このような場合にWidgetを更新する状態管理ソリューションも存在しますが、GetXでは実際に状態が変更された場合にのみ更新されます)。
## 状態管理ソリューションを混在させる
MixinBuilderはObxとGetBuilderを併用したいというリクエストから発想して作られました。これは ".obs" 変数の変更によるリアクティブな更新と、update() メソッドによるメカニカルな更新の両方を混在可能にします。ただし、GetBuiler / GetX / Obx / MixinBuilder の4つの中で最もリソースを消費するWidgetです。というのも、Widgetからのイベントを検知するためのSubscriptionに加えて、Controller自身のupdateメソッドも購読する必要があるからです。
MixinBuilderに使用するControllerクラスには、変数を `.obs`(Observable)とするかどうかに関わらず、GetxControllerを継承したものを使用してください。GetxControllerにはライフサイクルがあり、onInit() および onClose() メソッドでイベントを「開始」したり「終了」したりすることができます。
## StateMixin
`StateMixin<T>` を使うことでさらに `UI` の「状態」を便利に扱うことができます。
`with` を使って `StateMixin<T>` をControllerにミックスインしてください。Tにはモデルのクラス名が入ります。
``` dart
class Controller extends GetController with StateMixin<User>{}
```
状態を変更するには `change()` メソッドを使ってください。
パラメーターにはビューに渡すデータと「状態」をセットします。
```dart
change(data, status: RxStatus.success());
```
RxStatus の「状態」は以下の4つです。
``` dart
RxStatus.loading(); // ロード中
RxStatus.success(); // ロード成功
RxStatus.empty(); // データが空
RxStatus.error('message'); // エラー
```
それぞれの「状態」をUIで表すには以下のようにします。
```dart
class OtherClass extends GetView<Controller> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: controller.obx(
(state)=>Text(state.name),
// ここはカスタムのロードインジケーターでも可能ですが、
// デフォルトは Center(child:CircularProgressIndicator())
onLoading: CustomLoadingIndicator(),
onEmpty: Text('No data found'),
// ここもカスタムのエラーWidgetでも構いませんが、
// デフォルトは Center(child:Text(error))
onError: (error)=>Text(error),
),
);
}
```
## GetBuilder VS GetX VS Obx VS MixinBuilder
私は10年間プログラミングに携わってきて、いくつか貴重な教訓を得ることができました。
リアクティブプログラミングに初めて触れたとき、「おお、これはすごい」と感嘆せずにはいられませんでしたし、実際にすごいものでした。
しかし、リアクティブプログラミングはすべての状況に適しているわけではありません。多くの場合、必要なのは2,3のWidgetの状態を同時に更新すること、またはローカルでの一時的な状態の変更であり、これらの場合はリアクティブである必要はありません。
リアクティブプログラミングのRAM消費量の多さは、必要なときだけ、かつ1つのWidgetだけ同時に更新するようすることである程度補うことができます。ただ、たとえば80ものオブジェクトを持つリストがあったとして、それぞれが複数のStreamを持つのは得策ではありません。Dartのインスペクターを開いて、StreamBuilderがどれだけRAMを消費しているか見てみてください。私が伝えたいことを理解してもらえると思います。
そのことを念頭に私はシンプルな状態管理ソリューションを作りました。このシンプルさに期待することは、リソース面で経済的である点、Widget単位ではなくブロック単位で状態を更新できる点であるべきです。
GetBuilderはRAM消費の面で最も経済的なソリューションだと信じています(もしあれば、ぜひ教えてください)。
しかし、GetBuilderは依然として update() により更新がかかるスタイルのメカニカルな状態管理ソリューションであり、notifyListeners() と呼び出し回数は変わりありません。
一方で、ここでリアクティブプログラミングを使わないのは車輪の再発明なんじゃないかと思えるような状況もあります。この点を考慮して、GetX() は先進的な状態管理の手法を提供するために作られました。必要なものを必要なときだけ更新し、エラーが発生してユーザーが300ものイベントを同時に送信したとしても、GetX() は状態の変化をフィルタリングして画面を更新してくれます。
GetX() は他のリアクティブな状態管理ソリューションに比べて経済的であることに変わりはありませんが、GetBuilder() よりは少しだけ多くのRAMを消費します。その点を考慮し、リソース消費を最大限活かすことを目指して Obx() は開発されました。GetX() や GetBuilder() と異なり、Obx() の中でControllerを初期化することはできません。Obx() は、子Widgetからの更新イベントを受け取る Stream購読Widgetでしかありません。GetX() よりは経済的ですが、GetBuilder() には負けます。GetBuilder() はWidgetのハッシュ値と状態のsetterを保持しているだけなので、これはある意味当然です。Obx() はControllerの型を指定する必要がなく、複数の異なるコントローラからの変更を聞くことができます。ただし、Obx() の外かBindingsで事前にControllerを初期化しておく必要があります。
... ...
... ... @@ -35,7 +35,7 @@ class CountryView extends GetView<HomeController> {
onTap: () {
//Get.rootDelegate.toNamed('/home/country');
Get.rootDelegate
.offNamed('/home/country/details?id=$index');
.toNamed('/home/country/details?id=$index');
},
trailing: CircleAvatar(
backgroundImage: NetworkImage(
... ...
... ... @@ -70,8 +70,10 @@ class HomeView extends GetView<HomeController> {
),
shape: StadiumBorder(),
),
onPressed: () {
Get.rootDelegate.toNamed('/home/country');
onPressed: () async {
final data =
await Get.rootDelegate.toNamed('/home/country');
print('DATA: $data');
},
child: Text(
'fetch_country'.tr,
... ...
... ... @@ -205,6 +205,7 @@ class GetHttpClient {
if (authenticate) await _modifier.authenticator!(request);
final newRequest = await _modifier.modifyRequest<T>(request);
_httpClient.timeout = timeout;
var response = await _httpClient.send<T>(newRequest);
final newResponse =
... ...
... ... @@ -23,6 +23,9 @@ class HttpRequestImpl implements HttpRequestBase {
///on different sites. The default is false
final bool withCredentials;
@override
Duration? timeout;
/// Sends an HTTP request and asynchronously returns the response.
@override
Future<Response<T>> send<T>(Request<T> request) async {
... ... @@ -30,6 +33,7 @@ class HttpRequestImpl implements HttpRequestBase {
html.HttpRequest xhr;
xhr = html.HttpRequest()
..timeout = timeout?.inMilliseconds
..open(request.method, '${request.url}', async: true); // check this
_xhrs.add(xhr);
... ...
... ... @@ -8,4 +8,12 @@ abstract class HttpRequestBase {
/// Closes the [Request] and cleans up any resources associated with it.
void close();
/// Gets and sets the timeout.
///
/// For mobile, this value will be applied for both connection and request
/// timeout.
///
/// For web, this value will be the request timeout.
Duration? timeout;
}
... ...
... ... @@ -34,16 +34,20 @@ class HttpRequestImpl extends HttpRequestBase {
@override
Future<Response<T>> send<T>(Request<T> request) async {
var stream = request.bodyBytes.asBroadcastStream();
io.HttpClientRequest? ioRequest;
try {
var ioRequest = (await _httpClient!.openUrl(request.method, request.url))
_httpClient!.connectionTimeout = timeout;
ioRequest = (await _httpClient!.openUrl(request.method, request.url))
..followRedirects = request.followRedirects
..persistentConnection = request.persistentConnection
..maxRedirects = request.maxRedirects
..contentLength = request.contentLength ?? -1;
request.headers.forEach(ioRequest.headers.set);
var response = await stream.pipe(ioRequest) as io.HttpClientResponse;
var response = timeout == null
? await stream.pipe(ioRequest) as io.HttpClientResponse
: await stream.pipe(ioRequest).timeout(timeout!)
as io.HttpClientResponse;
var headers = <String, String>{};
response.headers.forEach((key, values) {
... ... @@ -68,6 +72,9 @@ class HttpRequestImpl extends HttpRequestBase {
body: body,
bodyString: stringBody,
);
} on TimeoutException catch (_) {
ioRequest?.abort();
rethrow;
} on io.HttpException catch (error) {
throw GetHttpException(error.message, error.uri);
}
... ...
... ... @@ -75,39 +75,35 @@ class Request<T> {
);
}
Request copyWith({
Request<T> copyWith({
Uri? url,
String? method,
Map<String, String>? headers,
Stream<List<int>>? bodyBytes,
bool followRedirects = true,
int maxRedirects = 4,
bool? followRedirects,
int? maxRedirects,
int? contentLength,
FormData? files,
bool persistentConnection = true,
bool? persistentConnection,
Decoder<T>? decoder,
bool appendHeader = true,
}) {
if (followRedirects) {
assert(maxRedirects > 0);
}
// If appendHeader is set to true, we will merge origin headers with that
if (appendHeader && headers != null) {
headers.addAll(this.headers);
}
return Request._(
return Request<T>._(
url: url ?? this.url,
method: method ?? this.method,
bodyBytes: bodyBytes ??= BodyBytesStream.fromBytes(const []),
bodyBytes: bodyBytes ?? this.bodyBytes,
headers: headers == null ? this.headers : Map.from(headers),
followRedirects: followRedirects,
maxRedirects: maxRedirects,
contentLength: contentLength,
files: files,
persistentConnection: persistentConnection,
decoder: decoder,
followRedirects: followRedirects ?? this.followRedirects,
maxRedirects: maxRedirects ?? this.maxRedirects,
contentLength: contentLength ?? this.contentLength,
files: files ?? this.files,
persistentConnection: persistentConnection ?? this.persistentConnection,
decoder: decoder ?? this.decoder,
);
}
}
... ...
... ... @@ -72,7 +72,7 @@ class SocketNotifier {
if (_onEvents!.containsKey(event)) {
_onEvents![event]!(data);
}
} on Exception catch (_) {
} catch (_) {
return;
}
}
... ...
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'log.dart';
... ... @@ -9,6 +10,6 @@ abstract class GetInterface {
SmartManagement smartManagement = SmartManagement.full;
RouterDelegate? routerDelegate;
RouteInformationParser? routeInformationParser;
bool isLogEnable = true;
bool isLogEnable = kDebugMode;
LogWriterCallback log = defaultLogWriterCallback;
}
... ...
import 'dart:developer' as developer;
import 'get_main.dart';
///Voidcallback from logs
///VoidCallback from logs
typedef LogWriterCallback = void Function(String text, {bool isError});
/// default logger from GetX
... ...
... ... @@ -92,8 +92,8 @@ extension Inst on GetInterface {
/// Clears all registered instances (and/or tags).
/// Even the persistent ones.
///
/// - [clearFactory] clears the callbacks registered by `Get.lazyPut()`
/// - [clearRouteBindings] clears Instances associated with Routes when using
/// - `clearFactory` clears the callbacks registered by `Get.lazyPut()`
/// - `clearRouteBindings` clears Instances associated with Routes when using
/// [GetMaterialApp].
// bool reset(
// {@deprecated bool clearFactory = true,
... ... @@ -145,7 +145,7 @@ extension Inst on GetInterface {
}
/// Replaces a parent instance with a new Instance<P> lazily from the
/// [<P>builder()] callback.
/// `<P>builder()` callback.
/// - [tag] optional, if you use a [tag] to register the Instance.
/// - [fenix] optional
///
... ...
... ... @@ -161,18 +161,31 @@ class GetInstance {
bool fenix = false,
}) {
final key = _getKey(S, name);
_singl.putIfAbsent(
key,
() => _InstanceBuilderFactory<S>(
if (_singl.containsKey(key)) {
final dep = _singl[key];
if (dep != null && dep.isDirty) {
_singl[key] = _InstanceBuilderFactory<S>(
isSingleton,
builder,
permanent,
false,
fenix,
name,
lateRemove: dep as _InstanceBuilderFactory<S>,
);
}
} else {
_singl[key] = _InstanceBuilderFactory<S>(
isSingleton,
builder,
permanent,
false,
fenix,
name,
),
);
}
}
/// Initializes the dependencies for a Class Instance [S] (or tag),
/// If its a Controller, it starts the lifecycle process.
... ... @@ -222,6 +235,16 @@ class GetInstance {
}
}
void markAsDirty<S>({String? tag, String? key}) {
final newKey = key ?? _getKey(S, tag);
if (_singl.containsKey(newKey)) {
final dep = _singl[newKey];
if (dep != null) {
dep.isDirty = true;
}
}
}
/// Initializes the controller
S _startController<S>({String? tag}) {
final key = _getKey(S, tag);
... ... @@ -258,7 +281,8 @@ class GetInstance {
S find<S>({String? tag}) {
final key = _getKey(S, tag);
if (isRegistered<S>(tag: tag)) {
if (_singl[key] == null) {
final dep = _singl[key];
if (dep == null) {
if (tag == null) {
throw 'Class "$S" is not registered';
} else {
... ... @@ -266,11 +290,16 @@ class GetInstance {
}
}
// if (dep.lateRemove != null) {
// dep.isDirty = true;
// if(dep.fenix)
// }
/// although dirty solution, the lifecycle starts inside
/// `initDependencies`, so we have to return the instance from there
/// to make it compatible with `Get.create()`.
final i = _initDependencies<S>(name: tag);
return i ?? _singl[key]!.getDependency() as S;
return i ?? dep.getDependency() as S;
} else {
// ignore: lines_longer_than_80_chars
throw '"$S" not found. You need to call "Get.put($S())" or "Get.lazyPut(()=>$S())"';
... ... @@ -287,8 +316,8 @@ class GetInstance {
/// Even the persistent ones.
/// This should be used at the end or tearDown of unit tests.
///
/// [clearFactory] clears the callbacks registered by [lazyPut]
/// [clearRouteBindings] clears Instances associated with routes.
/// `clearFactory` clears the callbacks registered by [lazyPut]
/// `clearRouteBindings` clears Instances associated with routes.
///
bool resetInstance(
{@deprecated bool clearFactory = true, bool clearRouteBindings = true}) {
... ... @@ -324,7 +353,16 @@ class GetInstance {
return false;
}
final builder = _singl[newKey]!;
final dep = _singl[newKey];
if (dep == null) return false;
final _InstanceBuilderFactory builder;
if (dep.isDirty) {
builder = dep.lateRemove ?? dep;
} else {
builder = dep;
}
if (builder.permanent && !force) {
Get.log(
... ... @@ -348,6 +386,12 @@ class GetInstance {
if (builder.fenix) {
builder.dependency = null;
builder.isInit = false;
return true;
} else {
if (dep.lateRemove != null) {
dep.lateRemove = null;
Get.log('"$newKey" deleted from memory');
return false;
} else {
_singl.remove(newKey);
if (_singl.containsKey(newKey)) {
... ... @@ -355,19 +399,20 @@ class GetInstance {
} else {
Get.log('"$newKey" deleted from memory');
}
}
return true;
}
}
}
/// Delete all registered Class Instances and, closes any open
/// controllers `DisposableInterface`, cleans up the memory
///
/// - [force] Will delete the Instances even if marked as `permanent`.
void deleteAll({bool force = false}) {
_singl.forEach((key, value) {
final keys = _singl.keys.toList();
for (final key in keys) {
delete(key: key, force: force);
});
}
}
void reloadAll({bool force = false}) {
... ... @@ -382,11 +427,11 @@ class GetInstance {
});
}
void reload<S>(
{String? tag,
void reload<S>({
String? tag,
String? key,
bool force = false,
bool closeInstance = true}) {
}) {
final newKey = key ?? _getKey(S, tag);
final builder = _getDependency<S>(tag: tag, key: newKey);
... ... @@ -406,7 +451,7 @@ class GetInstance {
return;
}
if (i is GetLifeCycleBase && closeInstance) {
if (i is GetLifeCycleBase) {
i.onDelete();
Get.log('"$newKey" onDelete() called');
}
... ... @@ -467,6 +512,10 @@ class _InstanceBuilderFactory<S> {
bool isInit = false;
_InstanceBuilderFactory<S>? lateRemove;
bool isDirty = false;
String? tag;
_InstanceBuilderFactory(
... ... @@ -475,8 +524,9 @@ class _InstanceBuilderFactory<S> {
this.permanent,
this.isInit,
this.fenix,
this.tag,
);
this.tag, {
this.lateRemove,
});
void _showInitLog() {
if (tag == null) {
... ...
... ... @@ -1016,6 +1016,7 @@ you can only use widgets and widget functions here''';
/// `() => MyHomeScreenView` becomes `/my-home-screen-view`.
String _cleanRouteName(String name) {
name = name.replaceAll('() => ', '');
/// uncommonent for URL styling.
// name = name.paramCase!;
if (!name.startsWith('/')) {
... ... @@ -1054,9 +1055,9 @@ you can only use widgets and widget functions here''';
}
}
void updateLocale(Locale l) {
Future<void> updateLocale(Locale l) async {
Get.locale = l;
forceAppUpdate();
await forceAppUpdate();
}
/// As a rule, Flutter knows which widget to update,
... ... @@ -1072,8 +1073,8 @@ you can only use widgets and widget functions here''';
/// reconstruct the application from the sketch, use this with caution.
/// Your entire application will be rebuilt, and touch events will not
/// work until the end of rendering.
void forceAppUpdate() {
engine!.performReassemble();
Future<void> forceAppUpdate() async {
await engine!.performReassemble();
}
void appUpdate() => _getxController.update();
... ...
... ... @@ -14,7 +14,7 @@ class GetInformationParser extends RouteInformationParser<GetNavConfig> {
SynchronousFuture<GetNavConfig> parseRouteInformation(
RouteInformation routeInformation,
) {
print('GetInformationParser: route location: ${routeInformation.location}');
Get.log('GetInformationParser: route location: ${routeInformation.location}');
var location = routeInformation.location;
if (location == '/') {
//check if there is a corresponding page
... ...
... ... @@ -311,7 +311,7 @@ class GetDelegate extends RouterDelegate<GetNavConfig>
return route;
}
Future<void> toNamed(
Future<T> toNamed<T>(
String page, {
dynamic arguments,
Map<String, String>? parameters,
... ... @@ -324,6 +324,10 @@ class GetDelegate extends RouterDelegate<GetNavConfig>
final decoder = Get.routeTree.matchRoute(page, arguments: arguments);
decoder.replaceArguments(arguments);
final completer = Completer<T>();
if (decoder.route != null) {
_allCompleters[decoder.route!] = completer;
await pushHistory(
GetNavConfig(
currentTreeBranch: decoder.treeBranch,
... ... @@ -331,15 +335,39 @@ class GetDelegate extends RouterDelegate<GetNavConfig>
state: null, //TODO: persist state?
),
);
return completer.future;
} else {
///TODO: IMPLEMENT ROUTE NOT FOUND
return Future.value();
}
}
Future<T?>? offAndToNamed<T>(
String page, {
dynamic arguments,
int? id,
dynamic result,
Map<String, String>? parameters,
PopMode popMode = PopMode.History,
}) async {
if (parameters != null) {
final uri = Uri(path: page, queryParameters: parameters);
page = uri.toString();
}
Future<void> offNamed(
await popRoute(result: result);
return toNamed(page, arguments: arguments, parameters: parameters);
}
Future<T> offNamed<T>(
String page, {
dynamic arguments,
Map<String, String>? parameters,
}) async {
await toNamed(page, arguments: arguments, parameters: parameters);
await _unsafeHistoryRemoveAt(history.length - 2);
history.removeLast();
return toNamed<T>(page, arguments: arguments, parameters: parameters);
}
/// Removes routes according to [PopMode]
... ... @@ -392,6 +420,8 @@ class GetDelegate extends RouterDelegate<GetNavConfig>
return false;
}
final _allCompleters = <GetPage, Completer>{};
bool _onPopVisualRoute(Route<dynamic> route, dynamic result) {
final didPop = route.didPop(result);
if (!didPop) {
... ... @@ -406,23 +436,29 @@ class GetDelegate extends RouterDelegate<GetNavConfig>
if (config != null) {
_removeHistoryEntry(config);
}
if (_allCompleters.containsKey(settings)) {
_allCompleters[settings]?.complete(route.popped);
}
}
refresh();
return true;
}
}
class GetNavigator extends Navigator {
GetNavigator({
GlobalKey<NavigatorState>? key,
GetNavigator(
{GlobalKey<NavigatorState>? key,
bool Function(Route<dynamic>, dynamic)? onPopPage,
required List<Page> pages,
required List<GetPage> pages,
List<NavigatorObserver>? observers,
bool reportsRouteUpdateToEngine = false,
TransitionDelegate? transitionDelegate,
}) : super(
String? initialRoute})
: super(
//keys should be optional
key: key,
initialRoute: initialRoute ?? '/',
onPopPage: onPopPage ??
(route, result) {
final didPop = route.didPop(result);
... ... @@ -431,6 +467,17 @@ class GetNavigator extends Navigator {
}
return true;
},
onGenerateRoute: (RouteSettings settings) {
final selectedPageList =
pages.where((element) => element.name == settings.name);
if (selectedPageList.isNotEmpty) {
final selectedPage = selectedPageList.first;
return GetPageRoute(
page: selectedPage.page,
settings: settings,
);
}
},
reportsRouteUpdateToEngine: reportsRouteUpdateToEngine,
pages: pages,
observers: [
... ...
... ... @@ -81,12 +81,14 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, GetNavConfig> {
required String initialRoute,
Iterable<GetPage> Function(Iterable<GetPage> afterAnchor)? filterPages,
GlobalKey<NavigatorState>? key,
GetDelegate? delegate,
}) : this.pickPages(
pickPages: (config) {
Iterable<GetPage<dynamic>> ret;
if (anchorRoute == null) {
// jump the ancestor path
final length = Uri.parse(initialRoute).pathSegments.length;
return config.currentTreeBranch
.skip(length)
.take(length)
... ... @@ -102,6 +104,7 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, GetNavConfig> {
Get.routeTree.matchRoute(initialRoute).route ??
delegate.notFoundRoute,
key: key,
delegate: delegate,
);
GetRouterOutlet.pickPages({
Widget Function(GetDelegate delegate)? emptyWidget,
... ... @@ -109,6 +112,7 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, GetNavConfig> {
required Iterable<GetPage> Function(GetNavConfig currentNavStack) pickPages,
bool Function(Route<dynamic>, dynamic)? onPopPage,
GlobalKey<NavigatorState>? key,
GetDelegate? delegate,
}) : super(
pageBuilder: (context, rDelegate, pages) {
final pageRes = <GetPage?>[
... ... @@ -134,7 +138,7 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, GetNavConfig> {
return (emptyWidget?.call(rDelegate) ?? SizedBox.shrink());
},
pickPages: pickPages,
delegate: Get.rootDelegate,
delegate: delegate ?? Get.rootDelegate,
);
GetRouterOutlet.builder({
... ...
... ... @@ -52,7 +52,7 @@ class GetCupertinoApp extends StatelessWidget {
this.onReady,
this.getPages,
this.opaqueRoute,
this.enableLog,
this.enableLog = kDebugMode,
this.logWriterCallback,
this.popGesture,
this.transitionDuration,
... ... @@ -154,7 +154,7 @@ class GetCupertinoApp extends StatelessWidget {
this.onInit,
this.onReady,
this.onDispose,
this.enableLog,
this.enableLog = kDebugMode,
this.logWriterCallback,
this.popGesture,
this.smartManagement = SmartManagement.full,
... ...
... ... @@ -55,7 +55,7 @@ class GetMaterialApp extends StatelessWidget {
this.defaultTransition,
this.getPages,
this.opaqueRoute,
this.enableLog,
this.enableLog = kDebugMode,
this.logWriterCallback,
this.popGesture,
this.transitionDuration,
... ... @@ -170,7 +170,7 @@ class GetMaterialApp extends StatelessWidget {
this.onInit,
this.onReady,
this.onDispose,
this.enableLog,
this.enableLog = kDebugMode,
this.logWriterCallback,
this.popGesture,
this.smartManagement = SmartManagement.full,
... ... @@ -298,13 +298,15 @@ class GetMaterialApp extends StatelessWidget {
)
: MaterialApp(
key: _.unikey,
navigatorKey:
(navigatorKey == null ? Get.key : Get.addKey(navigatorKey!)),
navigatorKey: (navigatorKey == null
? Get.key
: Get.addKey(navigatorKey!)),
scaffoldMessengerKey: scaffoldMessengerKey,
home: home,
routes: routes ?? const <String, WidgetBuilder>{},
initialRoute: initialRoute,
onGenerateRoute: (getPages != null ? generator : onGenerateRoute),
onGenerateRoute:
(getPages != null ? generator : onGenerateRoute),
onGenerateInitialRoutes: (getPages == null || home != null)
? onGenerateInitialRoutes
: initialRoutesGenerate,
... ... @@ -339,5 +341,6 @@ class GetMaterialApp extends StatelessWidget {
shortcuts: shortcuts,
scrollBehavior: scrollBehavior,
// actions: actions,
));
),
);
}
... ...
... ... @@ -7,7 +7,7 @@ import '../../get.dart';
class RouterReportManager<T> {
/// Holds a reference to `Get.reference` when the Instance was
/// created to manage the memory.
static final Map<String, Route?> _routesKey = {};
static final Map<Route?, List<String>> _routesKey = {};
/// Stores the onClose() references of instances created with `Get.create()`
/// using the `Get.reference`.
... ... @@ -29,7 +29,12 @@ class RouterReportManager<T> {
/// Links a Class instance [S] (or [tag]) to the current route.
/// Requires usage of `GetMaterialApp`.
static void reportDependencyLinkedToRoute(String depedencyKey) {
_routesKey.putIfAbsent(depedencyKey, () => _current);
if (_current == null) return;
if (_routesKey.containsKey(_current)) {
_routesKey[_current!]!.add(depedencyKey);
} else {
_routesKey[_current] = <String>[depedencyKey];
}
}
static void clearRouteKeys() {
... ... @@ -46,9 +51,6 @@ class RouterReportManager<T> {
static void reportRouteDispose(Route disposed) {
if (Get.smartManagement != SmartManagement.onlyBuilder) {
WidgetsBinding.instance!.addPostFrameCallback((_) {
///TODO: Check if it's necessary to compare _current != disposed
///Adding it breaks the context Navigation logic,
///as it resolves by Route name.
_removeDependencyByRoute(disposed);
});
}
... ... @@ -56,11 +58,8 @@ class RouterReportManager<T> {
static void reportRouteWillDispose(Route disposed) {
final keysToRemove = <String>[];
_routesKey.forEach((key, value) {
if (value == disposed) {
keysToRemove.add(key);
}
});
_routesKey[disposed]?.forEach(keysToRemove.add);
/// Removes `Get.create()` instances registered in `routeName`.
if (_routesByCreate.containsKey(disposed)) {
... ... @@ -74,7 +73,8 @@ class RouterReportManager<T> {
}
for (final element in keysToRemove) {
GetInstance().reload(key: element, closeInstance: false);
GetInstance().markAsDirty(key: element);
//_routesKey.remove(element);
}
... ... @@ -87,11 +87,8 @@ class RouterReportManager<T> {
/// Meant for internal usage of `GetPageRoute` and `GetDialogRoute`
static void _removeDependencyByRoute(Route routeName) {
final keysToRemove = <String>[];
_routesKey.forEach((key, value) {
if (value == routeName) {
keysToRemove.add(key);
}
});
_routesKey[routeName]?.forEach(keysToRemove.add);
/// Removes `Get.create()` instances registered in `routeName`.
if (_routesByCreate.containsKey(routeName)) {
... ... @@ -105,8 +102,10 @@ class RouterReportManager<T> {
}
for (final element in keysToRemove) {
GetInstance().delete(key: element);
_routesKey.remove(element);
final value = GetInstance().delete(key: element);
if (value) {
_routesKey[routeName]?.remove(element);
}
}
keysToRemove.clear();
... ...
... ... @@ -7,7 +7,22 @@ import 'get_transition_mixin.dart';
import 'route_middleware.dart';
import 'transitions_type.dart';
class GetPageRoute<T> extends PageRoute<T> with GetPageRouteTransitionMixin<T> {
mixin PageRouteReportMixin<T> on Route<T> {
@override
void install() {
super.install();
RouterReportManager.reportCurrentRoute(this);
}
@override
void dispose() {
super.dispose();
RouterReportManager.reportRouteDispose(this);
}
}
class GetPageRoute<T> extends PageRoute<T>
with GetPageRouteTransitionMixin<T>, PageRouteReportMixin {
/// Creates a page route for use in an iOS designed app.
///
/// The [builder], [maintainState], and [fullscreenDialog] arguments must not
... ... @@ -35,9 +50,7 @@ class GetPageRoute<T> extends PageRoute<T> with GetPageRouteTransitionMixin<T> {
this.maintainState = true,
bool fullscreenDialog = false,
this.middlewares,
}) : super(settings: settings, fullscreenDialog: fullscreenDialog) {
RouterReportManager.reportCurrentRoute(this);
}
}) : super(settings: settings, fullscreenDialog: fullscreenDialog);
@override
final Duration transitionDuration;
... ... @@ -75,18 +88,14 @@ class GetPageRoute<T> extends PageRoute<T> with GetPageRouteTransitionMixin<T> {
@override
void dispose() {
super.dispose();
RouterReportManager.reportRouteDispose(this);
// if (Get.smartManagement != SmartManagement.onlyBuilder) {
// GetInstance().removeDependencyByRoute("$reference");
// }
final middlewareRunner = MiddlewareRunner(middlewares);
middlewareRunner.runOnPageDispose();
}
@override
Widget buildContent(BuildContext context) {
Widget? _child;
Widget _getChild() {
if (_child != null) return _child!;
final middlewareRunner = MiddlewareRunner(middlewares);
final bindingsToBind = middlewareRunner.runOnBindingsStart(bindings);
final _bindingList = [
... ... @@ -112,6 +121,11 @@ class GetPageRoute<T> extends PageRoute<T> with GetPageRouteTransitionMixin<T> {
}
@override
Widget buildContent(BuildContext context) {
return _getChild();
}
@override
final String? title;
@override
... ...
... ... @@ -89,6 +89,8 @@ class GetPage<T> extends Page<T> {
this.showCupertinoParallax = true,
this.preventDuplicates = true,
}) : path = _nameToRegex(name),
assert(name.startsWith('/'),
'It is necessary to start route name [$name] with a slash: /$name'),
super(
key: ValueKey(name),
name: name,
... ... @@ -172,13 +174,18 @@ class GetPage<T> extends Page<T> {
);
}
late Future<T?> popped;
@override
Route<T> createRoute(BuildContext context) {
// return GetPageRoute<T>(settings: this, page: page);
return PageRedirect(
final _page = PageRedirect(
route: this,
settings: this,
unknownRoute: unknownRoute,
).getPageToRoute<T>(this, unknownRoute);
popped = _page.popped;
return _page;
}
}
... ...
... ... @@ -112,12 +112,15 @@ class GetObserver extends NavigatorObserver {
if (route is PageRoute) {
value.current = newRoute.name ?? '';
}
final previousRouteName = _extractRouteName(previousRoute);
if (previousRouteName != null) {
value.previous = previousRouteName;
}
value.args = route.settings.arguments;
value.route = route;
value.isBack = false;
value.removed = '';
value.previous = _extractRouteName(previousRoute) ?? '';
value.isSnackbar = newRoute.isSnackbar ? true : value.isSnackbar ?? false;
value.isBottomSheet =
newRoute.isBottomSheet ? true : value.isBottomSheet ?? false;
... ... @@ -154,13 +157,15 @@ class GetObserver extends NavigatorObserver {
// Only PageRoute is allowed to change current value
if (previousRoute is PageRoute) {
value.current = _extractRouteName(previousRoute) ?? '';
value.previous = newRoute.name ?? '';
} else if (value.previous.isNotEmpty) {
value.current = value.previous;
}
value.args = route.settings.arguments;
value.args = previousRoute?.settings.arguments;
value.route = previousRoute;
value.isBack = true;
value.removed = '';
value.previous = newRoute.name ?? '';
value.isSnackbar = newRoute.isSnackbar;
value.isBottomSheet = newRoute.isBottomSheet;
value.isDialog = newRoute.isDialog;
... ... @@ -181,8 +186,8 @@ class GetObserver extends NavigatorObserver {
Get.log("REPLACE ROUTE $oldName");
Get.log("NEW ROUTE $newName");
if (oldRoute != null) {
RouterReportManager.reportCurrentRoute(oldRoute);
if (newRoute != null) {
RouterReportManager.reportCurrentRoute(newRoute);
}
_routeSend?.update((value) {
... ...
... ... @@ -111,6 +111,24 @@ mixin RxObjectMixin<T> on NotifyManager<T> {
Stream<T> get stream => subject.stream;
/// Returns a [StreamSubscription] similar to [listen], but with the
/// added benefit that it primes the stream with the current [value], rather
/// than waiting for the next [value]. This should not be called in [onInit]
/// or anywhere else during the build process.
StreamSubscription<T> listenAndPump(void Function(T event) onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
final subscription = listen(
onData,
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
subject.add(value);
return subscription;
}
/// Binds an existing `Stream<T>` to this Rx<T> to keep the values in sync.
/// You can bind multiple sources to update the value.
/// Closing the subscription will happen automatically when the observer
... ... @@ -365,6 +383,6 @@ extension BoolExtension on bool {
}
extension RxT<T> on T {
/// Returns a `Rx` instace with [this] `T` as initial value.
/// Returns a `Rx` instance with [this] `T` as initial value.
Rx<T> get obs => Rx<T>(this);
}
... ...
... ... @@ -73,6 +73,18 @@ class RxList<E> extends ListMixin<E>
}
@override
void removeWhere(bool test(E element)) {
_value.removeWhere(test);
refresh();
}
@override
void retainWhere(bool test(E element)) {
_value.retainWhere(test);
refresh();
}
@override
int get length => value.length;
@override
... ... @@ -127,7 +139,7 @@ extension ListExtension<E> on List<E> {
// if (item != null) addAll(item);
// }
/// Add [item] to [List<E>] only if [condition] is true.
/// Add [item] to List<E> only if [condition] is true.
void addIf(dynamic condition, E item) {
if (condition is Condition) condition = condition();
if (condition is bool && condition) add(item);
... ...
import '../get_utils/get_utils.dart';
extension GetDynamicUtils<T> on T {
extension GetDynamicUtils on dynamic {
@Deprecated('isNull is deprecated and cannot be used, use "==" operator')
bool get isNull => GetUtils.isNull(this);
... ...
... ... @@ -583,7 +583,8 @@ class GetUtils {
return null;
}
return _groupIntoWords(text!)
.map((word) => word.toLowerCase()).join(separator);
.map((word) => word.toLowerCase())
.join(separator);
}
/// param-case
... ...
name: get
description: Open screens/snackbars/dialogs without context, manage states and inject dependencies easily with GetX.
version: 4.3.4
version: 4.3.8
homepage: https://github.com/jonataslaw/getx
environment:
... ...
... ... @@ -162,4 +162,31 @@ void main() {
expect(reactiveString.endsWith("c"), true);
expect(currentString, "abc");
});
test('Number of times "ever" is called in RxList', () async {
final list = [1, 2, 3].obs;
var count = 0;
ever<List<int>>(list, (value) {
count++;
});
list.add(4);
await Future.delayed(Duration.zero);
expect(count, 1);
count = 0;
list.addAll([4, 5]);
await Future.delayed(Duration.zero);
expect(count, 1);
count = 0;
list.removeWhere((element) => element == 2);
await Future.delayed(Duration.zero);
expect(count, 1);
count = 0;
list.retainWhere((element) => element == 1);
await Future.delayed(Duration.zero);
expect(count, 1);
});
}
... ...