sukesukejijii

Japanese translation - first draft

... ... @@ -17,21 +17,21 @@
<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)
[![Japanese](https://img.shields.io/badge/Language-Japanese-blueviolet?style=for-the-badge)](README-ja.md)
**言語**
[![英語](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>
... ... @@ -40,70 +40,75 @@
- [GetXによるカウンターアプリ](#GetXによるカウンターアプリ)
- [三本柱](#三本柱)
- [状態管理](#状態管理)
- [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)
- [Locales](#locales)
- [Change locale](#change-locale)
- [System locale](#system-locale)
- [Change Theme](#change-theme)
- [リアクティブな状態管理](#リアクティブな状態管理)
- [状態管理に関する詳細ドキュメント](#状態管理に関する詳細ドキュメント)
- [Route管理](#Route管理)
- [Route管理に関する詳細ドキュメント](#Route管理に関する詳細ドキュメント)
- [依存オブジェクト管理](#依存オブジェクト管理)
- [依存オブジェクト管理に関する詳細ドキュメント](#依存オブジェクト管理に関する詳細ドキュメント)
- [ユーティリティ](#ユーティリティ)
- [多言語対応](#多言語対応)
- [翻訳ファイル](#翻訳ファイル)
- [翻訳ファイルの利用](#翻訳ファイルの利用)
- [ロケール](#ロケール)
- [ロケールの変更](#ロケールの変更)
- [システムのロケールを読み込む](#システムのロケールを読み込む)
- [Themeの変更](#Themeの変更)
- [GetConnect](#getconnect)
- [Default configuration](#default-configuration)
- [Custom configuration](#custom-configuration)
- [GetPage Middleware](#getpage-middleware)
- [Priority](#priority)
- [Redirect](#redirect)
- [デフォルト設定](#デフォルト設定)
- [カスタム設定](#カスタム設定)
- [GetPageにミドルウェアを設定](#GetPageにミドルウェアを設定)
- [実行優先度](#実行優先度)
- [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)
- [onBindingsStart](#onbindingsstart)
- [onPageBuildStart](#onpagebuildstart)
- [onPageBuilt](#onpagebuilt)
- [onPageDispose](#onpagedispose)
- [その他API](#その他API)
- [オプションのグローバル設定と手動設定](#オプションのグローバル設定と手動設定)
- [ローカルステートWidget](#ローカルステートWidget)
- [ValueBuilder](#valuebuilder)
- [ObxValue](#obxvalue)
- [Useful tips](#useful-tips)
- [お役立ちTIPS](#お役立ちTIPS)
- [StateMixin](#statemixin)
- [GetView](#getview)
- [GetResponsiveView](#getresponsiveview)
- [How to use it](#how-to-use-it)
- [使い方](#使い方])
- [GetWidget](#getwidget)
- [GetxService](#getxservice)
- [Breaking changes from 2.0](#breaking-changes-from-20)
- [テストの実行](#テストの実行)
- [mockitoやmocktailを使う場合](#mockitoやmocktailを使う場合)
- [Get.reset()](#Get.reset())
- [Get.testMode](#Get.testMode)
- [バージョン2.0からの破壊的変更](#バージョン2.0からの破壊的変更)
- [なぜGetXなのか](#なぜGetXなのか)
- [コミュニティ](#コミュニティ)
- [コミュニティチャンネル](#コミュニティチャンネル)
- [貢献方法](#貢献方法)
- [GetXに関する記事とビデオ](#GetXに関する記事とビデオ)
- [コントリビュート方法](#コントリビュート方法)
- [GetXに関する記事と動画](#GetXに関する記事と動画)
# Getとは
- GetXはFlutterのための超軽量でパワフルなソリューションです。高パフォーマンスな状態管理、インテリジェントな依存性注入、そしてRoute管理の三本柱を迅速かつ実用的な形で組み合わせています。
- GetXはFlutterのための超軽量でパワフルなソリューションです。高パフォーマンスな状態管理機能、インテリジェントな依存オブジェクト管理機能、そしてRoute管理機能の三本柱を軽量かつ実用的な形で組み合わせています。
- GetXは3つの基本原則を元に開発されています。 **【生産性、パフォーマンス、コードの分離性】** これらはライブラリ内のすべてのリソースに優先適用される項目です。
- GetXは3つの基本原則を念頭に開発されています。 **【生産性、パフォーマンス、コードの分離性】** これらはライブラリ内のすべてのリソースに優先適用されている原則です。
- **パフォーマンス:** GetXは高いパフォーマンスと最小限のリソース消費を優先しています。GetXはStreamや ChangeNotifierを使用しません。
- **パフォーマンス:** GetXは高いパフォーマンスと最小限のリソース消費を目標にしています。GetXはでは Stream および ChangeNotifier を利用しなくて済みます。
- **生産性:** GetXはシンプルで使い心地のいい構文を採用しています。あなたの実現したい機能がどんなものであれ、GetXを使えばより簡単に実現できる方法が見つかるでしょう。開発にかかる時間を短縮し、あなたのアプリケーションのパフォーマンスを最大限引き出してくれます。
- **生産性:** GetXはシンプルで使い心地のいいシンタックスを採用しています。あなたの実現したい機能がどんなものであれ、GetXを使えばより簡単に実現できる方法が見つかるでしょう。開発にかかる時間を短縮し、あなたのアプリケーションのパフォーマンスを最大限引き出してくれます。
開発者はcontrollerなどのリソースをメモリから削除することに気を配るのが常です。しかしGetXでは、リソースが使用されていないときはメモリから削除されるのがデフォルト動作のため、この必要はありません。(逆にメモリに残しておきたい場合は、依存オブジェクトのパラメーターで「permanent: true」と明示的に宣言します)これにより時間が節約できますし、不要な依存オブジェクトがメモリ上に残るリスクも少なくなります。メモリへの読み込みについてもデフォルトは遅延読み込みであり、使用するときに初めてメモリ上に読み込まれます。
開発者はメモリリソースの管理に気を配るのが常です。しかしGetXでは、リソースが使用されていないときはメモリから削除されるのがデフォルト動作のため、過度に気にかける必要はありません。(逆にメモリに残しておきたい場合は、依存オブジェクトをインスタンス化するメソッドを使う際に「permanent: true」と宣言してください)これにより時間が節約できますし、不要な依存オブジェクトがメモリ上に残るリスクも少なくなります。メモリへの読み込みについてもデフォルトは遅延読み込みであり、使用するときに初めてメモリ上に読み込まれます。
- **コードの分離性:** GetXでは、View、プレゼンテーションロジック、ビジネスロジック、依存性注入、およびナビゲーション周りのコードを徹底して分離することができます。Route間のナビゲーションではcontextを必要としないため、Widgetツリーに依存することはありません。ロジックについてもInheritedWidget経由でcontroller/BLoCにアクセスするためのcontextは必要ありません。これによりプレゼンテーションロジックとビジネスロジックをUIレイヤーから完全に切り離すことができます。また、controller/model/BLoCのクラスを、`MultiProvider`を使ってWidgetツリーに注入する必要もありません。GetXでは独自の依存性注入機能を使用して、依存性注入とViewに関わるコードを完全に分離することができます。
- **コードの分離性:** GetXを使うと、ビュー、プレゼンテーションロジック、ビジネスロジック、依存オブジェクトの注入、およびナビゲーション周りのコードを書き分けやすくなります。Routeのナビゲーションにはcontextを必要としないため、Widgetツリーに依存することはありません。ロジックについてもInheritedWidget経由でController/BLoCにアクセスする際のcontextは必要ありません。プレゼンテーションロジックとビジネスロジックをUIクラスから完全に切り離すことができます。また、Controller/モデル/BLoCのクラスを、`MultiProvider`を使ってWidgetツリーに注入する必要もありません。GetXでは独自の依存オブジェクト注入機能を使用し、ビュークラスからビューとは無関係なコードをなくすことができるのです。
GetXを使うことでアプリケーションの各機能がどこに記載されているのかがわかりやすくなり、自然と見やすいコードになります。メンテナンスが容易になるだけでなく、それまでのFlutterでは考えられなかったモジュール共有が簡単に実現できるようになりました。
BLoCはその分野におけるFlutterの出発点でしたが、GetXはこれを正統進化させたもので、ビジネスロジックのみならずプレゼンテーションロジックも分離することができます。そのほか依存オブジェクトやRouteの注入も分離し、データレイヤーはこれらすべてから切り離されます。どこに何が配置されているのか構造がわかりやすくなり、Hello Worldを表示するよりも簡単に機能を利用できるようになるでしょう。
GetXはFlutter製の高性能アプリを作るために採用できる最も簡単で実用的、かつスケーラブルなソリューションです。強力なエコシステムも存在し、初心者にはわかりやすさ、プロフェッショナルには正確性を約束します。セキュアで安定的、かつFlutter/Dartの最新事情をいち早く反映し、Flutter SDKにはない幅広い種類のAPIを提供します。
GetXを使うことでアプリケーションの各機能がどこにあるのかがわかりやすくなり、自然と見やすいコードになります。メンテナンスが容易になるだけでなく、それまでのFlutterでは考えられなかったモジュール共有が簡単に実現できるようになりました。
BLoCはこの分野におけるFlutterの出発点と言えるものでしたが、GetXはこれを正統進化させており、ビジネスロジックのみならずプレゼンテーションロジックも分離することができます。そのほかデータレイヤーはもちろん、依存オブジェクトやRouteの注入に関するコードも。どこに何が配置されているのか全体の見通しがしやすくなり、Hello Worldを表示させるかのように簡単にアプリの機能を利用できるようになるでしょう。
Flutterアプリを作るならGetXは最も簡単で実用的、かつスケーラブルなソリューションです。強力なエコシステムも存在があるため、初心者にはわかりやすさ、プロには正確性を提供することができます。そしてFlutter SDKにはない幅広い種類のAPIを提供し、セキュアで安定的な環境を構築します。
- GetXは肥大化したライブラリではありません。何も気にせずすぐにプログラミングを始められるよう多数の機能を標準で備えていますが、それぞれの機能は個別にコンテナに入っており、使用してはじめて起動します。状態管理機能しか利用していない場合はその機能だけがコンパイルされます。Route管理機能だけを利用している場合は、状態管理機能は何もコンパイルされません。
- GetXは肥大化したライブラリではありません。何も気にせずすぐに開発を始められるよう多数の機能を標準で備えていますが、それぞれの機能は個別にコンテナに入っており、使用してはじめて起動します。状態管理機能しか利用していない場合はその機能だけがコンパイルされます。Route管理機能だけを利用していれば、状態管理機能がコンパイルされることはありません。
- GetXには大きなエコシステム、コミュニティ、コラボレーターの存在があるため、Flutterが存在する限りメンテナンスされ続けます。GetXもFlutterと同様にAndroid、iOS、Web、Mac、Linux、Windows、そしてあなたのサーバー上で、一つのコードから実行することができます。
- GetXには巨大なエコシステム、コミュニティ、コラボレーターの存在があるため、Flutterが存在する限りメンテナンスされ続けます。またGetXもFlutterと同様にAndroid、iOS、Web、Mac、Linux、Windows、そしてあなたのサーバー上で、単一のコードから実行することができます。
**[Get Server](https://github.com/jonataslaw/get_server)を使うことで、フロントエンドで作成したコードをバックエンドで再利用することが可能です。**
... ... @@ -137,7 +142,7 @@ Flutter縺ァ譁ー隕上繝ュ繧ク繧ァ繧ッ繝医r菴懈縺吶k髫帙↓陦ィ遉コ縺輔l繧九き繧ヲ繝ウ
void main() => runApp(GetMaterialApp(home: Home()));
```
- 注1: GetMaterialAppはFlutterのMaterialAppに手を加えたものではありません。MaterialAppをchildに持ち、諸々の追加設定をしてくれるWidgetに過ぎません。この設定は手動でも可能ですが、その必要はありません。GetMaterialAppは、Routeの作成・注入、言語翻訳の注入など、ナビゲーションに必要なものをすべて注入してくれます。Getを状態管理や依存性注入に限定して使用する場合は、GetMaterialAppを使用する必要はありません。GetMaterialAppは、Route、SnackBar、多言語対応、BottomSheet、Dialog、contextなしの高レベルAPIを利用する場合に必要です。
- 注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:
... ... @@ -152,7 +157,7 @@ class Controller extends GetxController{
```
- ステップ3:
Viewを作成します。StatelessWidgetを使用することでRAMが節約できます。GetではStatefulWidgetを使用する必要がなくなるかもしれません。
ビューを作成します。StatelessWidgetを使用することでRAMが節約できます。GetではStatefulWidgetを使用する必要がなくなるかもしれません。
```dart
class Home extends StatelessWidget {
... ... @@ -160,7 +165,7 @@ class Home extends StatelessWidget {
@override
Widget build(context) {
// Get.put()を使ってクラスをインスタンス化することですべての「子」Routeで利用ができます。
// Get.put()を使ってクラスをインスタンス化することですべての子Routeで利用できるようになります。
final Controller c = Get.put(Controller());
return Scaffold(
... ... @@ -201,16 +206,16 @@ Get縺ッ繝√繝縺ァ縺ョ菴懈・ュ繧呈Φ螳壹@縺ヲ險ュ險医&繧後※縺∪縺吶′縲∝倶ココ髢
## 状態管理
Getには、シンプルな手法(GetBuilder)と、リアクティブな手法(GetX/Obx)の2種類の状態管理手法があります。
Getの状態管理には、非リアクティブ(GetBuilder)と、リアクティブ(GetX/Obx)の2つのアプローチがあります。
### リアクティブな状態管理
リアクティブプログラミングは複雑であると言われ、多くの人に敬遠されています。GetXは、リアクティブプログラミングをシンプルなものに変えます:
- StreamControllerを作る必要がありません。
- 変数の数だけStreamBuilderを準備する必要がありません。
- 状態ごとにクラスを作成する必要がありません。
- 最初の値に対してgetを作成する必要がありません。
* StreamControllerを作る必要はありません。
* 変数ごとにStreamBuilderをセットする必要はありません。
* 状態ごとにクラスを作る必要はありません。
* 初期値のためにgetを準備する必要はありません。
- コードの自動生成をする必要がありません。
GetにおけるリアクティブプログラミングはsetStateと同じように簡単です。
... ... @@ -221,7 +226,7 @@ Get縺ォ縺翫¢繧九Μ繧「繧ッ繝ぅ繝悶繝ュ繧ー繝ゥ繝溘Φ繧ー縺ッsetState縺ィ蜷後§繧医≧
var name = 'Jonatas Borges';
```
このnameを監視可能にするには, ".obs"を値の末尾に付けるだけです。
このnameをObservable(監視可能)にするには, ".obs"を値の末尾に付けるだけです。
```dart
var name = 'Jonatas Borges'.obs;
... ... @@ -235,9 +240,9 @@ Obx(() => Text("${controller.name}"));
以上です。こんなに簡単なんですよ。
### 状態管理についての詳細
### 状態管理に関する詳細ドキュメント
**状態管理のより詳細な説明を知りたい方は[こちら](./documentation/ja_JP/state_management.md)をご覧ください。より多くの例や、普通の状態管理とリアクティブな状態管理の違いについても説明されています。**
**状態管理に関するより詳細な説明を知りたい方は[こちらの日本語ドキュメント](./documentation/ja_JP/state_management.md)をご覧ください。多くの事例や、非リアクティブな状態管理とリアクティブな状態管理の違いについても説明されています。**
GetXパワーがもたらす利点をより理解していただけると思います。
... ... @@ -253,13 +258,13 @@ GetMaterialApp( // MaterialApp 縺ョ蜑阪↓ Get
)
```
新しいRouteに画面遷移するにはこの構文。
新しいRouteに画面遷移するにはこのシンタックス。
```dart
Get.to(NextScreen());
```
名前付きRouteに画面遷移するにはこの構文。名前付きRouteの詳細は[こちら](./documentation/ja_JP/route_management.md#navigation-with-named-routes)
名前付きRouteに画面遷移するにはこのシンタックス。名前付きRouteの詳細は[こちらの日本語ドキュメント](./documentation/ja_JP/route_management.md#navigation-with-named-routes)
```dart
Get.toNamed('/details');
... ... @@ -285,29 +290,29 @@ Get.offAll(NextScreen());
以上、contextを一度も使わなかったことに気付きましたか?これがGetでRoute管理を行う最大のメリットのひとつです。contextを使わないので、たとえばcontrollerクラスの中でも、これらのメソッドを実行することができます。
### Route管理についての詳細
### Route管理に関する詳細ドキュメント
**Getは名前付きRouteでも動作し、Routeの下位レベルの制御も可能です。詳細なドキュメントは[こちら](./documentation/ja_JP/route_management.md)にあります。**
**Getは名前付きRouteでも動作し、Routeの下位レベルの制御も可能です。詳細なドキュメントは[こちらの日本語ドキュメント](./documentation/ja_JP/route_management.md)にあります。**
## 依存性注入の管理
## 依存オブジェクト管理
Getにはシンプルで強力な依存性注入機能があります。わずか1行のコードで、Provider contextやinheritedWidgetも使わず、BLoCやControllerのようなクラスのインスタンスを取得することができます。
Getにはシンプルで強力な依存オブジェクト注入機能があります。わずか1行のコードで、Provider contextやinheritedWidgetも使わず、BLoCやControllerのようなクラスのインスタンスを取得することができます。
```dart
Controller controller = Get.put(Controller()); // controller = Controller() とする代わりに
```
- 注: Getの状態管理機能を使用している場合は、Bindings APIにもご注目を。BindingsはViewとControllerを結びつけるのをより便利にしてくれます。
- 注: Getの状態管理機能を使用している場合は、Bindings APIにもご注目を。BindingsはビューとControllerを結びつけるのをより便利にしてくれます。
一つのクラスの中でControllerクラスをインスタンス化するのではなく、Getインスタンスの中でインスタンス化することで、アプリ全体でControllerが利用できるようになります。
**ヒント:** Getの依存性注入機能の部分は、パッケージ全体の中でも他の部分と切り離されているので、たとえば、あなたのアプリがすでに状態管理機能を一部で使用していたとしても、それらを書き直す必要はなく、この依存性注入機能をそのまま使用することができます。
**ヒント:** Getの依存オブジェクト注入機能の部分は、パッケージ全体の中でも他の部分と切り離されているので、たとえば、あなたのアプリがすでに状態管理機能を一部で使用していたとしても、それらを書き直す必要はなく、この依存オブジェクト注入機能をそのまま使用することができます。
```dart
controller.fetchApi();
```
色々なRouteを行き来した後に、あるControllerクラスのデータにアクセスする必要が生じたとしましょう。ProviderやGet_itなら再びそのクラスに依存性注入する必要がありますよね?Getの場合は違います。Getでは「find」と依頼するだけで、追加の依存性注入は必要ありません。
色々なRouteを行き来した後に、あるControllerクラスのデータにアクセスする必要が生じたとしましょう。ProviderやGet_itなら再びそのクラスに依存オブジェクトを注入する必要がありますよね?Getの場合は違います。Getでは「find」と依頼するだけで、追加の依存オブジェクトの注入は必要ありません。
```dart
Controller controller = Get.find();
... ... @@ -320,15 +325,15 @@ Controller controller = Get.find();
Text(controller.textFromApi);
```
### 依存性注入の管理についての詳細
### 依存オブジェクト管理に関する詳細ドキュメント
**依存性注入管理のより詳細な説明は[こちら](./documentation/ja_JP/dependency_management.md)をご覧ください。**
**依存オブジェクト管理に関するより詳細な説明は[こちらの日本語ドキュメント](./documentation/ja_JP/dependency_management.md)をご覧ください。**
# ユーティリティ
## 多言語対応
### 翻訳
### 翻訳ファイル
翻訳ファイルはシンプルなキーと値のMapとして保持されます。
翻訳を追加するには、クラスを作成して `Translations` を継承します。
... ... @@ -349,7 +354,7 @@ class Messages extends Translations {
}
```
#### 翻訳の利用
#### 翻訳ファイルの利用
指定されたキーに `.tr` (translateのtr)を追加するだけで、`Get.locale` と `Get.fallbackLocale` の現在の値をに沿って適切な言語に翻訳されます。
... ... @@ -406,7 +411,7 @@ var locale = Locale('en', 'US');
Get.updateLocale(locale);
```
#### システムロケール
#### システムのロケールを読み込む
システムのロケールを読み込むには、`Get.deviceLocale`を使用します。
... ... @@ -513,13 +518,13 @@ class HomeProvider extends GetConnect {
}
```
## GetPageのミドルウェア
## GetPageにミドルウェアを設定
GetPageに新しいプロパティが追加され、GetMiddleWareのListを設定することができるようになりました。GetMiddleWareは設定した任意の順序で実行されます。
**注**: GetPageにMiddlewareを設定すると、そのページの下にあるchildはすべて同じMiddlewareを自動的に持つことになります。
**注**: GetPageにミドルウェアを設定すると、そのページの子ページはすべて同じミドルウェアを自動的に持つことになります。
### 実行順
### 実行優先度
GetMiddlewareに設定したpriority(優先度)の若い順にミドルウェアが実行されます。
... ... @@ -574,7 +579,7 @@ List<Bindings> onBindingsStart(List<Bindings> bindings) {
### onPageBuildStart
onPageBuildStart関数は、Bindingsが初期化された直後、ページWidetが作成される前に実行されます。
onPageBuildStart関数は、Bindingsが初期化された直後、ページWidgetが作成され前に実行されます。
```dart
GetPageBuilder onPageBuildStart(GetPageBuilder page) {
... ... @@ -589,7 +594,7 @@ onPageBuilt髢「謨ー縺ッ縲;etPage.page(繝壹繧ク縺ョ繝薙Ν繝繝シ)縺悟他縺ウ蜃コ縺輔l
### onPageDispose
onPageDispose関数は、ページに関するすべてのオブジェクト(Controller、Viewなど)が破棄された直後に実行されます。
onPageDispose関数は、ページに関するすべてのオブジェクト(Controller、ビューなど)が破棄された直後に実行されます
## その他API
... ... @@ -764,7 +769,7 @@ Get.config(
```
オプションで、すべてのログメッセージを `Get` からリダイレクトさせることができます。
好きなロギングのパッケージを使ってログを取得したい場合はこのようにしてください。
お好みのロギングパッケージを使ってログを取得したい場合はこのようにしてください。
```dart
GetMaterialApp(
... ... @@ -782,24 +787,22 @@ void localLogWriter(String text, {bool isError = false}) {
### ローカルステートWidget
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`.
ローカルステートWidgetは、1つの変数の状態を一時的かつローカルに管理したい場合に便利です。
シンプルなValueBuilderとリアクティブなObxValueの2種類があります。
たとえば、`TextField` Widgetの obscureText プロパティを切り替えたり、折りたたみ可能なパネルをカスタムで作成したり、`BottomNavigation` の現在のインデックス値を変更して内容を変更したりといった用途に最適です。
#### ValueBuilder
A simplification of `StatefulWidget` that works with a `.setState` callback that takes the updated value.
setStateでお馴染みの `StatefulWidget` をシンプルにしたビルダーWidgetです。
```dart
ValueBuilder<bool>(
initialValue: false,
builder: (value, updateFn) => Switch(
value: value,
onChanged: updateFn, // same signature! you could use ( newValue ) => updateFn( newValue )
onChanged: updateFn, // ( newValue ) => updateFn( newValue ) も可
),
// if you need to call something outside the builder method.
// builderメソッドの外で何か実行する場合
onUpdate: (value) => print("Value updated: $value"),
onDispose: () => print("Widget unmounted"),
),
... ... @@ -807,96 +810,97 @@ ValueBuilder<bool>(
#### 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?
[`ValueBuilder`](#valuebuilder)に似ていますが、これはそのリアクティブバージョンです。Rxインスタンス(.obsを付けたときに戻る値です)を渡すと自動で更新されます。すごいでしょ?
```dart
ObxValue((data) => Switch(
value: data.value,
onChanged: data, // Rx has a _callable_ function! You could use (flag) => data.value = flag,
onChanged: data,
// Rxには_呼び出し可能な_関数が備わっているのでこれだけでOK
// (flag) => data.value = flag も可能
),
false.obs,
),
```
## Useful tips
## お役立ちTIPS
`.obs`ervables (also known as _Rx_ Types) have a wide variety of internal methods and operators.
`.obs`が付いた型(_Rx_型とも呼ばれる)には、さまざまな内部メソッドや演算子が用意されています。
> 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:
> `.obs`が付いたプロパティが **実際の値** だと信じてしまいがちですが...間違えないように!
> 我々がcontrollerにおける変数の型宣言を省略してvarとしているのはDartのコンパイラが賢い上に、
> そのほうがコードがすっきる見えるからですが…
```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**!
`message`を _print_ することで実際の文字列が取り出されはしますが、型は **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...
そのため `message.substring( 0, 4 )` などといったことはできません。
Stringのメソッドにアクセスするには _observable_ の中にある実際の値 `value` にアクセスします。
アクセスには `.value`を使うのが通常ですが、他の方法もあるのでご紹介します。
```dart
final name = 'GetX'.obs;
// only "updates" the stream, if the value is different from the current one.
// 新しい値が現在のものと異なる場合のみ Stream が更新されます。
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.
// すべてのRxプロパティは「呼び出し可能」で、valueを返してくれます。
// ただし `null` は受付不可。nullの場合はUIが更新されない。
name('Hello');
// is like a getter, prints 'Hello'.
// これはgetterみたいなものです。'Hello' を返します。
name() ;
/// numbers:
/// num型の場合
final count = 0.obs;
// You can use all non mutable operations from num primitives!
// num型の非破壊的な演算子はすべて使えます。
count + 1;
// Watch out! this is only valid if `count` is not final, but var
// 注意! この場合は`count`がfinalなら有効ではないです。varなら有効。
count += 1;
// You can also compare against values:
// 比較演算子も使用可能
count > 2;
/// booleans:
/// bool型の場合
final flag = false.obs;
// switches the value between true/false
// true/false を入れ替えることができます。
flag.toggle();
/// all types:
/// すべての型
// Sets the `value` to null.
// `value` を null にセット。
flag.nil();
// All toString(), toJson() operations are passed down to the `value`
print( count ); // calls `toString()` inside for RxInt
// toString(), toJson() などの操作はすべて `value` が対象になります。
print( count ); // RxIntの `toString()` が呼び出されて数字がprintされる。
final abc = [0,1,2].obs;
// Converts the value to a json Array, prints RxList
// Json is supported by all Rx types!
// json配列に変換した値と、'RxList' がprintされます。
// JsonはすべてのRx型でサポートされています!
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.
// RxMap、RxList、RxSetはそれぞれの元の型を拡張した特別なRx型です。
// たとえばRxListは通常のListとして扱うことができる上にリアクティブです。
abc.add(12); // 12をListにプッシュし、Streamを更新してくれます。
abc[3]; // Listと同様にインデックス番号3の値を取得してくれます。
// equality works with the Rx and the value, but hashCode is always taken from the value
// 等価演算子はRx型と元の型でも動作しますが、.hashCode は常にvalueから取得します。
final number = 12.obs;
print( number == 12 ); // prints > true
print( number == 12 ); // true
/// Custom Rx Models:
/// カスタムのRxモデル
// toJson(), toString() are deferred to the child, so you can implement override on them, and print() the observable directly.
// toJson()やtoString()をモデルクラスに設定すれば、.obsからでもprintされるように実装可能。
class User {
String name, last;
... ... @@ -909,39 +913,37 @@ class User {
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` 自体はリアクティブですが、その中のプロパティはリアクティブではありません。
// そのため、このようにプロパティの値を変更してもWidgetは更新されません。
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.
// `Rx` には自ら変更を検知する手段がないからです。
// そのため、カスタムクラスの場合はこのようにWidgetに変更を知らせる必要があります。
user.refresh();
// or we can use the `update()` method!
// もしくは `update()` メソッドを使用してください。
user.update((value){
value.name='Roi';
});
print( user );
```
## StateMixin
#### 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.
`UI`の状態を管理するもう一つの手法として、`StateMixin<T>`を利用する方法があります。
controllerクラスに`with`を使って`StateMixin<T>`を追加することで実装可能です。
``` 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:
`change()`メソッドにより好きなタイミングで状態を変更することができます。
このようにデータと状態を渡すだけです。
```dart
change(data, status: RxStatus.success());
```
RxStatus allow these status:
RxStatus には以下のステータスが存在します。
``` dart
RxStatus.loading();
... ... @@ -950,7 +952,7 @@ RxStatus.empty();
RxStatus.error('message');
```
To represent it in the UI, use:
ステータスごとにUIを設定するにはこのようにします。
```dart
class OtherClass extends GetView<Controller> {
... ... @@ -961,13 +963,13 @@ class OtherClass extends GetView<Controller> {
body: controller.obx(
(state)=>Text(state.name),
// here you can put your custom loading indicator, but
// by default would be Center(child:CircularProgressIndicator())
// ローディング中はカスタムのインジケーターの設定も可能ですが、
// デフォルトで 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))
// 同様にエラーWidgetはカスタム可能ですが、
// デフォルトは Center(child:Text(error)) です。
onError: (error)=>Text(error),
),
);
... ... @@ -976,22 +978,22 @@ class OtherClass extends GetView<Controller> {
#### GetView
I love this Widget, is so simple, yet, so useful!
このWidgetは私のお気に入りです。とてもシンプルで扱いやすいですよ!
Is a `const Stateless` Widget that has a getter `controller` for a registered `Controller`, that's all.
このWidgetを一言で表現すると、「controllerをgetterに持つ `const` な StatelessWidget」です。
```dart
class AwesomeController extends GetController {
final String title = 'My Awesome View';
}
// ALWAYS remember to pass the `Type` you used to register your controller!
// 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`
child: Text(controller.title), // `controller.なんとか` でアクセス
);
}
}
... ... @@ -999,66 +1001,60 @@ Is a `const Stateless` Widget that has a getter `controller` for a registered `C
#### GetResponsiveView
Extend this widget to build responsive view.
this widget contains the `screen` property that have all
information about the screen size and type.
GetViewをレスポンシブデザインに対応させたい場合はこのWidgetを継承してください。
画面サイズやデバイスタイプなどの情報を持つ `screen` プロパティを保持しています。
##### How to use it
##### 使い方
You have two options to build it.
Widgetをビルドする方法は2つあります。
- 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`
- `builder` メソッドを使う。
- `desktop`, `tablet`, `phone`, `watch` メソッドを使う。
画面サイズ、デバイスタイプに応じたWidgetがビルドされます。
たとえば画面が [ScreenType.Tablet] なら `tablet` メソッドが実行されます。
**注:** `alwaysUseBuilder` プロパティをfalseにする必要があります。
With `settings` property you can set the width limit for the screen types.
`settings` プロパティでブレイクポイントを設定することもできます。
![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)
![](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
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`.
このWidgetはあまり知られておらず、使用するケースは稀です。
GetViewとの違いは、Controllerを`キャッシュ`してくれる点です。
このキャッシュがあるため `const` にはできません。
> So, when do you need to "cache" a Controller?
> それでは一体いつControllerをキャッシュする必要があるのかって?
If you use, another "not so common" feature of **GetX**: `Get.create()`.
それは **GetX** のこれまた使う機会の少ない `Get.create()` を使うときです。
`Get.create(()=>Controller())` will generate a new `Controller` each time you call
`Get.find<Controller>()`,
`Get.create(()=>Controller())` は `Get.find<Controller>()` を実行するたびに
新しい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.
そこで `GetWidget` の出番です。たとえば、Todoアイテムのリスト内容を保持したいとき。
Widgetが更新されてもアイテムはControllerのキャッシュを参照してくれます。
#### 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.
このクラスは `GetxController` に似ており、同様のライフサイクル(`onInit()`, `onReady()`, `onClose()`)を共有しますが、そこに「ロジック」はありません。**GetX**の依存オブジェクト注入システムに、このサブクラスがメモリから **削除できない** ということを知らせるだけです。
So is super useful to keep your "Services" always reachable and active with `Get.find()`. Like:
`ApiService`, `StorageService`, `CacheService`.
そのため `Get.find()` で `ApiService`, `StorageService`, `CacheService` のようなサービス系クラスにいつでもアクセスできるようにしておくと非常に便利です。
```dart
Future<void> main() async {
await initServices(); /// AWAIT SERVICES INITIALIZATION.
await initServices(); /// サービスクラスの初期化をawait
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.
/// Flutterアプリ実行前にサービスクラスを初期化してフローをコントロールするのは賢いやり方です。
/// たとえば GetMaterialAppを更新する必要がないようにUser別の
/// Theme、apiKey、言語設定などをApiサービス実行前にロードしたり。
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.
/// get_storage, hive, shared_pref の初期化はここで行います。
/// あるいは moor の connection など非同期のメソッドならなんでも。
await Get.putAsync(() => DbService().init());
await Get.putAsync(SettingsService()).init();
print('All services started...');
... ... @@ -1083,21 +1079,21 @@ class SettingsService extends GetxService {
```
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`.
`GetxService` を破棄する唯一の方法は `Get.reset()` メソッドを使うことです。
これはアプリにおける「ホットリブート」のようなものです。あるクラスのインスタンスを
ライフサイクルの間ずっと残しておきたい場合は `GetxService` を使うというのを覚えておいてください。
### Tests
## テストの実行
You can test your controllers like any other class, including their lifecycles:
Controllerのライフサイクル含め、他のクラスと同様にテストを実行することができます。
```dart
class Controller extends GetxController {
@override
void onInit() {
super.onInit();
//Change value to name2
// 値を name2 に変更
name.value = 'name2';
}
... ... @@ -1116,22 +1112,20 @@ 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
/// ライフサイクルごとのテストは必ずしも行う必要はありませんが、
/// GetXの依存オブジェクト注入機能を使用しているのであれば実行をおすすめします。
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
/// このようにライフサイクル経過ごとの状態をテスト可能です。
Get.put(controller); // onInit が実行される
expect(controller.name.value, 'name2');
/// Test your functions
/// 関数もテストしましょう
controller.changeName();
expect(controller.name.value, 'name3');
/// onClose was called
/// onClose が実行される
Get.delete<Controller>();
expect(controller.name.value, '');
... ... @@ -1139,27 +1133,25 @@ Test the state of the reactive variable "name" across all of its lifecycles''',
}
```
#### Tips
##### Mockito or mocktail
If you need to mock your GetxController/GetxService, you should extend GetxController, and mixin it with Mock, that way
#### mockitoやmocktailを使う場合
GetxController/GetxService をモックする場合 Mock をミックスインしてください。
```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.reset()
WidgetやGroupのテスト時に、テストの最後かtearDownの中で Get.reset() を実行することで設定をリセットすることができます。
##### Get.testMode
if you are using your navigation in your controllers, use `Get.testMode = true` at the beginning of your main.
#### Get.testMode
Controllerの中でナビゲーションを使用している場合は、`Get.testMode = true`をmainの開始で実行してください。
# Breaking changes from 2.0
# バージョン2.0からの破壊的変更
1- Rx types:
1- Rx型の名称
| Before | After |
| 変更前 | 変更後 |
| ------- | ---------- |
| StringX | `RxString` |
| IntX | `RxInt` |
... ... @@ -1168,10 +1160,10 @@ if you are using your navigation in your controllers, use `Get.testMode = true`
| 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.
RxControllerとGetBuilderが統合され、Controllerにどれを使うか覚えておく必要がなくなりました。GetxControllerを使うだけで、リアクティブと非リアクティブな状態管理の両方に対応できるようになりました。
2- NamedRoutes
Before:
2- 名前付きRoute
変更前:
```dart
GetMaterialApp(
... ... @@ -1181,7 +1173,7 @@ GetMaterialApp(
)
```
Now:
変更後:
```dart
GetMaterialApp(
... ... @@ -1191,9 +1183,9 @@ GetMaterialApp(
)
```
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:
変更の効果:
ページ表示にはパラメータやログイントークンを起点にする方法もありますが、以前のアプローチではこれができず、柔軟性に欠けていました。
ページを関数から取得するよう変更したことで、このようなアプローチを可能にし、アプリ起動直後にRouteがメモリに割り当てられることもないため、RAMの消費量を大幅に削減することもできました。
```dart
... ... @@ -1210,16 +1202,16 @@ GetMaterialApp(
# なぜGetXなのか
1- Flutterのアップデートが重なると、せっかく作ったパッケージがうまく動かなくなることがあります。コンパイルエラーを起こしたり、その時点で解決方法がないエラーが発生したり。開発者はそのエラーがどこから来たのか把握するために問題の追跡をし、該当リポジトリにissueを提起し、問題が解決されるのを見届ける必要があります。Getは開発に必要な主要リソース(状態管理、依存オブジェクトの管理、Route管理)を一元化し、Pubspecにパッケージを1つ追加するだけでコーディングを開始することができます。Flutterのアップデート後に必要なことは、Getも併せてアップデートすることだけです。それですぐに作業を再開できます。またGetはパッケージ間の互換性の問題も解消します。互いに依存するパッケージAの最新バージョンとBの最新バージョンの間に互換性がない、ということが何度あったでしょうか。Getを使えばすべてが同じパッケージ内にあるため、互換性の心配はありません。
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を配置するだけで、その変数のすべての更新が自動的に画面に反映されます。
2- Flutterは手軽で素晴らしいフレームワークですが、`Navigator.of(context).push (context, builder [...]`のように、ほとんどの開発者にとって不要な定型文が一部にあります。Getを使えばそのような定型文を簡素化できます。Routeを呼ぶためだけに8行のコードを書く代わりに、`Get.to(Home())`を実行すれば、次の画面に遷移することができるのです。またウェブURLを動的なものにすることは現在Flutterでは本当に骨の折れる作業ですが、GetXを使えば非常に簡単です。そしてFlutterにおける状態管理と依存オブジェクト管理については、たくさんのパターンやパッケージがあるので多くの議論を生んでいます。しかしGetXのアプローチは大変シンプルです。これは一例ですが、変数の最後に「.obs」を追加して「Obx()」の中にWidgetを配置するだけで、その変数の状態変化が自動でWidgetに反映されます。
3- パフォーマンスのことを気にせず開発できます。Flutterのパフォーマンスはそれだけで素晴らしいものですが、アプリ内で状態管理と併せて、BLoC/store/controllerなどのクラスを配布するサービスロケーターを使用することを想像してみてください。そのインスタンスが必要ないときはリソースを解放するメソッドを明示的に呼び出さなければなりません。しかし、使用されなくなったら単純に自動でメモリから削除してくれればいいのに、と考えたことはありませんか?それを実現してくれるのがGetXです。SmartManagement機能により未使用リソースはすべてメモリから削除されるので、本来のプログラミングに集中することができます。メモリ管理のためのロジックを作らなくても、常に必要最小限のリソースを使っていることが保証されるのです。
3- GetXではパフォーマンスのことをあまり気にせず開発ができます。Flutterのパフォーマンスはそれだけで素晴らしいものですが、状態管理と併せて BLoC / データストア / Controller などを届けるためのサービスロケーターを使用することを想像してみてください。そのインスタンスが必要ないときはリソースを解放するイベントを明示的に呼び出さなければなりません。そんなとき、使用されなくなったら自動でメモリから削除してくれればいいのに、と考えたことはありませんか?それを実現してくれるのがGetXです。SmartManagement機能により未使用のリソースはすべて自動でメモリから破棄されるので、本来の開発作業に集中することができます。メモリ管理のためのロジックを作らなくても、常に必要最小限のリソースを使っていることが保証されるのです。
4- コードのデカップリング(分離)がしやすい。「Viewをビジネスロジックから分離する」というコンセプトを聞いたことがあるかもしれません。これはなにもBLoC、MVC、MVVMに限ったことではなく、どのアーキテクチャパターンにもこのコンセプトが底流にあると言っていいでしょう。しかし、Flutterではcontextの使用によりこのコンセプトが弱まってしまうことがあります。
InheritedWidgetを参照するためにcontextが必要なとき、viewの中でそれを使用するか、パラメータとしてcontextを渡しますよね?私はこの方法は美しくないと感じます。特にチームで仕事をする場合において、常にView内のビジネスロジックに依存しなければならないなんて。GetXのアプローチは標準的なそれとは異質のもので、StatefulWidgetやinitStateなどの使用を禁止しているわけではありませんが、それよりもっとすっきり書ける類似のアプローチを備えています。controller自身にライフサイクルがあるため、たとえばREST APIのリクエストを行うときも、Viewの中の何かに依存するということがありません。controllerのライフサイクルの一つである onInit を使用してhttpを呼び出し、データが到着すると変数にセットされます。GetXはフルリアクティブなので(Streamが根底にあります)、インスタンス変数が値で埋まれば、その変数を使用するすべてのWidgetが自動的に更新されます。これにより、UIの専門家はWidgetの構築に注力することができ、ボタンクリックなどのユーザーイベント以外のものをビジネスロジックに渡す必要がなくなります。その一方で、ビジネスロジックを扱う人はビジネスロジックだけに集中して、個別テストを簡単に行うことができます。
4- コードのデカップリング(分離)がしやすい。「ビューをビジネスロジックから分離する」というコンセプトを聞いたことがあるかもしれません。これはなにもBLoC、MVC、MVVMに限ったことではなく、どのアーキテクチャパターンもこのコンセプトが考え方の基本にあると言っていいでしょう。しかし、Flutterではcontextの使用によりこのコンセプトが薄まってしまいがちです。
InheritedWidgetを参照するためにcontextが必要なとき、ビューの中でそれを使用するか、引数としてcontextを渡しますよね?私はこの方法は美しくないと感じます。常にビュー内のビジネスロジックに依存しなければならないのは、特にチームで仕事をする場面においては不便だと感じます。GetXによるアプローチでは、StatefulWidgetやinitStateなどの使用を禁止しているわけではありませんが、それらよりもずっとスッキリ書けるようになっています。Controller自体にライフサイクルがあるため、たとえばREST APIのリクエストを行うときも、ビューの中の何かに依存するということがありません。Controllerのライフサイクルの一つである onInit を使用してhttpを呼び出し、データが到着すると変数にセットされます。GetXはリアクティブな変数を扱うことができるので、インスタンス変数が変わりし次第、その変数に依存するWidgetがすべて自動更新されます。これによりUIの担当者はWidgetの見た目に注力することができ、ボタンクリックなどのユーザーイベント以外のものをビジネスロジックに渡す必要がなくなります。その一方でビジネスロジックの担当者はビジネスロジックだけに集中し、個別のテストを簡単に行うことができます。
このGetXライブラリは今後も更新され続け、新しい機能を実装していきます。気軽にプルリクエストを出していただき、ライブラリの成長に貢献していただければ幸いです。
GetXライブラリは今後も更新され続け、新しい機能を実装していきます。気軽にプルリクエストを出していただき、ライブラリの成長に貢献していただけるとうれしいです。
# コミュニティ
... ... @@ -1231,7 +1223,7 @@ GetX繧ウ繝溘Η繝九ユ繧」縺ッ髱槫クク縺ォ豢サ逋コ縺ァ譛臥寢縺ェ諠ア縺ァ縺ゅ繧後※縺∪
| :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
| [![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をより良いものにするためのコントリビュート例をご紹介します。_
... ... @@ -1241,9 +1233,9 @@ _GetX繝励Ο繧ク繧ァ繧ッ繝医↓雋「迪ョ縺励※縺ソ縺セ縺帙s縺具シ溘≠縺ェ縺溘r繧ウ繝ウ繝医Μ
- コードやテストのプルリクエスト。
- 新機能の提案。
どのような形の貢献であれ歓迎しますので、ぜひコミュニティにご参加ください!
どのような形の貢献であれ歓迎しますので、ぜひコミュニティにご参加ください!
## GetXに関する記事とビデオ
## 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).
... ...
# 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)
- [Get.lazyPut()](#getlazyput)
- [Get.putAsync()](#getputasync)
- [Get.create()](#getcreate)
- [インスタンス化したクラスを使う](#インスタンス化したクラスを使う)
- [依存オブジェクトの置換](#依存オブジェクトの置換)
- [各メソッドの違い](#各メソッドの違い)
- [Bindings(Routeと依存オブジェクトの結束)](#Bindings(Routeと依存オブジェクトの結束))
- [Bindingsクラス](#bindingsクラス)
- [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)
- [Bindingsの仕組み](#Bindingsの仕組み)
- [補足](#補足)
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:
Getにはシンプルで強力な依存オブジェクト管理機能があります。たった1行のコードで、Provider contextやinheritedWidgetを使うことなく、BlocもしくはControllerのインスタンスを取得することができます。
```dart
Controller controller = Get.put(Controller()); // Rather Controller controller = Controller();
Controller controller = Get.put(Controller()); // 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
UIクラスの中でControllerクラスをインスタンス化する代わりに、Getインスタンスの中でインスタンス化することで、アプリ全体でControllerを利用できるようになります。
- 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
- 注: Getの状態管理機能を使用する場合は、[Bindings](#bindings)の使用も検討してください。Bindingsを使うことでビューにControllerを結合させることができます。
- 注²: Getの依存オブジェクト管理機能は、パッケージの他の部分から独立しています。そのため、たとえばあなたのアプリが既に他の状態管理ライブラリを使用している場合(どんなものでも)、何の問題もなく2つを組み合わせることができます。
## Instancing methods
The methods and it's configurable parameters are:
## インスタンス化に使用するメソッド
Controllerを初期化するのに使用するメソッドとその設定パラメーターについてご説明します。
### Get.put()
The most common way of inserting a dependency. Good for the controllers of your views for example.
依存オブジェクトを注入するための最も基本のメソッド。たとえば、ビューで使用するControllerに使います。
```dart
Get.put<SomeClass>(SomeClass());
... ... @@ -44,46 +43,45 @@ Get.put<LoginController>(LoginController(), permanent: true);
Get.put<ListItemController>(ListItemController, tag: "some unique string");
```
This is all options you can set when using put:
以下が 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
// 必須。インスタンスを保存しておきたいControllerなどを設定
// 注: "S" 型はジェネリクスで、どんな型でもOK
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
// オプション。これは同じ型のControllerインスタンスが複数存在する場合に、
// タグIDにより識別したい場合に使用します。
// Get.find<Controller>(tag: ) でこのputで設定したインスタンスを探します。
// tag はユニークな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
// オプション。デフォルトでは使用されなくなったインスタンスは破棄されますが、
// (たとえばビューが閉じられた場合など) SharedPreferencesのインスタンスなど、
// アプリ全体を通して生かしておきたい場合があるかと思います。
// その場合はこれをtrueにしてください。デフォルトは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
// オプション。テストで抽象クラスを使用した後、別クラスに置換してテストを追うことができます。
// デフォルトは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.
### Get.lazyPut()
依存オブジェクトをすぐにロードする代わりに、lazy(遅延、消極的)ロードすることができます。実際に使用されるときに初めてインスタンス化されます。計算量の多いクラスや、Bindingsを使って複数のControllerをまとめてインスタンス化したいが、その時点ではすぐにそれらを使用しないことがわかっている場合などに非常に便利です。
```dart
/// ApiMock will only be called when someone uses Get.find<ApiMock> for the first time
/// この場合のApiMockは Get.find<ApiMock> を使用した時点でインスタンス化されます。
Get.lazyPut<ApiMock>(() => ApiMock());
Get.lazyPut<FirebaseAuth>(
() {
// ... some logic if needed
// 必要ならここに何かのロジック
return FirebaseAuth();
},
tag: Math.random().toString(),
... ... @@ -93,27 +91,27 @@ Get.lazyPut<FirebaseAuth>(
Get.lazyPut<Controller>( () => Controller() )
```
This is all options you can set when using lazyPut:
これが .lazyPut で設定できるパラメーターです。
```dart
Get.lazyPut<S>(
// mandatory: a method that will be executed when your class is called for the first time
// 必須。クラスSが初めてfindの対象になったときに実行されるメソッド
InstanceBuilderCallback builder,
// optional: same as Get.put(), it is used for when you want multiple different instance of a same class
// must be unique
// オプション。Get.put()のtagと同様に同じクラスの異なるインスタンスが必要なときに使用
// ユニークな値を指定
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
// オプション。"permanent" に似ていますが、使用されていないときはインスタンスが
// 破棄され、再び使用するときにGetがインスタンスを再び作成する点が異なります。
// Bindings APIの "SmartManagement.keepFactory " と同じです。
// デフォルトはfalse
bool fenix = false
)
```
### Get.putAsync
If you want to register an asynchronous instance, you can use `Get.putAsync`:
### Get.putAsync()
SharedPreferencesなど、非同期のインスタンスを登録したいときに使います。
```dart
Get.putAsync<SharedPreferences>(() async {
... ... @@ -125,87 +123,85 @@ Get.putAsync<SharedPreferences>(() async {
Get.putAsync<YourAsyncClass>( () async => await YourAsyncClass() )
```
This is all options you can set when using putAsync:
これが .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
// オプション。Get.put() と同じです。同じクラスの異なるインスタンスを作りたいときに使用
// ユニークな値を指定
String tag,
// optional: same as in Get.put(), used when you need to maintain that instance alive in the entire app
// defaults to false
// オプション。Get.put() と同じです。アプリ全体を通して生かしておきたい場合に使用
// デフォルトはfalse
bool permanent = false
)
```
### Get.create
### 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:
これが .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())
// 必須。Get.find() が呼ばれるたびにインスタンスがこの関数で新たに組み立てられる。
// 例: 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
// オプション。Get.put() のtagと同様で、同じクラスによる
// 複数インスタンスを扱うときに使用します。
// リストのアイテムにそれぞれコントローラが必要な場合に便利です。
// 文字列はユニークである必要があります。
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
// オプション。Get.put() と同様アプリ全体でインスタンスを維持するときに使用。
// 唯一の違いは Get.create() のpermanentはデフォルトでtrueということだけです。
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:
いくつかのRouteを渡り歩いた後、以前のControllerに残してきたデータが必要になったとしたら、Provider や Get_it と組み合わせる必要がありますよね?Getの場合は違います。GetにControllerの「検索」を依頼するだけで追加の依存オブジェクトの注入は必要ありません。
```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.
// マジックみたいですよね。でも実際にGetはControllerのインスタンスを探して届けてくれます。
// 100万ものControllerをインスタンス化していても、Getは常に正しいControllerを探してくれます。
```
And then you will be able to recover your controller data that was obtained back there:
そしてそのControllerが以前取得したデータをあなたは復元することができます。
```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
print(count); // 出力: 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
Get.delete<Controller>(); // 通常であれば、GetXは未使用Controllerを自動削除するので、この作業は必要ありません。
```
## 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.
注入されている依存オブジェクトは `replace` または `lazyReplace` メソッドを使って、子クラスなど関連クラスのインスタンスに置き換えることができます。これは元の抽象クラスを型指定することで取得することができます。
```dart
abstract class BaseClass {}
... ... @@ -234,44 +230,44 @@ print(instance is OtherClass); //true
## Differences between methods
First, let's of the `fenix` of Get.lazyPut and the `permanent` of the other methods.
まずは Get.lazyPut の `fenix` プロパティと、他メソッドの `permanent` プロパティの違いについてご説明します。
The fundamental difference between `permanent` and `fenix` is how you want to store your instances.
`permanent` と `fenix` の根本的な違いは、インスタンスをどのように保持したいかという点に尽きます。
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.
しつこいようですが、GetXでは使われていないインスタンスは削除されるのがデフォルトの動作です。
これはもし画面AがController A、画面BがController Bを持っている場合において、画面Bに遷移するときに画面Aをスタックから削除した場合(`Get.off()` や `Get.offNamed()` を使うなどして)、Controller Aは消えてなくなるということです。
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.
しかし Get.put() する際に `permanent:true` としていれば、Controller Aはこの画面削除により失われることはありません。これはアプリケーション全体を通してControllerを残しておきたい場合に大変便利です。
`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.
一方の `fenix` は、画面削除に伴っていったんはControllerが消去されますが、再び使いたいと思ったときに復活させることができます。つまり基本的には未使用の Controller / サービス / その他クラス は消去されますが、必要なときは新しいインスタンスを「燃えカス」から作り直すことができるのです。
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.put と Get.putAsync はインスタンスを作成して初期化するプロセスは同じですが、後者は非同期メソッドを使用するという違いがあります。この2つのメソッドは内部に保有するメソッド `insert` に `permanent: false` と `isSingleton: true` という引数を渡して、メモリに直接インスタンスを挿入します (この isSingleton が行っていることは、依存オブジェクトを `dependency` と `builder` プロパティのどちらから拝借するかを判断することだけです)。その後に `Get.find()` が呼ばれると、メモリ上にあるインスタンスを即座に初期化するというプロセスをたどります。
- 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.create はその名の通り、依存オブジェクトを「クリエイト」します。Get.put() と同様に内部メソッドである `insert` を呼び出してインスタンス化します。違いは `permanent: true` で `isSingleton: false` である点です (依存オブジェクトを「クリエイト」しているため、シングルトンにはなりません。それが false になっている理由です)。また `permanent: true` となっているので、デフォルトでは画面の破棄などでインスタンスを失わないというメリットがあります。また `Get.find()` はすぐに呼ばれず、画面内で実際に使用されてから呼ばれます。これは `permanent` の特性を活かすための設計ですが、それゆえ `Get.create()` は共有しないけど破棄もされないインスタンスを作成する目的で作られたと言えます。たとえば、ListViewの中のボタンアイテムに使うControllerインスタンスのように、そのリスト内でしか使わないけどリストアイテムごとに固有のインスタンスが必要なケースなどが考えられます。そのため、Get.create は 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.
- Get.lazyPut は初期化をlazy(遅延、消極的)に行います。実行されるとインスタンスは作成されますが、すぐに使用できるように初期化はされず、待機状態になります。また他のメソッドと異なり `insert` メソッドは呼び出されません。その代わり、インスタンスはメモリの別の部分に挿入されます。この部分を「ファクトリー」と呼ぶことにしましょう。「ファクトリー」は、そのインスタンスが再生成できるかどうかを決める役割を持っています。これは後で使う予定のものを、現在進行形で使われているものと混ざらないようにするための工夫です。ここで `fenix` によるマジックが登場します。デフォルトの `fenix: false` のままにしており、かつ `SmartManagement` が `keepFactory` ではない場合において `Get.find` を使用すると、インスタンスは「ファクトリー」から共有メモリ領域に移動します。その直後にインスタンスは「ファクトリー」から削除されます。しかし `fenix: true` としていた場合、インスタンスは「ファクトリー」に残るため、共有メモリ領域から削除されても再び呼び出すことができるのです。
## Bindings
## Bindings(Routeと依存オブジェクトの結束)
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.
このパッケージの一番の差別化要素は、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 class
### Bindingsクラス
- Create a class and implements Binding
- Bindings機能を実装したクラスを作成することができます。
```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:
"dependencies" メソッドをオーバーライドするようIDEに自動で指摘されます。表示をクリックしてメソッドを override し、そのRoute内で使用するすべてのクラスを挿入してください。
```dart
class HomeBinding implements Bindings {
... ... @@ -290,9 +286,9 @@ class DetailsBinding implements Bindings {
}
```
Now you just need to inform your route, that you will use that binding to make the connection between route manager, dependencies and states.
Bindingsを設定したら、このクラスが Route管理 / 依存オブジェクト管理 / 状態管理 を互いに接続する目的で使用されるものだということをRouteに知らせてあげます。
- Using named routes:
- 名前付きRouteを使う場合
```dart
getPages: [
... ... @@ -309,16 +305,16 @@ getPages: [
];
```
- Using normal routes:
- 通常のRouteを使う場合
```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.
これでアプリケーションのメモリ管理を気にする必要がなくなります。Getがすべてやってくれます。
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.
BindingsクラスはRouteの呼び出しと同時に呼び出されます。また、すべてに共通の依存オブジェクトを挿入するためには GetMaterialApp の initialBinding プロパティを使用してください。
```dart
GetMaterialApp(
... ... @@ -329,8 +325,7 @@ GetMaterialApp(
### 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.
Bindingsを作成する一般的な方法は Bindings を実装したクラスを作成することですが、`BindingsBuilder` コールバックを使う方法もあります。
Example:
... ... @@ -354,25 +349,25 @@ getPages: [
];
```
That way you can avoid to create one Binding class for each route making this even simpler.
この方法ならRouteごとにBindingsクラスを作る必要はありません。
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.
エラーが発生してControllerを使用するWidgetが正しく破棄されなかった場合でも、Controllerが未使用になればGetXはデフォルトの動作通りそれをメモリから削除します。
これがいわゆる依存オブジェクト管理機能の `full` モードと呼ばれるものです。
しかしもしGetXによるオブジェクト破棄の方法をコントロールしたい場合は、`SmartManagement`クラスを使って設定してください。
#### 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
smartManagement: SmartManagement.onlyBuilders // ここで設定
home: Home(),
)
)
... ... @@ -381,30 +376,30 @@ void main () {
#### 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.
これがデフォルトのモードです。使用されていない、かつ `permanent: true` が設定されていないオブジェクトを自動で破棄してくれます。特殊な事情がない限り、この設定は触らない方がいいでしょう。GetXを使って間がない場合は特に。
#### SmartManagement.onlyBuilders
With this option, only controllers started in `init:` or loaded into a Binding with `Get.lazyPut()` will be disposed.
`init:` もしくはBindings内で `Get.lazyPut()` により設定したビルダー製のオブジェクトだけを破棄するモードです。
If you use `Get.put()` or `Get.putAsync()` or any other approach, SmartManagement will not have permissions to exclude this dependency.
もしそれが `Get.put()` や `Get.putAsync()` などのアプローチで生成したオブジェクトだとしたら、SmartManagement は勝手にメモリから除外することはできません。
With the default behavior, even widgets instantiated with "Get.put" will be removed, unlike SmartManagement.onlyBuilders.
それに対してデフォルトのモードでは `Get.put()` で生成したオブジェクトも破棄します。
#### 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.
SmartManagement.full と同じように、オブジェクトが使用されていない状態になれば破棄します。ただし、前述の「ファクトリー」に存在するものだけは残します。つまりそのインスタンスが再び必要になった際は依存オブジェクトを再度生成するということです。
### 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.
### Bindingsの仕組み
Bindingsは「一過性のファクトリー」のようなものを作成します。これはそのRouteに画面遷移した瞬間に作成され、そこから画面移動するアニメーションが発生した瞬間に破棄されます。
この動作は非常に高速で行われるので、アナライザーでは捕捉できないほどです。
再び元の画面に戻ると新しい「一過性のファクトリー」が呼び出されます。そのためこれは SmartManagement.keepFactory を使用するよりも多くの場合好ましいですが、Bindingsを作成したくない場合やすべての依存オブジェクトを同じBindingsに持っておきたい場合は SmartManagement.keepFactory を使うといいでしょう。
ファクトリーのメモリ使用量は少なく、インスタンスを保持することはありません。その代わりにそのクラスのインスタンスを形作る関数を保持します。
メモリコストは非常に低いのですが、最小リソースで最大パフォーマンスを得ることが目的のGetではデフォルトでファクトリーを削除します。
どちらか都合に合う方ををお使いいただければと思います。
## 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.
- 複数のBindingsを使う場合は SmartManagement.keepFactory は**使わない**でください。これは Bindings を使わないケースや、GetMaterialAppのinitialBindingに設定された単独のBindingと一緒に使うケースを想定されて作られました。
- 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.
- Bindingsを使うことは必須ではありません。`Get.put()` と `Get.find()` だけでも全く問題ありません。
ただし、サービスやその他抽象度の高いクラスをアプリに取り入れる場合はコード整理のために使うことをおすすめします。
... ...
- [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.
- [Route管理](#Route管理)
- [使い方](#使い方)
- [通常Routeによるナビゲーション](#通常Routeによるナビゲーション)
- [名前付きRouteによるナビゲーション](#名前付きRouteによるナビゲーション)
- [名前付きRouteにデータを送る](#名前付きRouteにデータを送る)
- [動的URLの生成](#動的URLの生成)
- [ミドルウェアの使用](#ミドルウェアの使用)
- [contextを使わないナビゲーション](#contextを使わないナビゲーション)
- [SnackBar](#snackbar)
- [Dialog](#dialog)
- [BottomSheet](#bottomsheet)
- [ネスト構造のナビゲーション](#ネスト構造のナビゲーション)
# Route管理
このドキュメントではGetXにおけるRoute管理のすべてをご説明します。
## How to use
Add this to your pubspec.yaml file:
次の3文字を pubspec.yaml ファイルに追加してください。
```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!
Route / SnackBar / Dialog / BottomSheet をcontextなしで、あるいは高レベルのGet APIを使用するには MaterialApp の前に「Get」を追加してください。それだけで GetMaterialApp の機能が使用できます。
```dart
GetMaterialApp( // Before: MaterialApp(
GetMaterialApp( // 変更前: MaterialApp(
home: MyHome(),
)
```
## Navigation without named routes
## 名前付きRouteによる画面遷移
To navigate to a new screen:
次の画面に遷移するには Get.to を使ってください。
```dart
Get.to(NextScreen());
```
To close snackbars, dialogs, bottomsheets, or anything you would normally close with Navigator.pop(context);
SnackBar / Dialog / BottomSheet など Navigator.pop(context) で閉じるものと同じものを閉じるには Get.back を使います。
```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.)
次の画面に遷移しつつ、前の画面に戻れないようにするには Get.off を使います(スプラッシュスクリーンやログイン画面などで使用)。
```dart
Get.off(NextScreen());
```
To go to the next screen and cancel all previous routes (useful in shopping carts, polls, and tests)
次の画面に遷移して、それ以前のRouteはすべて破棄するには Get.offAll を使います(ショッピングカート、投票、テストなどで使用)
```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:
... ... @@ -78,13 +78,12 @@ ex:
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:
どのようなシンタックスがあるかもっと知りたいですか?
いつもの Navigator ではなく navigator と入れてみてください。通常のNavigatorで使えるプロパティがcontextなしで使えるようになっているかと思います。
```dart
// Default Flutter navigator
// 通常のFlutterによるNavigator
Navigator.of(context).push(
context,
MaterialPageRoute(
... ... @@ -94,7 +93,7 @@ Navigator.of(context).push(
),
);
// Get using Flutter syntax without needing context
// GetではFlutterのシンタックスをcontextなしで使えます
navigator.push(
MaterialPageRoute(
builder: (_) {
... ... @@ -103,35 +102,35 @@ navigator.push(
),
);
// Get syntax (It is much better, but you have the right to disagree)
// Getのシンタックス(上記よりかなり短いですね)
Get.to(HomePage());
```
## Navigation with named routes
## 名前付きRouteによる画面遷移
- If you prefer to navigate by namedRoutes, Get also supports this.
- Getは名前付きRouteによる遷移もサポートしています。
To navigate to nextScreen
次の画面への遷移はこう。
```dart
Get.toNamed("/NextScreen");
```
To navigate and remove the previous screen from the tree.
Get.off の名前付きRoute版。
```dart
Get.offNamed("/NextScreen");
```
To navigate and remove all previous screens from the tree.
Get.offAll の名前付きRoute版。
```dart
Get.offAllNamed("/NextScreen");
```
To define routes, use GetMaterialApp:
Routeを定義するにはGetMaterialAppを使ってください。
```dart
void main() {
... ... @@ -144,7 +143,7 @@ void main() {
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.zoom
transition: Transition.zoom
),
],
)
... ... @@ -152,7 +151,7 @@ void main() {
}
```
To handle navigation to non-defined routes (404 error), you can define an unknownRoute page in GetMaterialApp.
未定義Route(404エラー)に遷移させるには、GetMaterialAppで unknownRoute を設定してください。
```dart
void main() {
... ... @@ -169,39 +168,39 @@ void main() {
}
```
### Send data to named Routes
### 名前付きRouteにデータを送る
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.
次の画面に渡すデータは arguments で引数を設定します。Getでは引数にどんなものでも指定できます。StringでもMapでもListでも、クラスのインスタンスでも大丈夫です。
```dart
Get.toNamed("/NextScreen", arguments: 'Get is the best');
```
on your class or controller:
ビュー側のクラスやControllerで値を使うにはこうしてください。
```dart
print(Get.arguments);
//print out: Get is the best
// Get is the best が表示される
```
### Dynamic urls links
### 動的URLの生成
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.
Getはウェブのような高度な動的URLを提供します。ウェブ開発者はFlutterにこの機能が提供されることを待ち望んでいたことでしょう。この機能の提供を謳うパッケージは存在しますが、ウェブ上のURLとは全く異なるシンタックスが表示されているのを見たことがあるかもしれません。Getはこの点も解決します。
```dart
Get.offAllNamed("/NextScreen?device=phone&id=354&name=Enzo");
```
on your controller/bloc/stateful/stateless class:
ビュー側のクラスやControllerで値を使う方法。
```dart
print(Get.parameters['id']);
// out: 354
// 出力: 354
print(Get.parameters['name']);
// out: Enzo
// 出力: Enzo
```
You can also receive NamedParameters with Get easily:
この名前付きパラメーターはこのように簡単に受け取ることもできます。
```dart
void main() {
... ... @@ -217,7 +216,8 @@ void main() {
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.
// 引数userを使う場合と使わない場合で別ページを定義することが可能です。
// ただ、そのためにはスラッシュ '/' をベースのRoute名の後に入れる必要があります。
GetPage(
name: '/profile/:user',
page: () => UserProfile(),
... ... @@ -225,7 +225,7 @@ void main() {
GetPage(
name: '/third',
page: () => Third(),
transition: Transition.cupertino
transition: Transition.cupertino
),
],
)
... ... @@ -233,46 +233,46 @@ void main() {
}
```
Send data on route name
Route名を使ってデータを送る方法。
```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
// 出力: 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
あとは Get.toNamed() を使い、名前付きRouteを指定するだけです(contextを使わないので BLoC や Controller から直接Routeを呼び出すことができます)。ウェブアプリとしてコンパイルされると、Routeが正しくURLに表示されます。
### Middleware
### ミドルウェアの使用
If you want to listen Get events to trigger actions, you can to use routingCallback to it
何かのアクションのトリガーとなるイベントを取得したい場合は、routingCallbackを使用してください。
```dart
GetMaterialApp(
... ... @@ -284,7 +284,7 @@ GetMaterialApp(
)
```
If you are not using GetMaterialApp, you can use the manual API to attach Middleware observer.
GetMaterialAppを使用しない場合は、手動のAPIを使ってミドルウェアオブザーバーを設定してください。
```dart
void main() {
... ... @@ -294,21 +294,21 @@ void main() {
initialRoute: "/",
navigatorKey: Get.key,
navigatorObservers: [
GetObserver(MiddleWare.observer), // HERE !!!
GetObserver(MiddleWare.observer), // ここ
],
),
);
}
```
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.
/// Routeの他に SnackBar / Dialog / BottomSheet のイベントも監視することができます。
/// また、ここで直接この3つのいずれかを表示したい場合は、
/// イベント自身が「それではない」ことを事前にチェックする必要があります。
if (routing.current == '/second' && !routing.isSnackbar) {
Get.snackbar("Hi", "You are on second route");
} else if (routing.current =='/third'){
... ... @@ -318,7 +318,7 @@ class MiddleWare {
}
```
Now, use Get on your code:
それではGetをコードで使ってみましょう。
```dart
class First extends StatelessWidget {
... ... @@ -391,11 +391,11 @@ class Third extends StatelessWidget {
}
```
## Navigation without context
## contextを使わないナビゲーション
### SnackBars
### SnackBar
To have a simple SnackBar with Flutter, you must get the context of Scaffold, or you must use a GlobalKey attached to your Scaffold
FlutterでシンプルなSnackBarを表示したいとき、Scaffoldのcontextか、GlobalKeyを取得する必要があります。
```dart
final snackBar = SnackBar(
... ... @@ -405,23 +405,22 @@ final snackBar = SnackBar(
onPressed: (){}
),
);
// Find the Scaffold in the widget tree and use
// it to show a SnackBar.
// WidgetツリーでScaffoldを探し、それをSnackBar表示に使用します。
Scaffold.of(context).showSnackBar(snackBar);
```
With Get:
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!
コードのどこにいようと、Get.snackbar を呼ぶだけでいいのです。カスタマイズも自由自在です。
```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
"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:(){},
... ... @@ -431,7 +430,7 @@ Get.snackbar(
);
////////// ALL FEATURES //////////
////////// すべてのプロパティ //////////
// Color colorText,
// Duration duration,
// SnackPosition snackPosition,
... ... @@ -468,18 +467,17 @@ Get.snackbar(
///////////////////////////////////
```
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.
従来の SnackBar がお好みの場合や、ゼロからカスタマイズしたい場合 (たとえば Get.snackbar ではタイトルと本文が必須項目となっています)は `Get.rawSnackbar();` を使ってください。SnackBarの元々のAPIを取得できます。
### Dialogs
### Dialog
To open dialog:
ダイアログを表示する方法。
```dart
Get.dialog(YourDialogWidget());
```
To open default dialog:
デフォルトのダイアログを表示する方法。
```dart
Get.defaultDialog(
... ... @@ -488,15 +486,15 @@ Get.defaultDialog(
);
```
You can also use Get.generalDialog instead of showGeneralDialog.
また showGeneralDialog の代わりに Get.generalDialog が使えます。
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.
Overlayを使用するCupertino含むその他のFlutterのダイアログについては、contextの代わりに Get.overlayContext を使うことでコードのどこでもダイアログを表示することができます。
Overlayを使わないWidgetについては、Get.context が使えます。
これら2つのcontextはほとんどのケースでUIのcontextを代替することができるでしょう。ただし、ナビゲーションのcontextを使用せずInheritedWidgetが使われているケースは例外です。
### BottomSheets
### BottomSheet
Get.bottomSheet is like showModalBottomSheet, but don't need of context.
Get.bottomSheet は showModalBottomSheet に似ていますが、contextが不要です。
```dart
Get.bottomSheet(
... ... @@ -519,18 +517,18 @@ Get.bottomSheet(
);
```
## 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.
GetはFlutterのネスト構造のナビゲーションの扱いも簡単にしてくれます。
contextを必要とせず、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.
- 注: 並列のナビゲーションスタックを作成することは危険です。ネスト構造のNavigatorを使用しないか、使用を控えめにするのが理想です。必要なら使っていただいても問題ありませんが、複数のナビゲーションのスタックを保持することはRAM消費の面で好ましくないということは覚えておいてください。
See how simple it is:
こんなに簡単にできます。
```dart
Navigator(
key: Get.nestedKey(1), // create a key by index
key: Get.nestedKey(1), // インデックス指定でkey作成
initialRoute: '/',
onGenerateRoute: (settings) {
if (settings.name == '/') {
... ... @@ -543,7 +541,7 @@ Navigator(
child: TextButton(
color: Colors.blue,
onPressed: () {
Get.toNamed('/second', id:1); // navigate by your nested route by index
Get.toNamed('/second', id:1); // インデックス指定でネスト型Routeに遷移
},
child: Text("Go to 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)
* [状態管理](#状態管理)
+ [リアクティブな状態管理](#リアクティブな状態管理)
- [利点](#利点)
- [パフォーマンスの最大化](#パフォーマンスの最大化)
- [リアクティブな変数の宣言](#リアクティブな変数の宣言)
- [初期値の設定](#初期値の設定)
- [Observableの値をビュー内で使う](#Observableの値をビュー内で使う)
- [更新条件を設定](#更新条件を設定)
- [.obsの使いどころ](#.obsの使いどころ)
- [List(Rx)に関する補足](#List(Rx)に関する補足)
- [なぜ「.value」を使う必要があるのか](#なぜ「.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)
- [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)
# 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.
GetXは他の状態管理ライブラリのように Stream や ChangeNotifier を使用する必要がありません。なぜか?私たちは応答時間とRAM消費量を改善するために GetValueとGetStream という低遅延のソリューションを開発しましたが、状態管理機能を含むGetXのリソースはすべてこれをベースに作られているためです。このソリューションはより低い運用コストと高いパフォーマンスを実現します。GetXを使えばAndroid、iOS、Web、Linux、macOS用のアプリケーションを作成するだけでなく、Flutter/GetXと同じシンタックスでサーバーアプリケーションを作ることができます。
* _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.
* _バカみたいにシンプル_: 他の状態管理アプローチの中には、複雑で多くのボイラープレートコードを書かなければいけないものもあります。この問題により少なくない人たちがFlutterを見限りましたが、今ようやく、バカみたいにシンプルなソリューションを手に入れることができました。GetXを使えば、非常にすっきりとした、記述量の少ないコードでより多くのことができるようになります。イベントごとにクラスを定義する必要もありません。
* _コード生成にサヨナラ_: 開発時間の半分はアプリケーションロジックの作成に費やします。それにも関わらず、状態管理ライブラリの中には、ミニマルなコードを作るためにコード生成ツールに依存しているものがあります。変数を変更して build_runner を実行するのは非生産的ですし、flutter clean 後の待ち時間もコーヒーをたくさん飲まなければならないほど長くなることもあります。
With GetX everything is reactive, and nothing depends on code generators, increasing your productivity in all aspects of your development.
GetXはすべてがリアクティブであり、コード生成ツールに依存しないため、開発のあらゆる面において生産性が向上します。
* _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.
* _context依存にサヨナラ_: ビューとビジネスロジックを連携させるため、ビューのcontextをControllerに送る必要に迫られた。contextがないところで依存オブジェクトの注入をする必要があり、contextを方々のクラスや関数からなんとか渡した。これらの経験、誰もが通ってきた道かと思います。しかし、GetXではこのような経験をすることはありません。contextなしで、Controllerの中から別のControllerにアクセスすることができます。パラメーターを通じて無駄にcontextを送る必要はもうありません。
* _細かいコントロール_: 多くの状態管理ソリューションは、ChangeNotifierをベースにしています。ChangeNotifierは、notifyListenerが呼ばれたときに、依存するすべてのWidgetに通知します。画面に40個のWidgetがあるとしましょう。それらがすべてChangeNotifierの変数に依存している場合、変数を1つでも更新すれば、すべてのWidgetが更新されます。
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.
GetXを使えばネストされたWidgetさえも的確にビルドを処理することができます。ListViewを担当するObxと、ListViewの中のチェックボックスを担当するObxがあれば、チェックボックスの値を変更した場合はチェックボックスWidgetだけが更新され、Listの値を変更した場合はListViewだけが更新されます。
* _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.
* _変数が本当に変わったときだけ更新する_: GetXはデータの流れをコントロールします。つまり、Textに紐づいたObservable(監視可能)変数の値 'Paola' を、同じ 'Paola' に変更してもWidgetは更新されません。これは、GetXがTextに'Paola'がすでに表示されていることをわかっているためです。
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:
リアクティブプログラミングは複雑であると言われがちなためか、多くの人に敬遠されています。しかし、GetXはリアクティブプログラミングを非常にシンプルなものにしてくれます。
* 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.
* StreamControllerを作る必要はありません。
* 変数ごとにStreamBuilderをセットする必要はありません。
* 状態ごとにクラスを作る必要はありません。
* 初期値のためにgetを準備する必要はありません。
Reactive programming with Get is as easy as using setState.
Getによるリアクティブプログラミングは、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.
たとえば name という変数があり、それを変更するたびに変数に依存するすべてのWidgetを自動更新したいとします。
This is your count variable:
これがその name 変数です。
``` dart
var name = 'Jonatas Borges';
```
To make it observable, you just need to add ".obs" to the end of it:
これをObservable(監視可能)にするには、値の末尾に ".obs" を付け足すだけです。
``` 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_.
(以後、このリアクティブな ".obs" 変数、Observable(監視可能)を _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.
内部ではこのような処理を行っています: `String`の`Stream`を作成し、初期値`"Jonatas Borges"`を割り当て、`"Jonatas Borges"`に依存するすべてのWidgetに、あなたは今この変数の影響下にあるから、_Rx_の値が変更されたときには、あなたも同様に変更する必要がある旨を通知。
This is the **magic of GetX**, thanks to Dart's capabilities.
これがDartの機能のおかげで実現できた **GetX マジック** です。
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".
しかし皆さんご存知の通り、`Widget` は関数の中にいなければ自らを更新できません。静的クラスには「自動更新」の機能がないからです。
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?
それなら、同じスコープ内で複数の変数に依存してWidgetをビルドする場合は、複数の `StreamBuilder` をネストして変数の変化を監視する必要がありますね。
No, you don't need a `StreamBuilder` , but you are right about static classes.
いいえ、**GetX** なら `StreamBuilder` すら不要です。
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.
またWidgetを更新する際のボイラープレートコードについても、**GetX**では忘れてください。
`StreamBuilder( … )` ? `initialValue: …` ? `builder: …` ? Nope, you just need to place this variable inside an `Obx()` Widget.
`StreamBuilder( ... )` ? `initialValue: ...` ? `builder: ...` ? これらはすべて不要で、対象のWidgetを `Obx()` の中に入れるだけです。
``` dart
Obx (() => Text (controller.name));
```
_What do you need to memorize?_ Only `Obx(() =>` .
_覚えること?_ それは `Obx(() =>` だけです。
You are just passing that Widget through an arrow-function into an `Obx()` (the "Observer" of the _Rx_).
そのWidgetをアロー関数を通じて `Obx()`(_Rx_のObserver(監視者))に渡すだけです。
`Obx` is pretty smart, and will only change if the value of `controller.name` changes.
`Obx` は非常に賢く、`controller.name` の値が本当に変わったときにのみ、Widgetの更新をかけます。
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?**
`name` が `"John"` だとして、それを `"John"` ( `name.value = "John"` ) に変更しても、以前と同じ `value` のため画面上では何も変化しません。`Obx` はリソースを節約するために値を無視し、Widgetを更新しません。**すごいでしょ?**
> So, what if I have 5 _Rx_ (observable) variables within an `Obx` ?
> では、もしも `Obx` の中に_Rx_(Observable)変数が5つあったらどうでしょう?
It will just update when **any** of them changes.
5つの**いずれかに**値の変化があればWidgetは更新されます。
> And if I have 30 variables in a class, when I update one, will it update **all** the variables that are in that class?
> また、1つのControllerクラスに30もの変数がある場合、1つの変数を更新したら変数に関わるWidgetが**すべて**更新されてしまうのでしょうか?
Nope, just the **specific Widget** that uses that _Rx_ variable.
いいえ、_Rx_ 変数を使う特定のWidgetだけが更新されます。
So, **GetX** only updates the screen, when the _Rx_ variable changes it's value.
言い換えるなら、**GetX**は _Rx_ 変数の値が変化したときだけ画面更新をしてくれるということです。
```
```dart
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.
**GetX()**は何を更新して何をしないのか、の**細かい**コントロールが可能です。
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.
すべての更新するのでそのようなコントロールが不要な場合は、`GetBuilder` を検討してください。
これはわずか数行のコードで作られた、状態更新のためのシンプルなビルダーです。(`setState()`のようにブロックで)
CPUへの影響を最小限にするために作られており、単一の目的(_状態_ の再構築)を果たすため、可能な限りリソース消費を抑えました。
If you need a **powerful** State Manager, you can't go wrong with **GetX**.
**強力な** 状態管理のソリューションを求めているなら、**GetX**で間違いはありません。
It doesn't work with variables, but __flows__, everything in it are `Streams` under the hood.
変数をそのまま扱うことはできませんが、内部では `Stream` としてデータが扱われています。
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`.
すべてが `Stream` なので、_RxDart_ を組み合わせることも可能ですし、
"_Rx_ 変数" のイベントや状態を監視することも可能です。
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` .
GetXは _MobX_ より簡単で、コード自動生成や記述量を減らした_BLoC_ 型アプローチと言えるかもしれません。
値の末尾に `.obs` を付けるだけで**なんでも** _"Observable(監視可能)"_ にできるのです。
### Maximum performance:
### パフォーマンスの最大化
In addition to having a smart algorithm for minimal rebuilds, **GetX** uses comparators
to make sure the State has changed.
ビルドを最小限に抑えるための賢いアルゴリズムに加えて、
**GetX**はコンパレーターを使用して状態が変更されたことを確認します。
If you experience any errors in your app, and send a duplicate change of State,
**GetX** will ensure it will not crash.
アプリでなにかしらのエラーが発生し、状態が変更された情報を
二重に送信してしまったとしても**GetX**はクラッシュを防いでくれます。
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.
**GetX**では値が変化したときにはじめて「状態」が変化するためです。
これが **GetX** と _MobX の `computed`_ を使う際の主な違いです。
2つの __Observable__ を組み合わせて一つが変化したとき、それを監視しているオブジェクトも変化します。
With **GetX**, if you join two variables, `GetX()` (similar to `Observer()` ) will only rebuild if it implies a real change of State.
これは `GetX()` (`Observer()`のようなもの) において2つの変数を組み合わせた場合においても、
それが本当に状態の変化を意味するときだけWidgetの更新が行われるということでもあります。
### Declaring a reactive variable
### リアクティブな変数の宣言
You have 3 ways to turn a variable into an "observable".
変数を "Observable" にする方法は3つあります。
1 - The first is using **`Rx{Type}`**.
1 - **`Rx{Type}`** を使用する
``` dart
// initial value is recommended, but not mandatory
// 初期値を入れることを推奨しますが、必須ではありません
final name = RxString('');
final isLogged = RxBool(false);
final count = RxInt(0);
... ... @@ -163,7 +163,7 @@ final items = RxList<String>([]);
final myMap = RxMap<String, int>({});
```
2 - The second is to use **`Rx`** and use Darts Generics, `Rx<Type>`
2 - **`Rx`** とジェネリクスによる型指定の組み合わせ
``` dart
final name = Rx<String>('');
... ... @@ -174,11 +174,11 @@ final number = Rx<Num>(0);
final items = Rx<List<String>>([]);
final myMap = Rx<Map<String, int>>({});
// Custom classes - it can be any class, literally
// 任意の型を指定可能 - どんなクラスでもOK
final user = Rx<User>();
```
3 - The third, more practical, easier and preferred approach, just add **`.obs`** as a property of your `value` :
3 - 最も実用的で簡単な方法として、**`.obs`** を値に付ける
``` dart
final name = ''.obs;
... ... @@ -189,31 +189,31 @@ 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**.
ご存知の通り、_Dart_ は現在 _null safety_ へ移行しているところです。
それに備えるために今後は _Rx_ 変数は常に**初期値**を設定してください。
> Transforming a variable into an _observable_ + _initial value_ with **GetX** is the simplest, and most practical approach.
> **GetX** で変数を _Observable_ にしつつ _初期値_ を設定するのはとても簡単です。
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_).
変数の末尾に `.obs` を付ける。**それだけ。**
めでたく Observable とそのプロパティ `.value` (つまり _初期値_)ができました。
### Using the values in the view
### Observableの値をビュー内で使う
``` dart
// controller file
// Controllerクラス
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");
... ... @@ -234,37 +234,38 @@ GetX<Controller>(
),
```
If we increment `count1.value++` , it will print:
`count1.value++` を実行すると、以下の通りprintされます。
* `count 1 rebuild`
* `count 3 rebuild`
because `count1` has a value of `1` , and `1 + 0 = 1` , changing the `sum` getter value.
なぜなら `count1` の値が `1` に変わり、それに伴ってgetter `sum` の値にも `1 + 0 = 1` と変化が起こるからです。
If we change `count2.value++` , it will print:
今度は `count2.value++` を実行してみましょう。
* `count 2 rebuild`
* `count 3 rebuild`
because `count2.value` changed, and the result of the `sum` is now `2` .
もうおわかりですね。これは `count2.value` が変わり、その結果 `sum` が `2` になったからです。
* NOTE: By default, the very first event will rebuild the widget, even if it is the same `value`.
* 注: デフォルト仕様では、`value` に変化がなかったとしても、それが最初のイベントであればWidgetを更新します。
This behavior exists due to Boolean variables.
この仕様はbool変数の性質から来るものです。
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` .
そして、isLogged(ユーザーがログインしたかどうか)の変化をトリガーにever関数内のコールバックfireRouteを呼び出したいとします。
``` dart
@override
onInit() async {
// everは引数1が変化するたびに引数2を実行するリスナー
ever(isLogged, fireRoute);
isLogged.value = await Preferences.hasToken();
}
... ... @@ -278,26 +279,26 @@ fireRoute(logged) {
}
```
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` .
もし `hasToken` が `false` なら `isLogged` に変化はありません。すると `ever()` のコールバックは永遠に呼び出されないことになります。
このような挙動を防ぐために _Observable_ への最初の更新は、それがたとえ同じ `.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.
Getにはさらに洗練された「状態」のコントロール方法があります。イベント(Listへのオブジェクト追加など)に対して条件を付けることが可能です。
``` dart
// First parameter: condition, must return true or false.
// Second parameter: the new value to apply if the condition is true.
// 引数1: Listにオブジェクトを加える条件。trueかfalseを返すこと
// 引数2: 条件がtrueの場合に加える新しいオブジェクト
list.addIf(item < limit, item);
```
Without decorations, without a code generator, without complications :smile:
最低限のコードで、コード生成ツールも使わず、とても簡単ですね :smile:
Do you know Flutter's counter app? Your Controller class might look like this:
カウンターアプリもこのようにシンプルに実現できます。
``` dart
class CountController extends GetxController {
... ... @@ -305,19 +306,19 @@ class CountController extends GetxController {
}
```
With a simple:
Controllerを設定して、下記を実行するだけ。
``` dart
controller.count.value++
```
You could update the counter variable in your UI, regardless of where it is stored.
UIの数字が置き換わりましたね。このようにアプリのどこであっても更新をかけることができます。
### Where .obs can be used
### .obsの使いどころ
You can transform anything on obs. Here are two ways of doing it:
.obs を使うことでどんなものもObservableにすることができます。方法は2つ。
* You can convert your class values to obs
* クラスのインスタンス変数をobsに変換する
``` dart
class RxUser {
... ... @@ -326,7 +327,7 @@ class RxUser {
}
```
* or you can convert the entire class to be an observable
* クラスのインスタンスを丸々obsに変換する
``` dart
class User {
... ... @@ -335,181 +336,181 @@ class User {
var age;
}
// when instantianting:
// インスタンス化の際
final user = User(name: "Camila", age: 18).obs;
```
### Note about Lists
### List(Rx)に関する補足
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.
List(Rx)はその中のオブジェクトと同様、監視可能(Observable)です。そのためオブジェクトを追加すると、List(Rx)に依存するWidgetは自動更新されます。
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.
またList(Rx)をListとするために ".value" を使う必要はありません。DartのAPIがこれを可能にしてくれました。ただ、残念ながら他のStringやintのようなプリミティブ型は拡張ができないため、.value を使う必要があります。getterやsetterを活用するのであればあまり問題になりませんが。
``` dart
// On the controller
// 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
// ビュークラス
Text(controller.title.value), // Stringの場合は .value が必要
ListView.builder (
itemCount: controller.list.length // lists don't need it
itemCount: controller.list.length // Listの場合は不要
)
```
When you are making your own classes observable, there is a different way to update them:
カスタムのクラスをObservableにした場合は、様々な方法で値を更新することができます。
``` dart
// on the model file
// we are going to make the entire class observable instead of each attribute
// モデルクラス
// 属性をobsにするやり方ではなく、クラス全体をobsにする方法を採ります
class User() {
User({this.name = '', this.age = 0});
String name;
int age;
}
// on the controller file
// Controllerクラス
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変数を更新するときはこのようなメソッドを作ります
user.update( (user) { // このパラメーターは更新するオブジェクトそのもの
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)
// .value を使わずにモデルのプロパティにアクセスすることも可能です
user().name; // userがUserではないことに注目。user()でUserを受け取れます。
```
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.
ListのsetAllやsetRangeメソッドの代わりに、"assign" "assignAll" APIを使っていただくことも可能です。
"assign" APIはListの内容をクリアした後に、指定した単独のオブジェクトを追加してくれます。
"assignAll" APIはそのIterable版です。
### Why i have to use .value
### なぜ「.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.
ちょっとしたアノテーションとコード生成ツールを使って`String`や`int`で `.value` を使わなくて済むようにもすることはできますが、このライブラリの目的は「外部依存パッケージを減らす」ことです。私たちは、外部パッケージを必要としない、必須ツール(Route、依存オブジェクト、状態の管理)が揃った開発環境を軽量かつシンプルな方法で提供したいと考えています。
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.
まさに pubspecに3文字(get)とコロンを加えて、プログラミングを始めることができるのです。Route管理から状態管理まで、必要なソリューションが標準装備されています。GetXはシンプルさ、生産性、高いパフォーマンスを目指します。
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.
`.value` が嫌でコード生成ツールを使いたいという方には、MobXは素晴らしいライブラリだと思いますし、Getと併用することもできます。逆に多くの外部パッケージに依存したくない方、パッケージ間の互換性を気にしたくない方、状態管理ツールや依存オブジェクトから状態更新エラーが出ているかどうかを気にせずプログラミングをしたい方、依存するControllerクラスのインスタンスがあるかどうかを都度都度心配したくない方にとってはGetはまさに最適です。
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.
MobXのコード生成や、BLoCのボイラープレートコードが気にならないのであれば、Route管理にだけでもGetをお使いいただけるとうれしいです。GetのSEMとRSMは必要に迫られて生まれたものです。私の会社で以前、90以上のControllerを持つプロジェクトがあり、それなりの性能のマシンでflutter cleanを行った後でさえ、コード生成ツールがタスクを完了するのに30分以上かかりました。もしあなたが大きなプロジェクトに関わっており、コード生成ツールが問題になっているのであれば、Getを検討してみてください。
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.
もちろん、コード生成ツールをGetXに導入したい方が実際にツールを作成してプロジェクトに貢献した場合は、このReadMeに代替ソリューションとして掲載させていただきます。私はすべての開発者のニーズをかなえたいわけではありませんが、今はこの質問に対しては、「すでに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.
GetX()の代わりにObx()を使用することもできます。ObxはWidgetを生成する匿名関数をパラメーターに持ちます。複数のControllerに対応することができますが、自身はControllerのインスタンスを持たず、型指定もできません。そのため別途Controllerのインスタンスを作るか、`Get.find<Controller>()` でインスタンスを探しておく必要があります。
### Workers
### Worker
Workers will assist you, triggering specific callbacks when an event occurs.
Worker はイベント発生に伴って指定したコールバックを呼び出すことができます。
``` dart
/// Called every time `count1` changes.
/// `count1` が更新されるたびに第2引数のコールバックが実行される
ever(count1, (_) => print("$_ has been changed"));
/// Called only first time the variable $_ is changed
/// `count1` の最初の更新時のみ実行される
once(count1, (_) => print("$_ was changed once"));
/// Anti DDos - Called every time the user stops typing for 1 second, for example.
/// DDoS攻撃対策に最適。たとえば、ユーザーが打鍵やクリックを止めて1秒後に実行など
debounce(count1, (_) => print("debouce$_"), time: Duration(seconds: 1));
/// Ignore all changes within 1 second.
/// 1秒以内の連続更新はすべて無視して実行しない
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.
すべてのWorker(`debounce` 以外) は `condition` パラメーターを持ちます。`condition` は `bool` でも `bool` を返すコールバックでも構いません。
この `condition` が Worker のコールバックを実行するかどうかを決めています。
また Worker は `Worker` インスタンスを返します。これは `dispose()` などを通じて Worker を破棄するときに使用します。
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.
は _Rx_ 変数が新しい値になるたびに呼ばれます。
* **`everAll`**
Much like `ever` , but it takes a `List` of _Rx_ values Called every time its variable is changed. That's it.
`ever` とほぼ同じですが、_Rx_ 変数の `List` を受け取ります。いずれかの値が更新されれば、その更新後の値を受け取ってコールバックが実行されます。
* **`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.
'debounce' は検索機能などで導入するととても有益です。たとえば、ユーザーがタイピングを止めたときにのみAPIを呼び出したいときに使います。ユーザーが "Jonny" と入れたときに 5回も APIに問い合わせを行うのは避けたいですよね。Getなら "debounce" があるので大丈夫です。
* **`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.
`interval` は debounce とは異なります。ユーザーが1秒間に1000回変数に変更を加えた場合、debounceが一定期間経過後(デフォルトは800ミリ秒)に最後の変更イベントだけ送信するのに対して、intervalは代わりに一定期間の間のユーザーによるアクションをすべて無視します。intervalは1秒ごとにイベントを送信しており、3秒に設定した場合は1分間に20個のイベントを送信します。これはユーザーがキーやマウスを連打することで何かしらの報酬を得られる場合に、その悪用を避けるために使用できます(ユーザーが何かをクリックしてコインを獲得できるとします。たとえ何秒かかったとしても300回クリックすれば300枚のコインを得ることができてしまいます。intervalを使用してインターバルを3秒に設定した場合は、何回クリックしようが1分間で得られるコインの上限は20枚になります)。一方のdebounceはアンチDDosや、検索のように変更を加えるたびにonChangeからAPI問い合わせが発生するような機能に適しています。ユーザーが入力し終わるのを待ってリクエストを送信するのです。debounceを前述のコイン獲得のケースで使用した場合、ユーザーはコインを1枚しか獲得できません。これは指定した期間、ユーザーが動作を「一時停止」したときにのみ実行されるからです。
* 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).
* 注: Workerを使用する場合は、Controllerなどを起動するときに次のいずれかの方法で登録する必要があります。onInit(推奨)内、クラスのコンストラクタ、またはStatefulWidgetのinitState内(この方法は推奨しませんが、副作用はないはずです)。
## 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.
GetはChangeNotifierを使わない軽量かつシンプルな状態管理機能を有しています。特にFlutterに慣れていない方のニーズを満たし、大規模なアプリケーションでも問題を起こすことがないと信じています。
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.
GetBuilderは複数の状態を扱う場面で使われることを想定して作られました。たとえばショッピングカートに30個の商品があるとします。そしてあなたが商品を一つ削除すると同時に、カートのリストが更新され、合計金額が更新され、アイテム数を示すバッジが更新されます。GetBuilderはこのようなユースケースに最適です。というのも、GetBuilderは状態をControllerで束ねてそのControllerに依存するすべてのWidgetを一度に更新させることができるからです。
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.
それらとは独立したControllerが必要な場合は、GetBuilderのidプロパティに専用IDを割り当てるか、GetXを使ってください。ケースバイケースですが、そのような「独立した」Widetが多いほど GetX() のパフォーマンスが際立ち、複数の状態変化がありそれに伴うWidgetの更新が多いほど GetBuilder() のパフォーマンスが勝ることを覚えておいてください。
### Advantages
### 利点
1. Update only the required widgets.
1. 必要なWidgetのみ更新される。
2. Does not use changeNotifier, it is the state manager that uses less memory (close to 0mb).
2. ChangeNotifierを使わず、メモリ使用量が少ない。
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.
3. StatefulWidgetのことはもう忘れましょう。Getでは必要ありません。他の状態管理ライブラリではStatefulWidgetを使用することがあるでしょう。しかしAppBarやScaffoldなどクラス内のほとんどのWidgetがStatelessであるにも関わらず、StatefulなWidgetの状態だけを保持する代わりに、クラス全体の状態を保持しているのはなぜでしょうか?Getならクラス全体をStatelessにすることができます。更新が必要なコンポーネントは GetBuilder などで囲むことで「状態」が保持されます。
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.
4. プロジェクトを整理しましょう!ControllerはUIの中にあってはいけません。TextEditControllerなどの類はすべてControllerクラスに配置してしまいましょう。
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.
5. Widgetのレンダリングが開始されると同時にイベントを実行してWidgetを更新させる必要がありますか?GetBuilderにはStatefulWidgetと同様の「initState」プロパティがあり、そこからControllerのイベントを直接呼び出すことができます。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.
6. StreamやTimerのインスタンスを破棄したい場合はGetBuilderのdisposeプロパティを利用してください。Widgetが破棄されると同時にイベントを呼び出すことができます。
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).
7. GetXとStreamController / StreamBuilderを組み合わせるなどしてStreamを普通に使っていただいても問題ありませんが、必要なときに限って使うことをおすすめします。Streamのメモリ消費は適度であり、リアクティブプログラミングは美しいですが、たとえば30ものStreamを同時に立ち上げることを考えてみてください。これはChangeNotifierを使うよりもよくないことのように思います。
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.
8. 必要以上にRAMを使わずWidgetを更新します。GetはGetBuilderのクリエーターIDのみを保存し、必要に応じてGetBuilderを更新します。何千ものGetBuilderを作成したとしても、ID保存のためのメモリ消費量は非常に少ないです。GetBuilderを新規に作成するということは、実際にはクリエーターIDを持つ GetBuilder の状態を共有しているに過ぎないためです。GetBuilderごとに状態が新たに作成されるわけではないため、特に大規模なアプリケーションでは多くのRAMを節約できます。基本的にGetXで作成するアプリケーションは全体的にStatelessであり、いくつかのStatefulなWidget(GetBuilder内のWidget)は単一の状態を持っているため、一つを更新すればすべてが更新されます。
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.
9. Getはアプリ全体の流れをよく把握しており、Controllerをメモリから破棄するタイミングを正確に知っています。実際の破棄はGetがやってくれるため、開発者が心配する必要はありません。
### Usage
### 使用例
``` dart
// Create controller class and extends GetxController
// Controllerクラスを作成してGetxControllerを継承しましょう
class Controller extends GetxController {
int counter = 0;
void increment() {
counter++;
update(); // use update() to update counter variable on UI when increment be called
update();
// increment 実行時にcounter変数に依存するUIを更新。
// GetBuilderを使うWidgetの場合はupdate()が必要。
}
}
// On your Stateless/Stateful class, use GetBuilder to update Text when increment be called
// ビュー側のクラスでGetBuilderを使ってcounter変数を組み込む
GetBuilder<Controller>(
init: Controller(), // INIT IT ONLY THE FIRST TIME
init: Controller(), // 最初に使用するときのみ初期化
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.
// Controllerの初期化は最初の1回だけ行ってください。同じControllerを再度 GetBuilder / GetX で使用する場合は初期化する必要はありません。コントローラは、それを「init」とマークしたウィジェットがデプロイされると同時に、自動的にメモリから削除されます。Getがすべて自動で行ってくれるので、何も心配することはありません。同じControllerを2つ立ち上げることがないよう、それだけご注意ください。
```
**Done!**
**最後に**
* You have already learned how to manage states with Get.
* 以上、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.
* 注: もっと柔軟に管理する手法として、initプロパティを使わない方法もあります。Bindingsを継承したクラスを作成し、dependenciesメソッドをoverrideしてその中でGet.put()でControllerを注入してください(複数可)。このクラスとUI側のクラスを紐づけることでControllerをそのRoute内で使用できます。そしてそのControllerを初めて使用するとき、Getはdependencies内を見て初期化を実行してくれます。このlazy(遅延、消極的)ロードを維持しつつ、不要になったControllerは破棄し続けます。具体的な仕組みについてはpub.devの例をご参照ください。
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):
Routeを移動して以前使用したControllerのデータが必要になった場合は、再度GetBuilderを使用してください。initする必要はありません。
``` dart
class OtherClass extends StatelessWidget {
... ... @@ -526,16 +527,16 @@ class OtherClass extends StatelessWidget {
```
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>()` )
GetBuilderの外でControllerを使用する場合は、Controller内にgetterを作成しておくと便利です。Controller.to で呼び出しましょう。(もしくは `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
/// 記述量を省くためにstaticメソッドにすることをおすすめします。
/// staticメソッド使う場合 → Controller.to.increment();
/// 使わない場合 → Get.find<Controller>().increment();
/// どちらを使ってもパフォーマンスに影響があったり副作用が出たりはしません。前者は型の指定が不要という違いがあるだけです
static Controller get to => Get.find(); // これを追加
int counter = 0;
void increment() {
... ... @@ -545,35 +546,34 @@ class Controller extends GetxController {
}
```
And then you can access your controller directly, that way:
これで以下のようにControllerに直接アクセスできます。
``` 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.
FloatingActionButton を押すと counter変数 に依存するWidgetがすべて自動的に更新されます。
### How it handles controllers
### Controllerインスタンスの扱い
Let's say we have this:
次のような画面の流れがあるとします。
`Class a => Class B (has controller X) => Class C (has controller X)`
`画面A => 画面B (Controller X を使用) => 画面C (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.
画面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" を追加してください。
### You won't need StatefulWidgets anymore
### StatefulWidgetsはもういらない
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.
StatefulWidgetsを使用すると、画面全体の状態を不必要に保存することになります。ウィジェットを最小限に再構築する必要がある場合は、Consumer/Observer/BlocProvider/GetBuilder/GetX/Obxの中に埋め込むことになりますが、それは別のStatefulWidgetになります。
StatefulWidgetはStatelessWidgetよりも多くのRAMが割り当てられます。これは1つや2つのStatefulWidgetでは大きな違いは産まないかもしれませんが、それが100もあった場合は確実に違いが出ます。
TickerProviderStateMixinのようなMixinを使用する必要がない限り、GetでStatefulWidgetを使用する必要はありません。
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;
たとえばinitState()やdispose()メソッドなど、StatefulWidgetのメソッドをGetBuilderから直接呼び出すことも可能です。
``` dart
GetBuilder<Controller>(
... ... @@ -583,7 +583,7 @@ GetBuilder<Controller>(
),
```
A much better approach than this is to use the onInit() and onClose() method directly from your controller.
しかし、これよりもベターなアプローチはControllerの中で直接 onInit() や onClose() メソッドを呼び出すことです。
``` dart
@override
... ... @@ -593,24 +593,23 @@ void 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.
* 注: コンストラクタを通じてControllerを立ち上げる必要はありません。このようなプラクティスは、パフォーマンス重視であるGetのControllerの作成や割り当ての原理、考え方から外れてしまいます(コンストラクタ経由でインスタンスを作成すれば、実際に使用される前の段階でControllerを生成し、メモリを割り当てることになります)。onInit() と onClose() メソッドはこのために作られたもので、Controllerのインスタンスが作成されたとき、または初めて使用されたときに呼び出されます(Get.lazyPutを使用しているか否か次第)。たとえば、データを取得するためにAPIを呼び出したい場合は initState/dispose の代わりに onInit() を使用し、Streamを閉じるなどのコマンドを実行する必要がある場合は onClose() を使用してください。
### Why it exists
### Getの目的
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.
このパッケージの目的は、Routeのナビゲーション、依存オブジェクトと状態の管理のための完全なソリューションを、開発者が外部パッケージに極力依存せずに済むような形で提供し、高度なコード分離性(デカップリング)を実現することです。それを確実なものとするため、Getはあらゆる高レベルおよび低レベルのFlutter APIを取り込んでいます。これによりビューとロジックを切り分けることが容易になり、UIチームにはWidgetの構築に集中してもらい、ビジネスロジック担当チームにはロジックに集中してもらうことができます。Getを使うことでよりクリーンな作業環境を構築することができるのです。
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.
要するに、initState内でメソッドを呼び出してパラメーターを通じてControllerにデータを送信する必要も、そのためにControllerのコンストラクタを使用する必要もありません。Getには必要なタイミングでサービスを呼び出してくれう onInit() メソッドがあります。
Controllerが不要になれば、onClose() メソッドがジャストなタイミングでメモリから破棄してくれます。これにより、ビューとビジネスロジックを分離することができるのです。
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:
GetxController 内に dispose() メソッドがあっても何も起こらないので記述しないでください。ControllerはWidgetではないので「dispose」できません。たとえばController内でStreamを使用していてそれを閉じたい場合は、以下のように onClose() メソッドにコードを記述してください。
``` dart
class Controller extends GetxController {
StreamController<User> user = StreamController<User>();
StreamController<String> name = StreamController<String>();
/// close stream = onClose method, not dispose.
/// Streamを閉じる場合は dispose() ではなく onClose()
@override
void onClose() {
user.close();
... ... @@ -620,132 +619,131 @@ class Controller extends GetxController {
}
```
Controller life cycle:
Controllerのライフサイクルについて。
* 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.
* onInit() はControllerが作成されたタイミングで実行されます。
* onClose() は onDelete() メソッドが実行される直前のタイミングで実行されます。
* Controllerが削除されるとそのAPIにアクセスすることはできません。文字通りメモリからの削除だからです。削除のトレースログも残りません。
### Other ways of using it
### Controllerの様々な使用方法
You can use Controller instance directly on GetBuilder value:
ControllerインスタンスはGetBuilderのvalueを通じて使用することができます。
``` dart
GetBuilder<Controller>(
init: Controller(),
builder: (value) => Text(
'${value.counter}', //here
'${value.counter}', // ここ
),
),
```
You may also need an instance of your controller outside of your GetBuilder, and you can use these approaches to achieve this:
GetBuilderの外でControllerインスタンスを使う場合は、このアプローチをおすすめします。
``` 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
// ビュー側で
GetBuilder<Controller>(
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Controller.to.counter}', //here
'${Controller.to.counter}', // ここ
)
),
```
or
もしくは
``` dart
class Controller extends GetxController {
// static Controller get to => Get.find(); // with no static get
// static get を省き、
[...]
}
// on stateful/stateless class
GetBuilder<Controller>(
init: Controller(), // use it only first time on each controller
// ビュー側で
GetBuilder<Controller>(
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Get.find<Controller>().counter}', //here
'${Get.find<Controller>().counter}', // ここ
),
),
```
* 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:
* get_it や modular など他の依存オブジェクト管理ライブラリを使用しているため、単にControllerのインスタンスを渡したいだけの場合は、このような「非正規」な方法もあります。
``` dart
Controller controller = Controller();
[...]
GetBuilder<Controller>(
init: controller, //here
init: controller, // ここ
builder: (_) => Text(
'${controller.counter}', // here
'${controller.counter}', // ここ
),
),
```
### Unique IDs
### ユニークIDの設定
If you want to refine a widget's update control with GetBuilder, you can assign them unique IDs:
GetBuilderを使ってWidgetの更新をコントロールしたい場合は、このようにユニークIDを振ってください。
``` dart
GetBuilder<Controller>(
id: 'text'
init: Controller(), // use it only first time on each controller
init: Controller(), // 最初に使うときだけ必要
builder: (_) => Text(
'${Get.find<Controller>().counter}', //here
'${Get.find<Controller>().counter}', // ここ
),
),
```
And update it this form:
そして以下のようにWidgetを更新します。
``` 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).
GetXはこの更新を自動で行ってくれます。指定したIDを持ち、その変数に依存するWidgetのみを更新します。また変数を前の値と同じ値に変更しても、それが状態の変化を意味しない場合はメモリとCPUサイクルを節約するためにWidgetを更新しません (画面に 3 が表示されているときに、変数を再び 3 に変更したとします。このような場合にWidgetを更新する状態管理ソリューションも存在しますが、GetXでは実際に状態が変更された場合にのみ更新されます)。
## 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.
MixinBuilderはObxとGetBuilderを併用したいというリクエストから発想して作られました。これは ".obs" 変数の変更によるリアクティブな更新と、update() メソッドによるメカニカルな更新の両方を混在可能にします。ただし、GetBuiler / GetX / Obx / MixinBuilder の4つの中で最もリソースを消費するWidgetです。というのも、Widgetからのイベントを検知するためのSubscriptionに加えて、Controller自身のupdateメソッドも購読する必要があるからです。
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.
MixinBuilderに使用するControllerクラスには、変数を `.obs`(Observable)とするかどうかに関わらず、GetxControllerを継承したものを使用してください。GetxControllerにはライフサイクルがあり、onInit() および onClose() メソッドでイベントを「開始」したり「終了」したりすることができます。
## 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.
`StateMixin<T>` を使うことでさらに `UI` の「状態」を便利に扱うことができます。
`with` を使って `StateMixin<T>` をControllerにミックスインしてください。Tにはモデルのクラス名が入ります。
``` 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:
状態を変更するには `change()` メソッドを使ってください。
パラメーターにはビューに渡すデータと「状態」をセットします。
```dart
change(data, status: RxStatus.success());
```
RxStatus allow these status:
RxStatus の「状態」は以下の4つです。
``` dart
RxStatus.loading();
RxStatus.success();
RxStatus.empty();
RxStatus.error('message');
RxStatus.loading(); // ロード中
RxStatus.success(); // ロード成功
RxStatus.empty(); // データが空
RxStatus.error('message'); // エラー
```
To represent it in the UI, use:
それぞれの「状態」をUIで表すには以下のようにします。
```dart
class OtherClass extends GetView<Controller> {
... ... @@ -755,35 +753,35 @@ class OtherClass extends GetView<Controller> {
body: controller.obx(
(state)=>Text(state.name),
// here you can put your custom loading indicator, but
// by default would be Center(child:CircularProgressIndicator())
// ここはカスタムのロードインジケーターでも可能ですが、
// デフォルトは 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))
// ここもカスタムのエラーWidgetでも構いませんが、
// デフォルトは Center(child:Text(error))
onError: (error)=>Text(error),
),
);
}
```
## GetBuilder vs GetX vs Obx vs MixinBuilder
## GetBuilder VS GetX VS Obx VS MixinBuilder
In a decade working with programming I was able to learn some valuable lessons.
私は10年間プログラミングに携わってきて、いくつか貴重な教訓を得ることができました。
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.
リアクティブプログラミングに初めて触れたとき、「おお、これはすごい」と感嘆せずにはいられませんでしたし、実際にすごいものでした。
しかし、リアクティブプログラミングはすべての状況に適しているわけではありません。多くの場合、必要なのは2,3のWidgetの状態を同時に更新すること、またはローカルでの一時的な状態の変更であり、これらの場合はリアクティブである必要はありません。
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.
リアクティブプログラミングのRAM消費量の多さは、必要なときだけ、かつ1つのWidgetだけ同時に更新するようすることである程度補うことができます。ただ、たとえば80ものオブジェクトを持つリストがあったとして、それぞれが複数のStreamを持つのは得策ではありません。Dartのインスペクターを開いて、StreamBuilderがどれだけRAMを消費しているか見てみてください。私が伝えたいことを理解してもらえると思います。
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.
そのことを念頭に私はシンプルな状態管理ソリューションを作りました。このシンプルさに期待することは、リソース面で経済的である点、Widget単位ではなくブロック単位で状態を更新できる点であるべきです。
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).
GetBuilderはRAM消費の面で最も経済的なソリューションだと信じています(もしあれば、ぜひ教えてください)。
However, GetBuilder is still a mechanical state manager, you need to call update() just like you would need to call Provider's notifyListeners().
しかし、GetBuilderは依然として update() により更新がかかるスタイルのメカニカルな状態管理ソリューションであり、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() は先進的な状態管理の手法を提供するために作られました。必要なものを必要なときだけ更新し、エラーが発生してユーザーが300ものイベントを同時に送信したとしても、GetX() は状態の変化をフィルタリングして画面を更新してくれます。
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.
GetX() は他のリアクティブな状態管理ソリューションに比べて経済的であることに変わりはありませんが、GetBuilder() よりは少しだけ多くのRAMを消費します。その点を考慮し、リソース消費を最大限活かすことを目指して Obx() は開発されました。GetX() や GetBuilder() と異なり、Obx() の中でControllerを初期化することはできません。Obx() は、子Widgetからの更新イベントを受け取る Stream購読Widgetでしかありません。GetX() よりは経済的ですが、GetBuilder() には負けます。GetBuilder() はWidgetのハッシュ値と状態のsetterを保持しているだけなので、これはある意味当然です。Obx() はControllerの型を指定する必要がなく、複数の異なるコントローラからの変更を聞くことができます。ただし、Obx() の外かBindingsで事前にControllerを初期化しておく必要があります。
... ...