diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 1fc11d547..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - // Use o IntelliSense para aprender sobre possíveis atributos. - // Passe o mouse para ver as descrições dos atributos existentes. - // Para obter mais informações, visite: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "getx", - "cwd": "getx", - "request": "launch", - "type": "dart" - }, - { - "name": "example debug", - "cwd": "getx/example", - "request": "launch", - "flutterMode": "debug", - "type": "dart" - }, - { - "name": "example profile", - "cwd": "getx/example", - "request": "launch", - "flutterMode": "profile", - "type": "dart" - }, - { - "name": "example release", - "cwd": "getx/example", - "request": "launch", - "flutterMode": "release", - "type": "dart" - }, - { - "name": "get_core", - "cwd": "packages/get_core", - "request": "launch", - "type": "dart" - }, - { - "name": "get_instance", - "cwd": "packages/get_instance", - "request": "launch", - "type": "dart" - }, - { - "name": "get_navigation", - "cwd": "packages/get_navigation", - "request": "launch", - "type": "dart" - }, - { - "name": "get_rx", - "cwd": "packages/get_rx", - "request": "launch", - "type": "dart" - }, - { - "name": "get_state_manager", - "cwd": "packages/get_state_manager", - "request": "launch", - "type": "dart" - }, - { - "name": "get_test", - "cwd": "packages/get_test", - "request": "launch", - "type": "dart" - }, - { - "name": "get_utils", - "cwd": "packages/get_utils", - "request": "launch", - "type": "dart" - } - ] -} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df5ee436..6d01bc79b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## [3.13.2] +- Reunification of the package. +During the 2 week period, we try to keep this package as a compilation of smaller packages. We were successful in separating, getx is well decoupled and it was only necessary to send the internal folders as packages to pub.dev, however, it became very complicated to contribute to the package. This is because it was necessary to clone the repository, replace all pubspec packages with local paths, and after modification, return the original paths to do the PR. With that, the frequency of updates, which was about 4 to 5 days, became almost 2 weeks, and this is not legal for a community as active as Getx, which uses this package precisely in addition to being modern and performance, be constantly improving. This led contributors to the conclusion that getx works best together. +Additional packages will continue to be maintained, and will have the same base as the main package, however, development will take place in the full and main package, and as the addition of new features or bug fixes arrives, we will migrate to the individual packages . Getx reached the mark of 50 contributors today, more than 1500 likes in the pub, and will continue to make development easy. + ## [3.13.1] - Remove spaces whitespaces from dart files - diff --git a/README-es.md b/README-es.md index 88bca7bd9..40f249ac4 100644 --- a/README-es.md +++ b/README-es.md @@ -1,4 +1,4 @@ -![](get.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png) *Idiomas: Español (este archivo), [Lengua china](README.zh-cn.md), [Inglés](README.md), [Portugués de Brasil](README.pt-br.md), [Polaco](README.pl.md).* @@ -13,30 +13,30 @@ Buy Me A Coffee -![](getx.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png)

Lamentamos la inconsistencia en la traducción. El paquete GetX se actualiza con bastante frecuencia y es posible que las traducciones a documentos no sean tan rápidas. Entonces, para que esta documentación aún tenga todo el contenido, dejaré aquí todos los textos nuevos sin traducir (considero que es mejor tener los documentos en inglés que no tenerlos), por lo que si alguien quiere traducir, sería de gran ayuda 😁

- [Communication and support channels:](#communication-and-support-channels) - [Sobre GetX](#sobre-getx) - [Como contribuir](#como-contribuir) -- [Instalando](#installing) -- [Proyecto Counter en GetX](#proyeto-counter-no-getx) +- [Installing](#installing) +- [Proyecto Counter no GetX](#proyecto-counter-no-getx) - [Los tres pilares](#los-tres-pilares) - [Gestión del Estado](#gestión-del-estado) - - [STATE_MANAGER Reactivo](#reactivo-state_manager) + - [Reactivo STATE_MANAGER](#reactivo-state_manager) - [Más detalles sobre la gestión del estado.](#más-detalles-sobre-la-gestión-del-estado) - - [Explicación en video sobre state management](#video-explanation-about-state-management) + - [Explicación en video sobre state management](#explicación-en-video-sobre-state-management) - [Gestión de Rutas](#gestión-de-rutas) - [Más detalles sobre la gestión de rutas.](#más-detalles-sobre-la-gestión-de-rutas) - - [Explicación del video](#video-explanation) + - [Explicación del video](#explicación-del-video) - [Gestión de dependencias](#gestión-de-dependencias) - [Más detalles sobre la gestión de dependencias.](#más-detalles-sobre-la-gestión-de-dependencias) -- [Utilidades](#utils) +- [Utilidades](#utilidades) - [Cambiar de tema](#cambiar-de-tema) - [Otras API avanzadas y configuraciones manuales](#otras-api-avanzadas-y-configuraciones-manuales) - [Configuraciones globales opcionales](#configuraciones-globales-opcionales) - - [Explicación en video de Other GetX Features](#video-explanation-of-other-getx-features) + - [Video explanation of Other GetX Features](#video-explanation-of-other-getx-features) - [Rompiendo cambios desde 2.0](#rompiendo-cambios-desde-20) - [¿Por qué Getx?](#por-qué-getx) @@ -155,7 +155,7 @@ class Other extends StatelessWidget { Resultado: -![](counter-app-gif.gif) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif) Este es un proyecto simple pero ya deja en claro cuán poderoso es GetX. A medida que su proyecto crezca, esta diferencia se volverá más significativa. GetX fue diseñado para trabajar con equipos, pero también simplifica el trabajo de un desarrollador individual. Mejore sus plazos, entregue todo a tiempo, sin perder rendimiento. GetX no es para todos, pero si te identificaste con esa frase, ¡GET es para ti! diff --git a/README.md b/README.md index 12f13aa14..e9a90018f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![](get.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png) _Languages: English (this file), [Chinese](README.zh-cn.md), [Brazilian Portuguese](README.pt-br.md), [Spanish](README-es.md),[Polish](README.pl.md)._ @@ -13,7 +13,7 @@ _Languages: English (this file), [Chinese](README.zh-cn.md), [Brazilian Portugue Buy Me A Coffee -![](getx.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png) - [About Get](#about-get) - [Installing](#installing) @@ -148,7 +148,7 @@ class Other extends StatelessWidget { Result: -![](counter-app-gif.gif) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif) This is a simple project but it already makes clear how powerful Get is. As your project grows, this difference will become more significant. diff --git a/README.pl.md b/README.pl.md index 3183de2f0..dfd71d0c8 100644 --- a/README.pl.md +++ b/README.pl.md @@ -1,4 +1,4 @@ -![](get.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png) *Languages: [English](README.md), [Język chiński](README.zh-cn.md), [Brazilian Portuguese](README.pt-br.md), [Spanish](README-es.md), Polish (Jesteś tu).* @@ -14,28 +14,28 @@ Buy Me A Coffee -![](getx.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png) - [Kanały komunikacji i wsparcia:](#kanały-komunikacji-i-wsparcia) - [Wprowadzenie](#wprowadzenie) - [Instalacja](#instalacja) - [Counter App z GetX](#counter-app-z-getx) -- [Trzy fialary](#trzy-filary) +- [Trzy filary](#trzy-filary) - [Menadżer stanu](#menadżer-stanu) - [Reaktywny menadżer stanu](#reaktywny-menadżer-stanu) - [Bardziej szczegółowo o menadżerze stanu](#bardziej-szczegółowo-o-menadżerze-stanu) - [Video tłumaczące użycie menadżera stanu](#video-tłumaczące-użycie-menadżera-stanu) - - [Zarzadzanie routami](#zarządzanie-routami) + - [Zarządzanie routami](#zarządzanie-routami) - [Więcej o routach](#więcej-o-routach) - [Video tłumaczące użycie](#video-tłumaczące-użycie) - [Zarządzanie dependencies](#zarządzanie-dependencies) - - [Bardziej szczefółowo o menadżerze dependencies](#bardziej-szczegółowo-o-menadżerze-dependencies) + - [Bardziej szczegółowo o menadżerze dependencies](#bardziej-szczegółowo-o-menadżerze-dependencies) - [Jak włożyć coś od siebie](#jak-włożyć-coś-od-siebie) - [Narzędzia](#narzędzia) - [Zmiana motywu](#zmiana-motywu) - - [Inne zaawansowane API](#inne-zaawansowane-api) + - [Inne zaawansowane API](#inne-zaawansowane-api) - [Opcjonalne globalne ustawienia i manualna konfiguracja](#opcjonalne-globalne-ustawienia-i-manualna-konfiguracja) - - [Video tłumaczace inne funkcjonalności GetX](#video-tłumaczące-inne-funkcjonalności-getx) + - [Video tłumaczące inne funkcjonalności GetX](#video-tłumaczące-inne-funkcjonalności-getx) - [Zmiany od 2.0](#zmiany-od-20) @@ -130,7 +130,7 @@ class Other extends StatelessWidget { ``` Wynik: -![](counter-app-gif.gif) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif) Jest to prosty projekt, ale już na jego przykładzie widać potęgę Get. Wzraz ze wzrostem rozmiaru aplikacji ta różnica tylko się powieksza. diff --git a/README.pt-br.md b/README.pt-br.md index 2912a1a18..88c2cb1d0 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -1,4 +1,4 @@ -![](get.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png) *Idiomas: [Inglês](README.md), [Língua chinesa](README.zh-cn.md), Português Brasileiro (este arquivo), [Espanhol](README-es.md), [Polaco](README.pl.md).* @@ -14,7 +14,7 @@ Buy Me A Coffee -![](getx.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png)

Pedimos desculpas por qualquer parte não traduzida aqui. O GetX™ é atualizado com muita frequência e as traduções podem não vir ao mesmo tempo. Então, para manter essa documentação pelo menos com tudo que a versão em inglês tem, eu vou deixar todos os textos não-traduzidos aqui (eu considero que é melhor ele estar lá em inglês do que não estar), então se alguém quiser traduzir, seria muito útil 😁

@@ -36,7 +36,7 @@ - [Traduções](#traduções) - [Usando traduções](#usando-traduções) - [Localidade](#localidade) - - [Alterar Local](#alterar-local) + - [Alterar local](#alterar-local) - [Localidade do sistema operacional](#localidade-do-sistema-operacional) - [Mudar tema (changeTheme)](#mudar-tema-changetheme) - [Outras APIs avançadas](#outras-apis-avançadas) @@ -44,17 +44,17 @@ - [Widgets de Estado Local](#widgets-de-estado-local) - [ValueBuilder](#valuebuilder) - [ObxValue](#obxvalue) + - [Explicação em vídeo sobre Outras Features do GetX](#explicação-em-vídeo-sobre-outras-features-do-getx) - [Dicas Úteis](#dicas-úteis) - [GetView](#getview) - [GetWidget](#getwidget) - [GetxService](#getxservice) - - [Explicação em vídeo sobre Outras Features do GetX](#explicação-em-vídeo-sobre-outras-features-do-getx) - [Breaking Changes da versão 2 para 3](#breaking-changes-da-versão-2-para-3) - [Tipagem Rx](#tipagem-rx) - [RxController e GetBuilder se uniram](#rxcontroller-e-getbuilder-se-uniram) - [Rotas nomeadas](#rotas-nomeadas) - - [Porque essa mudança](#porque-essa-mudança) -- [Por que GetX?](#por-que-getx) + - [Porque essa mudança?](#porque-essa-mudança) +- [Por que GetX™?](#por-que-getx) - [Comunidade](#comunidade) - [Canais da comunidade](#canais-da-comunidade) - [Como contribuir](#como-contribuir) @@ -147,7 +147,7 @@ class Outra extends StatelessWidget { Resultado: -![](counter-app-gif.gif) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif) Esse é um projeto simples mas já deixa claro o quão poderoso o Get é. Enquanto seu projeto cresce, essa diferença se torna bem mais significante. @@ -824,14 +824,14 @@ o ciclo de vida de seu aplicativo, use GetxService. ## Tipagem Rx -| Antes | Depois | -| -------- | ---------- | -| StringX | `RxString` | -| IntX | `RxInt` | -| MapX | `RxMap` | -| ListX | `RxList` | -| NumX | `RxNum` | -| DoubleX | `RxDouble` | +| Antes | Depois | +| ------- | ---------- | +| StringX | `RxString` | +| IntX | `RxInt` | +| MapX | `RxMap` | +| ListX | `RxList` | +| NumX | `RxNum` | +| DoubleX | `RxDouble` | ## RxController e GetBuilder se uniram diff --git a/README.zh-cn.md b/README.zh-cn.md index c5e6d4346..3b27edb81 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -1,4 +1,4 @@ -![](get.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/get.png) _语言: 中文, [英文](README.md), [巴西葡萄牙语](README.pt-br.md), [西班牙语](README-es.md), [波兰语](README.pl.md)_ @@ -13,11 +13,11 @@ _语言: 中文, [英文](README.md), [巴西葡萄牙语](README.pt-br.md), [ Buy Me A Coffee -![](getx.png) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/getx.png) -- [关于 Get](#关于Get) +- [关于Get](#关于get) - [安装](#安装) -- [GetX 的计数器示例](#GetX的计数器示例) +- [GetX的计数器示例](#getx的计数器示例) - [三大功能](#三大功能) - [状态管理](#状态管理) - [响应式状态管理器](#响应式状态管理器) @@ -34,7 +34,7 @@ _语言: 中文, [英文](README.md), [巴西葡萄牙语](README.pt-br.md), [ - [改变语言](#改变语言) - [系统语言](#系统语言) - [改变主题](#改变主题) - - [其他高级API](#其他高级API) + - [其他高级API](#其他高级api) - [可选的全局设置和手动配置](#可选的全局设置和手动配置) - [局部状态组件](#局部状态组件) - [ValueBuilder](#valuebuilder) @@ -43,10 +43,10 @@ _语言: 中文, [英文](README.md), [巴西葡萄牙语](README.pt-br.md), [ - [GetView](#getview) - [GetWidget](#getwidget) - [GetxService](#getxservice) -- [从2.0开始的兼容性变化](#从2.0开始的兼容性变化) -- [为什么选择Getx?](#为什么选择Getx?) +- [从2.0开始的兼容性变化](#从20开始的兼容性变化) +- [为什么选择Getx?](#为什么选择getx) - [社区](#社区) - - [社区频道](#社区频道) + - [社区渠道](#社区渠道) - [如何做贡献](#如何做贡献) - [文章和视频](#文章和视频) @@ -151,7 +151,7 @@ class Other extends StatelessWidget { 结果: -![](counter-app-gif.gif) +![](https://raw.githubusercontent.com/jonataslaw/getx-community/master/counter-app-gif.gif) 这是一个简单的项目,但它已经让人明白Get的强大。随着项目的发展,这种差异将变得更加显著。 diff --git a/counter-app-gif.gif b/counter-app-gif.gif deleted file mode 100644 index d4b7fc7ef..000000000 Binary files a/counter-app-gif.gif and /dev/null differ diff --git a/example/android/.gitignore b/example/android/.gitignore deleted file mode 100644 index 0a741cb43..000000000 --- a/example/android/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -gradle-wrapper.jar -/.gradle -/captures/ -/gradlew -/gradlew.bat -/local.properties -GeneratedPluginRegistrant.java - -# Remember to never publicly share your keystore. -# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app -key.properties diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle deleted file mode 100644 index c04b826b6..000000000 --- a/example/android/app/build.gradle +++ /dev/null @@ -1,63 +0,0 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - -android { - compileSdkVersion 29 - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - lintOptions { - disable 'InvalidPackage' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "getx.demo.app.example" - minSdkVersion 16 - targetSdkVersion 29 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug - } - } -} - -flutter { - source '../..' -} - -dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" -} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml deleted file mode 100644 index 1172bc4d2..000000000 --- a/example/android/app/src/debug/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index af0bcf2c2..000000000 --- a/example/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/example/android/app/src/main/kotlin/getx/demo/app/example/MainActivity.kt b/example/android/app/src/main/kotlin/getx/demo/app/example/MainActivity.kt deleted file mode 100644 index b51fd2c8c..000000000 --- a/example/android/app/src/main/kotlin/getx/demo/app/example/MainActivity.kt +++ /dev/null @@ -1,6 +0,0 @@ -package getx.demo.app.example - -import io.flutter.embedding.android.FlutterActivity - -class MainActivity: FlutterActivity() { -} diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml deleted file mode 100644 index 304732f88..000000000 --- a/example/android/app/src/main/res/drawable/launch_background.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index db77bb4b7..000000000 Binary files a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index 17987b79b..000000000 Binary files a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index 09d439148..000000000 Binary files a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index d5f1c8d34..000000000 Binary files a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index 4d6372eeb..000000000 Binary files a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 1f83a33fd..000000000 --- a/example/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml deleted file mode 100644 index 1172bc4d2..000000000 --- a/example/android/app/src/profile/AndroidManifest.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/example/android/build.gradle b/example/android/build.gradle deleted file mode 100644 index 3100ad2d5..000000000 --- a/example/android/build.gradle +++ /dev/null @@ -1,31 +0,0 @@ -buildscript { - ext.kotlin_version = '1.3.50' - repositories { - google() - jcenter() - } - - dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -allprojects { - repositories { - google() - jcenter() - } -} - -rootProject.buildDir = '../build' -subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" -} -subprojects { - project.evaluationDependsOn(':app') -} - -task clean(type: Delete) { - delete rootProject.buildDir -} diff --git a/example/android/gradle.properties b/example/android/gradle.properties deleted file mode 100644 index a6738207f..000000000 --- a/example/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx1536M -android.useAndroidX=true -android.enableJetifier=true -android.enableR8=true diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 296b146b7..000000000 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Jun 23 08:50:38 CEST 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip diff --git a/example/android/settings.gradle b/example/android/settings.gradle deleted file mode 100644 index 44e62bcf0..000000000 --- a/example/android/settings.gradle +++ /dev/null @@ -1,11 +0,0 @@ -include ':app' - -def localPropertiesFile = new File(rootProject.projectDir, "local.properties") -def properties = new Properties() - -assert localPropertiesFile.exists() -localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } - -def flutterSdkPath = properties.getProperty("flutter.sdk") -assert flutterSdkPath != null, "flutter.sdk not set in local.properties" -apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/example/linux/.gitignore b/example/linux/.gitignore deleted file mode 100644 index d3896c984..000000000 --- a/example/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/example/linux/CMakeLists.txt b/example/linux/CMakeLists.txt deleted file mode 100644 index 632fd41a8..000000000 --- a/example/linux/CMakeLists.txt +++ /dev/null @@ -1,106 +0,0 @@ -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -set(BINARY_NAME "example") -set(APPLICATION_ID "getx.demo.app.example") - -cmake_policy(SET CMP0063 NEW) - -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Configure build options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") - -# Flutter library and tool build rules. -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Application build -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) -apply_standard_settings(${BINARY_NAME}) -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) -add_dependencies(${BINARY_NAME} flutter_assemble) -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/example/linux/flutter/CMakeLists.txt b/example/linux/flutter/CMakeLists.txt deleted file mode 100644 index 4f48a7ced..000000000 --- a/example/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) -pkg_check_modules(BLKID REQUIRED IMPORTED_TARGET blkid) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO - PkgConfig::BLKID -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - linux-x64 ${CMAKE_BUILD_TYPE} -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/example/linux/flutter/generated_plugin_registrant.cc b/example/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index d38195aa0..000000000 --- a/example/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,9 +0,0 @@ -// -// Generated file. Do not edit. -// - -#include "generated_plugin_registrant.h" - - -void fl_register_plugins(FlPluginRegistry* registry) { -} diff --git a/example/linux/flutter/generated_plugin_registrant.h b/example/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index 9bf747894..000000000 --- a/example/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// Generated file. Do not edit. -// - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/linux/flutter/generated_plugins.cmake b/example/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 51436ae8c..000000000 --- a/example/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) diff --git a/example/linux/main.cc b/example/linux/main.cc deleted file mode 100644 index 058e6178f..000000000 --- a/example/linux/main.cc +++ /dev/null @@ -1,10 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - // Only X11 is currently supported. - // Wayland support is being developed: https://github.com/flutter/flutter/issues/57932. - gdk_set_allowed_backends("x11"); - - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/example/linux/my_application.cc b/example/linux/my_application.cc deleted file mode 100644 index f28ca3094..000000000 --- a/example/linux/my_application.cc +++ /dev/null @@ -1,46 +0,0 @@ -#include "my_application.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "example"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - nullptr)); -} diff --git a/example/linux/my_application.h b/example/linux/my_application.h deleted file mode 100644 index 72271d5e4..000000000 --- a/example/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 1dcc58f03..e846e5ded 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -27,16 +27,14 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. get: - git: - url: git://github.com/jonataslaw/getx.git - path: getx - ref: master + path: ../ dio: ^3.0.9 - get_test: - git: - url: git://github.com/jonataslaw/getx.git - path: packages/get_test - ref: master + get_test: ^3.13.2 + +dependency_overrides: + get: + path: ../ + dev_dependencies: flutter_test: sdk: flutter diff --git a/example/web/favicon.png b/example/web/favicon.png deleted file mode 100644 index 8aaa46ac1..000000000 Binary files a/example/web/favicon.png and /dev/null differ diff --git a/example/web/icons/Icon-192.png b/example/web/icons/Icon-192.png deleted file mode 100644 index b749bfef0..000000000 Binary files a/example/web/icons/Icon-192.png and /dev/null differ diff --git a/example/web/icons/Icon-512.png b/example/web/icons/Icon-512.png deleted file mode 100644 index 88cfd48df..000000000 Binary files a/example/web/icons/Icon-512.png and /dev/null differ diff --git a/example/web/index.html b/example/web/index.html deleted file mode 100644 index a0c14606f..000000000 --- a/example/web/index.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - example - - - - - - - - diff --git a/example/web/manifest.json b/example/web/manifest.json deleted file mode 100644 index 8c012917d..000000000 --- a/example/web/manifest.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "example", - "short_name": "example", - "start_url": ".", - "display": "standalone", - "background_color": "#0175C2", - "theme_color": "#0175C2", - "description": "A new Flutter project.", - "orientation": "portrait-primary", - "prefer_related_applications": false, - "icons": [ - { - "src": "icons/Icon-192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "icons/Icon-512.png", - "sizes": "512x512", - "type": "image/png" - } - ] -} diff --git a/get.png b/get.png deleted file mode 100644 index e08f5e7ca..000000000 Binary files a/get.png and /dev/null differ diff --git a/getx.png b/getx.png deleted file mode 100644 index 5dd2bd5cb..000000000 Binary files a/getx.png and /dev/null differ diff --git a/lib/get_navigation/src/routes/default_transitions.dart b/lib/get_navigation/src/routes/default_transitions.dart index 992c3914a..02947e7ab 100644 --- a/lib/get_navigation/src/routes/default_transitions.dart +++ b/lib/get_navigation/src/routes/default_transitions.dart @@ -184,4 +184,3 @@ class SizeTransitions { ); } } - diff --git a/lib/get_rx/src/rx_core/rx_impl.dart b/lib/get_rx/src/rx_core/rx_impl.dart index 6c1e66e72..269287d29 100644 --- a/lib/get_rx/src/rx_core/rx_impl.dart +++ b/lib/get_rx/src/rx_core/rx_impl.dart @@ -1,6 +1,6 @@ import 'dart:async'; import 'dart:collection'; -import 'package:meta/meta.dart'; +import 'package:flutter/foundation.dart'; import '../rx_core/rx_interface.dart'; part 'rx_num.dart'; diff --git a/lib/get_rx/src/rx_iterables/rx_list.dart b/lib/get_rx/src/rx_iterables/rx_list.dart index f9563cf94..68c0dd5af 100644 --- a/lib/get_rx/src/rx_iterables/rx_list.dart +++ b/lib/get_rx/src/rx_iterables/rx_list.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:collection'; import 'dart:math'; -import 'package:meta/meta.dart'; +import 'package:flutter/foundation.dart'; import '../rx_core/rx_impl.dart'; import '../rx_core/rx_interface.dart'; diff --git a/lib/get_rx/src/rx_iterables/rx_map.dart b/lib/get_rx/src/rx_iterables/rx_map.dart index c9b9c26df..ffae94d71 100644 --- a/lib/get_rx/src/rx_iterables/rx_map.dart +++ b/lib/get_rx/src/rx_iterables/rx_map.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'dart:collection'; -import 'package:meta/meta.dart'; - +import 'package:flutter/foundation.dart'; import '../rx_core/rx_impl.dart'; import '../rx_core/rx_interface.dart'; import '../rx_typedefs/rx_typedefs.dart'; diff --git a/lib/get_rx/src/rx_iterables/rx_set.dart b/lib/get_rx/src/rx_iterables/rx_set.dart index d621d6686..b78c23cb5 100644 --- a/lib/get_rx/src/rx_iterables/rx_set.dart +++ b/lib/get_rx/src/rx_iterables/rx_set.dart @@ -1,6 +1,6 @@ import 'dart:async'; import 'dart:collection'; -import 'package:meta/meta.dart'; +import 'package:flutter/foundation.dart'; import '../rx_core/rx_impl.dart'; import '../rx_core/rx_interface.dart'; diff --git a/logo-no-background.png b/logo-no-background.png deleted file mode 100644 index a8ddd3cfb..000000000 Binary files a/logo-no-background.png and /dev/null differ diff --git a/packages/get_core/.gitignore b/packages/get_core/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_core/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_core/.metadata b/packages/get_core/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_core/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_core/CHANGELOG.md b/packages/get_core/CHANGELOG.md deleted file mode 100644 index 57b4e07ed..000000000 --- a/packages/get_core/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 - -## [3.10.2] - -* Initial release diff --git a/packages/get_core/LICENSE b/packages/get_core/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_core/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_core/README.md b/packages/get_core/README.md deleted file mode 100644 index ffd72c852..000000000 --- a/packages/get_core/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_core - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_core/analysis_options.yaml b/packages/get_core/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_core/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_core/lib/get_core.dart b/packages/get_core/lib/get_core.dart deleted file mode 100644 index f2361e782..000000000 --- a/packages/get_core/lib/get_core.dart +++ /dev/null @@ -1,7 +0,0 @@ -library get_core; - -export 'src/get_interface.dart'; -export 'src/get_main.dart'; -export 'src/log.dart'; - -export 'src/smart_management.dart'; diff --git a/packages/get_core/lib/src/get_interface.dart b/packages/get_core/lib/src/get_interface.dart deleted file mode 100644 index 044e22e16..000000000 --- a/packages/get_core/lib/src/get_interface.dart +++ /dev/null @@ -1,11 +0,0 @@ -import 'log.dart'; -import 'smart_management.dart'; - -/// GetInterface allows any auxiliary package to be merged into the "Get" -/// class through extensions -abstract class GetInterface { - SmartManagement smartManagement = SmartManagement.full; - String reference; - bool isLogEnable = true; - LogWriterCallback log = defaultLogWriterCallback; -} diff --git a/packages/get_core/lib/src/get_main.dart b/packages/get_core/lib/src/get_main.dart deleted file mode 100644 index cab2be9ac..000000000 --- a/packages/get_core/lib/src/get_main.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'get_interface.dart'; - -///Use to instead of Navigator.push, off instead of Navigator.pushReplacement, -///offAll instead of Navigator.pushAndRemoveUntil. For named routes just -///add "named" after them. Example: toNamed, offNamed, and AllNamed. -///To return to the previous screen, use back(). -///No need to pass any context to Get, just put the name of the route inside -///the parentheses and the magic will occur. -class _GetImpl extends GetInterface {} - -// ignore: non_constant_identifier_names -final Get = _GetImpl(); diff --git a/packages/get_core/lib/src/log.dart b/packages/get_core/lib/src/log.dart deleted file mode 100644 index 0af9108c5..000000000 --- a/packages/get_core/lib/src/log.dart +++ /dev/null @@ -1,10 +0,0 @@ -import 'dart:developer' as developer; -import 'get_main.dart'; - -///Voidcallback from logs -typedef LogWriterCallback = void Function(String text, {bool isError}); - -/// default logger from GetX -void defaultLogWriterCallback(String value, {bool isError = false}) { - if (isError || Get.isLogEnable) developer.log(value, name: 'GETX'); -} diff --git a/packages/get_core/lib/src/smart_management.dart b/packages/get_core/lib/src/smart_management.dart deleted file mode 100644 index c4f06418c..000000000 --- a/packages/get_core/lib/src/smart_management.dart +++ /dev/null @@ -1,22 +0,0 @@ -/// GetX by default disposes unused controllers from memory, -/// Through different behaviors. -/// SmartManagement.full -/// [SmartManagement.full] is the default one. Dispose classes that are -/// not being used and were not set to be permanent. In the majority -/// of the cases you will want to keep this config untouched. -/// If you new to GetX then don't change this. -/// [SmartManagement.onlyBuilders] only controllers started in init: -/// or loaded into a Binding with Get.lazyPut() will be disposed. If you use -/// Get.put() or Get.putAsync() or any other approach, SmartManagement -/// will not have permissions to exclude this dependency. With the default -/// behavior, even widgets instantiated with "Get.put" will be removed, -/// unlike SmartManagement.onlyBuilders. -/// [SmartManagement.keepFactory]Just like SmartManagement.full, -/// it will remove it's dependencies when it's not being used anymore. -/// However, it will keep their factory, which means it will recreate -/// the dependency if you need that instance again. -enum SmartManagement { - full, - onlyBuilder, - keepFactory, -} diff --git a/packages/get_core/pubspec.yaml b/packages/get_core/pubspec.yaml deleted file mode 100644 index 8cc83818f..000000000 --- a/packages/get_core/pubspec.yaml +++ /dev/null @@ -1,50 +0,0 @@ -name: get_core -description: A base package from allow use resources from GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - -dependencies: - - -dev_dependencies: - - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_instance/.gitignore b/packages/get_instance/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_instance/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_instance/.metadata b/packages/get_instance/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_instance/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_instance/CHANGELOG.md b/packages/get_instance/CHANGELOG.md deleted file mode 100644 index 4cb259062..000000000 --- a/packages/get_instance/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 - -## [3.10.2] -- Initial release diff --git a/packages/get_instance/LICENSE b/packages/get_instance/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_instance/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_instance/README.md b/packages/get_instance/README.md deleted file mode 100644 index 2e2d26468..000000000 --- a/packages/get_instance/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_instance - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_instance/analysis_options.yaml b/packages/get_instance/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_instance/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_instance/example/main.dart b/packages/get_instance/example/main.dart deleted file mode 100644 index 84019aeb3..000000000 --- a/packages/get_instance/example/main.dart +++ /dev/null @@ -1,11 +0,0 @@ -import 'package:get_instance/get_instance.dart'; - -void main() { - Get.put(Foo()); - - final foo = Get.find(); - final foo2 = Get.find(); - print(foo == foo2); // true -} - -class Foo {} diff --git a/packages/get_instance/lib/get_instance.dart b/packages/get_instance/lib/get_instance.dart deleted file mode 100644 index fe4dc8a0a..000000000 --- a/packages/get_instance/lib/get_instance.dart +++ /dev/null @@ -1,5 +0,0 @@ -export 'package:get_core/get_core.dart'; -export 'src/bindings_interface.dart'; -export 'src/extension_instance.dart'; -export 'src/get_instance.dart'; -export 'src/lifecycle.dart'; diff --git a/packages/get_instance/lib/src/bindings_interface.dart b/packages/get_instance/lib/src/bindings_interface.dart deleted file mode 100644 index b7b9cc75c..000000000 --- a/packages/get_instance/lib/src/bindings_interface.dart +++ /dev/null @@ -1,65 +0,0 @@ -import 'get_instance.dart'; - -/// [Bindings] should be extended or implemented. -/// When using [GetMaterialApp], all [GetPage]s and navigation -/// methods (like Get.to()) have a [binding] property that takes an -/// instance of Bindings to manage the -/// dependencies() (via [Get.put()]) for the Route you are opening. -// ignore: one_member_abstracts -abstract class Bindings { - void dependencies(); -} - -/// Simplifies Bindings generation from a single callback. -/// To avoid the creation of a custom Binding instance per route. -/// -/// Example: -/// ``` -/// GetPage( -/// name: '/', -/// page: () => Home(), -/// // This might cause you an error. -/// // binding: BindingsBuilder(() => Get.put(HomeController())), -/// binding: BindingsBuilder(() { Get.put(HomeController(); })), -/// // Using .lazyPut() works fine. -/// // binding: BindingsBuilder(() => Get.lazyPut(() => HomeController())), -/// ), -/// ``` -class BindingsBuilder extends Bindings { - /// Register your dependencies in the [builder] callback. - final BindingBuilderCallback builder; - - /// Shortcut to register 1 Controller with Get.put(), - /// Prevents the issue of the fat arrow function with the constructor. - /// BindingsBuilder(() => Get.put(HomeController())), - /// - /// Sample: - /// ``` - /// GetPage( - /// name: '/', - /// page: () => Home(), - /// binding: BindingsBuilder.put(() => HomeController()), - /// ), - /// ``` - factory BindingsBuilder.put(InstanceBuilderCallback builder, - {String tag, bool permanent = false}) { - return BindingsBuilder(() => GetInstance() - .put(null, tag: tag, permanent: permanent, builder: builder)); - } - - /// WARNING: don't use `()=> Get.put(Controller())`, - /// if only passing 1 callback use `BindingsBuilder.put(Controller())` - /// or `BindingsBuilder(()=> Get.lazyPut(Controller()))` - BindingsBuilder(this.builder); - - @override - void dependencies() { - builder(); - } -} - -// abstract class INavigation {} -// typedef Snack = Function(); -// typedef Modal = Function(); -// typedef Route = Function(); -typedef BindingBuilderCallback = void Function(); diff --git a/packages/get_instance/lib/src/extension_instance.dart b/packages/get_instance/lib/src/extension_instance.dart deleted file mode 100644 index 77b627eb1..000000000 --- a/packages/get_instance/lib/src/extension_instance.dart +++ /dev/null @@ -1,115 +0,0 @@ -import 'package:get_core/get_core.dart'; - -import 'get_instance.dart'; - -extension Inst on GetInterface { - /// Creates a new Instance lazily from the [builder()] callback. - /// - /// The first time you call [Get.find()], the [builder()] callback will create - /// the Instance and persisted as a Singleton (like you would use - /// [Get.put()]). - /// - /// Using [Get.smartManagement] as [SmartManagement.keepFactory] has - /// the same outcome - /// as using [fenix:true] : - /// The internal register of [builder()] will remain in memory to recreate - /// the Instance if the Instance has been removed with [Get.delete()]. - /// Therefore, future calls to [Get.find()] will return the same Instance. - /// - /// If you need to make use of GetxController's life-cycle - /// ([onInit(), onStart(), onClose()]) - /// [fenix] is a great choice to mix with [GetBuilder()] and [GetX()] widgets, - /// and/or [GetMaterialApp] Navigation. - /// - /// You could use [Get.lazyPut(fenix:true)] in your app's [main()] instead of - /// [Bindings()] for each [GetPage]. - /// And the memory management will be similar. - /// - /// Subsequent calls to [Get.lazyPut()] with the same parameters - /// (<[S]> and optionally [tag] will **not** override the original). - void lazyPut(InstanceBuilderCallback builder, - {String tag, bool fenix = false}) { - GetInstance().lazyPut(builder, tag: tag, fenix: fenix); - } - - /// async version of [Get.put()]. - /// Awaits for the resolution of the Future from [builder()] parameter and - /// stores the Instance returned. - Future putAsync(AsyncInstanceBuilderCallback builder, - {String tag, bool permanent = false}) async => - GetInstance().putAsync(builder, tag: tag, permanent: permanent); - - /// Creates a new Class Instance [S] from the builder callback[S]. - /// Every time [find]<[S]>() is used, it calls the builder method to generate - /// a new Instance [S]. - /// It also registers each [instance.onClose()] with the current - /// Route [GetConfig.currentRoute] to keep the lifecycle active. - /// Is important to know that the instances created are only stored per Route. - /// So, if you call `Get.delete()` the "instance factory" used in this - /// method ([Get.create()]) will be removed, but NOT the instances - /// already created by it. - /// Uses `tag` as the other methods. - /// - /// Example: - /// - /// ```create(() => Repl()); - /// Repl a = find(); - /// Repl b = find(); - /// print(a==b); (false)``` - void create(InstanceBuilderCallback builder, - {String tag, bool permanent = true}) => - GetInstance().create(builder, tag: tag, permanent: permanent); - - /// Finds a Instance of the required Class <[S]>(or [tag]) - /// In the case of using [Get.create()], it will generate an Instance - /// each time you call [Get.find()]. - S find({String tag}) => GetInstance().find(tag: tag); - - /// Injects an [Instance] in memory. - /// - /// No need to define the generic type <[S]> as it's inferred - /// from the [dependency] parameter. - /// - /// - [dependency] The Instance to be injected. - /// - [tag] optionally, use a [tag] as an "id" to create multiple records - /// of the same Type<[S]> the [tag] does **not** conflict with the same tags - /// used by other [dependencies] Types. - /// - [permanent] keeps the Instance in memory and persist it, - /// not following [Get.smartManagement] - /// rules. Although, can be removed by [GetInstance.reset()] - /// and [Get.delete()] - /// - [builder] If defined, the [dependency] must be returned from here - S put(S dependency, - {String tag, - bool permanent = false, - InstanceBuilderCallback builder}) => - GetInstance() - .put(dependency, tag: tag, permanent: permanent, builder: builder); - - /// Clears all registered instances (and/or tags). - /// Even the persistent ones. - /// - /// - [clearFactory] clears the callbacks registered by [Get.lazyPut()] - /// - [clearRouteBindings] clears Instances associated with Routes when using - /// [GetMaterialApp]. - bool reset({bool clearFactory = true, bool clearRouteBindings = true}) => - GetInstance().reset( - clearFactory: clearFactory, clearRouteBindings: clearRouteBindings); - - /// Deletes the Instance<[S]>, cleaning the memory and closes any open - /// controllers ([DisposableInterface]). - /// - /// - [tag] Optional "tag" used to register the Instance - /// - [force] Will delete an Instance even if marked as [permanent]. - Future delete({String tag, bool force = false}) async => - GetInstance().delete(tag: tag, force: force); - - /// Checks if a Class Instance<[S]> (or [tag]) is registered in memory. - /// - [tag] optional, if you use a [tag] to register the Instance. - bool isRegistered({String tag}) => GetInstance().isRegistered(tag: tag); - - /// Checks if an Instance<[S]> (or [tag]) returned from a factory builder - /// [Get.lazyPut()], is registered in memory. - /// - [tag] optional, if you use a [tag] to register the Instance. - bool isPrepared({String tag}) => GetInstance().isPrepared(tag: tag); -} diff --git a/packages/get_instance/lib/src/get_instance.dart b/packages/get_instance/lib/src/get_instance.dart deleted file mode 100644 index 8fecd9b55..000000000 --- a/packages/get_instance/lib/src/get_instance.dart +++ /dev/null @@ -1,420 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; - -import 'package:get_core/get_core.dart'; - -import 'lifecycle.dart'; - -class GetInstance { - factory GetInstance() => _getInstance ??= GetInstance._(); - - const GetInstance._(); - - static GetInstance _getInstance; - - /// Holds references to every registered Instance when using - /// [Get.put()] - static final Map _singl = {}; - - /// Holds a reference to every registered callback when using - /// [Get.lazyPut()] - static final Map _factory = {}; - - /// Holds a reference to [Get.reference] when the Instance was - /// created to manage the memory. - static final Map _routesKey = {}; - - /// Stores the onClose() references of instances created with [Get.create()] - /// using the [Get.reference]. - /// Experimental feature to keep the lifecycle and memory management with - /// non-singleton instances. - static final Map> _routesByCreate = {}; - - /// Creates a new Instance lazily from the [builder()] callback. - /// - /// The first time you call [Get.find()], the [builder()] callback will create - /// the Instance and persisted as a Singleton (like you would - /// use [Get.put()]). - /// - /// Using [Get.smartManagement] as [SmartManagement.keepFactory] has - /// the same outcome as using [fenix:true] : - /// The internal register of [builder()] will remain in memory to recreate - /// the Instance if the Instance has been removed with [Get.delete()]. - /// Therefore, future calls to [Get.find()] will return the same Instance. - /// - /// If you need to make use of GetxController's life-cycle - /// ([onInit(), onStart(), onClose()]) [fenix] is a great choice to mix with - /// [GetBuilder()] and [GetX()] widgets, and/or [GetMaterialApp] Navigation. - /// - /// You could use [Get.lazyPut(fenix:true)] in your app's [main()] instead - /// of [Bindings()] for each [GetPage]. - /// And the memory management will be similar. - /// - /// Subsequent calls to [Get.lazyPut()] with the same parameters - /// (<[S]> and optionally [tag] will **not** override the original). - void lazyPut( - InstanceBuilderCallback builder, { - String tag, - bool fenix = false, - }) { - final key = _getKey(S, tag); - _factory.putIfAbsent(key, () => _Lazy(builder, fenix)); - } - - /// async version of [Get.put()]. - /// Awaits for the resolution of the Future from [builder()] parameter and - /// stores the Instance returned. - Future putAsync( - AsyncInstanceBuilderCallback builder, { - String tag, - bool permanent = false, - }) async { - return put(await builder(), tag: tag, permanent: permanent); - } - - /// Injects an instance <[S]> in memory to be globally accessible. - /// - /// No need to define the generic type <[S]> as it's inferred from - /// the [dependency] - /// - /// - [dependency] The Instance to be injected. - /// - [tag] optionally, use a [tag] as an "id" to create multiple records of - /// the same Type<[S]> - /// - [permanent] keeps the Instance in memory, not following - /// [Get.smartManagement] rules. - S put( - S dependency, { - String tag, - bool permanent = false, - InstanceBuilderCallback builder, - }) { - _insert( - isSingleton: true, - name: tag, - permanent: permanent, - builder: builder ?? (() => dependency)); - return find(tag: tag); - } - - /// Creates a new Class Instance [S] from the builder callback[S]. - /// Every time [find]<[S]>() is used, it calls the builder method to generate - /// a new Instance [S]. - /// It also registers each [instance.onClose()] with the current - /// Route [Get.reference] to keep the lifecycle active. - /// Is important to know that the instances created are only stored per Route. - /// So, if you call `Get.delete()` the "instance factory" used in this - /// method ([Get.create()]) will be removed, but NOT the instances - /// already created by it. - /// - /// Example: - /// - /// ```create(() => Repl()); - /// Repl a = find(); - /// Repl b = find(); - /// print(a==b); (false)``` - void create( - InstanceBuilderCallback builder, { - String tag, - bool permanent = true, - }) { - _insert( - isSingleton: false, name: tag, builder: builder, permanent: permanent); - } - - /// Injects the Instance [S] builder into the [_singleton] HashMap. - void _insert({ - bool isSingleton, - String name, - bool permanent = false, - InstanceBuilderCallback builder, - }) { - assert(builder != null); - final key = _getKey(S, name); - _singl.putIfAbsent( - key, - () => - _InstanceBuilderFactory(isSingleton, builder, permanent, false)); - } - - /// Clears from memory registered Instances associated with [routeName] when - /// using [Get.smartManagement] as [SmartManagement.full] or - /// [SmartManagement.keepFactory] - /// Meant for internal usage of [GetPageRoute] and [GetDialogRoute] - void removeDependencyByRoute(String routeName) { - final keysToRemove = []; - _routesKey.forEach((key, value) { - if (value == routeName) { - keysToRemove.add(key); - } - }); - - /// Removes [Get.create()] instances registered in [routeName]. - if (_routesByCreate.containsKey(routeName)) { - for (final onClose in _routesByCreate[routeName]) { - // assure the [DisposableInterface] instance holding a reference - // to [onClose()] wasn't disposed. - if (onClose != null) { - onClose(); - } - } - _routesByCreate[routeName].clear(); - _routesByCreate.remove(routeName); - } - - for (final element in keysToRemove) { - delete(key: element); - } - - for (final element in keysToRemove) { - _routesKey?.remove(element); - } - keysToRemove.clear(); - } - - /// Initializes the dependencies for a Class Instance [S] (or tag), - /// If its a Controller, it starts the lifecycle process. - /// Optionally associating the current Route to the lifetime of the instance, - /// if [Get.smartManagement] is marked as [SmartManagement.full] or - /// [Get.keepFactory] - /// Only flags `isInit` if it's using `Get.create()` - /// (not for Singletons access). - /// Returns the instance if not initialized, required for Get.create() to - /// work properly. - S _initDependencies({String name}) { - final key = _getKey(S, name); - final isInit = _singl[key].isInit; - S i; - if (!isInit) { - i = _startController(tag: name); - if (_singl[key].isSingleton) { - _singl[key].isInit = true; - if (Get.smartManagement != SmartManagement.onlyBuilder) { - _registerRouteInstance(tag: name); - } - } - } - return i; - } - - /// Links a Class instance [S] (or [tag]) to the current route. - /// Requires usage of [GetMaterialApp]. - void _registerRouteInstance({String tag}) { - _routesKey.putIfAbsent(_getKey(S, tag), () => Get.reference); - } - - /// Finds and returns a Instance<[S]> (or [tag]) without further processing. - S findByType(Type type, {String tag}) { - final key = _getKey(type, tag); - return _singl[key].getDependency() as S; - } - - /// Initializes the controller - S _startController({String tag}) { - final key = _getKey(S, tag); - final i = _singl[key].getDependency() as S; - if (i is GetLifeCycle) { - if (i.onStart != null) { - i.onStart(); - Get.log('"$key" has been initialized'); - } - if (!_singl[key].isSingleton && i.onClose != null) { - _routesByCreate[Get.reference] ??= HashSet(); - _routesByCreate[Get.reference].add(i.onClose); - } - } - return i; - } - - S putOrFind(InstanceBuilderCallback dep, {String tag}) { - final key = _getKey(S, tag); - - if (_singl.containsKey(key)) { - return _singl[key].getDependency() as S; - } else { - if (_factory.containsKey(key)) { - final _value = put((_factory[key].builder() as S), tag: tag); - - if (Get.smartManagement != SmartManagement.keepFactory) { - if (!_factory[key].fenix) { - _factory.remove(key); - } - } - return _value; - } - - return GetInstance().put(dep(), tag: tag); - } - } - - /// Finds the registered type <[S]> (or [tag]) - /// In case of using Get.[create] to register a type <[S]> or [tag], - /// it will create an instance each time you call [find]. - /// If the registered type <[S]> (or [tag]) is a Controller, - /// it will initialize it's lifecycle. - S find({String tag}) { - final key = _getKey(S, tag); - if (isRegistered(tag: tag)) { - if (_singl[key] == null) { - if (tag == null) { - throw 'Class "$S" is not registered'; - } else { - throw 'Class "$S" with tag "$tag" is not registered'; - } - } - - /// although dirty solution, the lifecycle starts inside - /// `initDependencies`, so we have to return the instance from there - /// to make it compatible with `Get.create()`. - final i = _initDependencies(name: tag); - return i ?? _singl[key].getDependency() as S; - } else { - if (!_factory.containsKey(key)) { - // ignore: lines_longer_than_80_chars - throw '"$S" not found. You need to call "Get.put($S())" or "Get.lazyPut(()=>$S())"'; - } - - Get.log('Lazy instance "$S" created'); - final _value = put(_factory[key].builder() as S, tag: tag); - _initDependencies(name: tag); - - if (Get.smartManagement != SmartManagement.keepFactory && - !_factory[key].fenix) { - _factory.remove(key); - } - - return _value; - } - } - - /// Generates the key based on [type] (and optionally a [name]) - /// to register an Instance Builder in the hashmap. - String _getKey(Type type, String name) { - return name == null ? type.toString() : type.toString() + name; - } - - /// Clears all registered instances (and/or tags). - /// Even the persistent ones. - /// - /// [clearFactory] clears the callbacks registered by [lazyPut] - /// [clearRouteBindings] clears Instances associated with routes. - /// - bool reset({bool clearFactory = true, bool clearRouteBindings = true}) { - if (clearFactory) _factory.clear(); - if (clearRouteBindings) _routesKey.clear(); - _singl.clear(); - return true; - } - - /// Delete registered Class Instance [S] (or [tag]) and, closes any open - /// controllers [DisposableInterface], cleans up the memory - /// - /// /// Deletes the Instance<[S]>, cleaning the memory. - // /// - // /// - [tag] Optional "tag" used to register the Instance - // /// - [key] For internal usage, is the processed key used to register - // /// the Instance. **don't use** it unless you know what you are doing. - - /// Deletes the Instance<[S]>, cleaning the memory and closes any open - /// controllers ([DisposableInterface]). - /// - /// - [tag] Optional "tag" used to register the Instance - /// - [key] For internal usage, is the processed key used to register - /// the Instance. **don't use** it unless you know what you are doing. - /// - [force] Will delete an Instance even if marked as [permanent]. - bool delete({String tag, String key, bool force = false}) { - // return _queue.secure(() { - return _delete(tag: tag, key: key, force: force); - // }); - } - - bool _delete({String tag, String key, bool force = false}) { - final newKey = key ?? _getKey(S, tag); - - if (!_singl.containsKey(newKey)) { - Get.log('Instance "$newKey" already removed.', isError: true); - return false; - } - - final builder = _singl[newKey]; - if (builder.permanent && !force) { - Get.log( - // ignore: lines_longer_than_80_chars - '"$newKey" has been marked as permanent, SmartManagement is not authorized to delete it.', - isError: true, - ); - return false; - } - final i = builder.dependency; - - if (i is GetxServiceMixin && !force) { - return false; - } - if (i is GetLifeCycle) { - i.onClose(); - Get.log('"$newKey" onClose() called'); - } - - _singl.removeWhere((oldKey, value) => (oldKey == newKey)); - if (_singl.containsKey(newKey)) { - Get.log('Error removing object "$newKey"', isError: true); - } else { - Get.log('"$newKey" deleted from memory'); - } - // _routesKey?.remove(key); - return true; - } - - /// Check if a Class Instance<[S]> (or [tag]) is registered in memory. - /// - [tag] is optional, if you used a [tag] to register the Instance. - bool isRegistered({String tag}) => _singl.containsKey(_getKey(S, tag)); - - /// Checks if a lazy factory callback ([Get.lazyPut()] that returns an - /// Instance<[S]> is registered in memory. - /// - [tag] is optional, if you used a [tag] to register the lazy Instance. - bool isPrepared({String tag}) => _factory.containsKey(_getKey(S, tag)); -} - -typedef InstanceBuilderCallback = S Function(); - -typedef AsyncInstanceBuilderCallback = Future Function(); - -/// Internal class to register instances with Get.[put]<[S]>(). -class _InstanceBuilderFactory { - /// Marks the Builder as a single instance. - /// For reusing [dependency] instead of [builderFunc] - bool isSingleton; - - /// Stores the actual object instance when [isSingleton]=true. - S dependency; - - /// Generates (and regenerates) the instance when [isSingleton]=false. - /// Usually used by factory methods - InstanceBuilderCallback builderFunc; - - /// Flag to persist the instance in memory, - /// without considering [Get.smartManagement] - bool permanent = false; - - bool isInit = false; - - _InstanceBuilderFactory( - this.isSingleton, - this.builderFunc, - this.permanent, - this.isInit, - ); - - /// Gets the actual instance by it's [builderFunc] or the persisted instance. - S getDependency() { - return isSingleton ? dependency ??= builderFunc() : builderFunc(); - } -} - -/// Internal class to register a future instance with [lazyPut], -/// keeps a reference to the callback to be called. -class _Lazy { - bool fenix; - InstanceBuilderCallback builder; - - _Lazy(this.builder, this.fenix); -} diff --git a/packages/get_instance/lib/src/lifecycle.dart b/packages/get_instance/lib/src/lifecycle.dart deleted file mode 100644 index fe61dd036..000000000 --- a/packages/get_instance/lib/src/lifecycle.dart +++ /dev/null @@ -1,40 +0,0 @@ -/// Special callable class to keep the contract of a regular method, and avoid -/// overrides if you extend the class that uses it, as Dart has no final -/// methods. -/// Used in [DisposableInterface] to avoid the danger of overriding onStart. -/// -class _InternalFinalCallback { - T Function() callback; - - _InternalFinalCallback(); - - T call() => callback.call(); -} - -abstract class GetLifeCycle { - /// Called at the exact moment the widget is allocated in memory. - /// It uses an internal "callable" type, to avoid any @overrides in subclases. - /// This method should be internal and is required to define the - /// lifetime cycle of the subclass. - final onStart = _InternalFinalCallback(); - - /// Called immediately after the widget is allocated in memory. - /// You might use this to initialize something for the controller. - void onInit() {} - - /// Called 1 frame after onInit(). It is the perfect place to enter - /// navigation events, like snackbar, dialogs, or a new route, or - /// async request. - void onReady() {} - - /// Called before [onDelete] method. [onClose] might be used to - /// dispose resources used by the controller. Like closing events, - /// or streams before the controller is destroyed. - /// Or dispose objects that can potentially create some memory leaks, - /// like TextEditingControllers, AnimationControllers. - /// Might be useful as well to persist some data on disk. - void onClose() {} -} - -/// Allow track difference between GetxServices and GetxControllers -mixin GetxServiceMixin {} diff --git a/packages/get_instance/pubspec.yaml b/packages/get_instance/pubspec.yaml deleted file mode 100644 index 091f6909a..000000000 --- a/packages/get_instance/pubspec.yaml +++ /dev/null @@ -1,19 +0,0 @@ -name: get_instance -description: A smart dependency injector to GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - - -dependencies: - get_core: ">=3.13.0 <4.0.0" - -dev_dependencies: - test: ">=1.0.0 <2.0.0" - test_coverage: ">=0.4.3 <1.0.0" - - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec diff --git a/packages/get_instance/test/get_instance_test.dart b/packages/get_instance/test/get_instance_test.dart deleted file mode 100644 index eb25dbd9f..000000000 --- a/packages/get_instance/test/get_instance_test.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'package:get_instance/get_instance.dart'; -import 'package:test/test.dart'; -import 'package:get_core/get_core.dart'; -import 'util/matcher.dart' as m; - -class Mock { - static Future test() async { - await Future.delayed(Duration.zero); - return 'test'; - } -} - -class Controller {} - -class DisposableController extends GetLifeCycle { - DisposableController() { - onStart.callback = _onStart; - } - - // Internal callback that starts the cycle of this controller. - void _onStart() { - onInit(); - } - - bool initialized = false; - - void onInit() async { - initialized = true; - } -} - -// ignore: one_member_abstracts -abstract class Service { - String post(); -} - -class Api implements Service { - @override - String post() { - return 'test'; - } -} - -void main() { - test('Get.putAsync test', () async { - await Get.putAsync(Mock.test); - expect('test', Get.find()); - Get.reset(); - }); - - test('Get.put test', () async { - final instance = Get.put(Controller()); - expect(instance, Get.find()); - Get.reset(); - }); - - test('Get.put tag test', () async { - final instance = Get.put(Controller(), tag: 'one'); - final instance2 = Get.put(Controller(), tag: 'two'); - expect(instance == instance2, false); - expect(Get.find(tag: 'one') == Get.find(tag: 'two'), - false); - expect(Get.find(tag: 'one') == Get.find(tag: 'one'), - true); - expect(Get.find(tag: 'two') == Get.find(tag: 'two'), - true); - Get.reset(); - }); - - test('Get.lazyPut tag test', () async { - Get.lazyPut(() => Controller(), tag: 'one'); - Get.lazyPut(() => Controller(), tag: 'two'); - - expect(Get.find(tag: 'one') == Get.find(tag: 'two'), - false); - expect(Get.find(tag: 'one') == Get.find(tag: 'one'), - true); - expect(Get.find(tag: 'two') == Get.find(tag: 'two'), - true); - Get.reset(); - }); - - test('Get.lazyPut test', () async { - final controller = Controller(); - Get.lazyPut(() => controller); - final ct1 = Get.find(); - expect(ct1, controller); - Get.reset(); - }); - - test('Get.lazyPut with abstract class test', () async { - final api = Api(); - Get.lazyPut(() => api); - final ct1 = Get.find(); - expect(ct1, api); - Get.reset(); - }); - - test('Get.create with abstract class test', () async { - Get.create(() => Api()); - final ct1 = Get.find(); - final ct2 = Get.find(); - expect(ct1 is Service, true); - expect(ct2 is Service, true); - expect(ct1 == ct2, false); - Get.reset(); - }); - - group('test put, delete and check onInit execution', () { - tearDownAll(Get.reset); - - test('Get.put test with init check', () async { - final instance = Get.put(DisposableController()); - expect(instance, Get.find()); - expect(instance.initialized, true); - }); - - test('Get.delete test with disposable controller', () async { - expect(await Get.delete(), true); - expect(() => Get.find(), - throwsA(m.TypeMatcher())); - }); - - test('Get.put test after delete with disposable controller and init check', - () async { - final instance = Get.put(DisposableController()); - expect(instance, Get.find()); - expect(instance.initialized, true); - }); - }); -} diff --git a/packages/get_instance/test/util/matcher.dart b/packages/get_instance/test/util/matcher.dart deleted file mode 100644 index 930f36666..000000000 --- a/packages/get_instance/test/util/matcher.dart +++ /dev/null @@ -1,120 +0,0 @@ -import 'package:test/test.dart'; - -// Copyright 2014, the Dart project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: - -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. - -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -class _FunctionMatcher extends CustomMatcher { - final dynamic Function(T value) _feature; - - _FunctionMatcher(String name, this._feature, matcher) - : super('`$name`:', '`$name`', matcher); - - @override - Object featureValueOf(covariant T actual) => _feature(actual); -} - -class HavingMatcher implements TypeMatcher { - final TypeMatcher _parent; - final List<_FunctionMatcher> _functionMatchers; - - HavingMatcher(TypeMatcher parent, String description, - Object Function(T) feature, dynamic matcher, - [Iterable<_FunctionMatcher> existing]) - : _parent = parent, - _functionMatchers = [ - ...?existing, - _FunctionMatcher(description, feature, matcher) - ]; - - @override - TypeMatcher having( - Object Function(T) feature, String description, dynamic matcher) => - HavingMatcher(_parent, description, feature, matcher, _functionMatchers); - - @override - bool matches(dynamic item, Map matchState) { - for (var matcher in [_parent].followedBy(_functionMatchers)) { - if (!matcher.matches(item, matchState)) { - addStateInfo(matchState, {'matcher': matcher}); - return false; - } - } - return true; - } - - @override - Description describeMismatch( - dynamic item, - Description mismatchDescription, - Map matchState, - bool verbose, - ) { - var matcher = matchState['matcher'] as Matcher; - matcher.describeMismatch( - item, mismatchDescription, matchState['state'] as Map, verbose); - return mismatchDescription; - } - - @override - Description describe(Description description) => description - .add('') - .addDescriptionOf(_parent) - .add(' with ') - .addAll('', ' and ', '', _functionMatchers); -} - -class TypeMatcher extends Matcher { - const TypeMatcher(); - - TypeMatcher having( - Object Function(T) feature, String description, dynamic matcher) => - HavingMatcher(this, description, feature, matcher); - - @override - Description describe(Description description) { - var name = _stripDynamic(T); - return description.add(""); - } - - @override - bool matches(Object item, Map matchState) => item is T; - - @override - Description describeMismatch( - dynamic item, - Description mismatchDescription, - Map matchState, - bool verbose, - ) { - var name = _stripDynamic(T); - return mismatchDescription.add("is not an instance of '$name'"); - } -} - -String _stripDynamic(Type type) => - type.toString().replaceAll(_dart2DynamicArgs, ''); -final _dart2DynamicArgs = RegExp(''); diff --git a/packages/get_navigation/.gitignore b/packages/get_navigation/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_navigation/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_navigation/.metadata b/packages/get_navigation/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_navigation/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_navigation/CHANGELOG.md b/packages/get_navigation/CHANGELOG.md deleted file mode 100644 index f9d3a4a6d..000000000 --- a/packages/get_navigation/CHANGELOG.md +++ /dev/null @@ -1,10 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 -* Fix defaultCustomTransition - -## [3.10.2] - -- initial release diff --git a/packages/get_navigation/LICENSE b/packages/get_navigation/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_navigation/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_navigation/README.md b/packages/get_navigation/README.md deleted file mode 100644 index 61fd12578..000000000 --- a/packages/get_navigation/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_navigation - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_navigation/analysis_options.yaml b/packages/get_navigation/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_navigation/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_navigation/lib/get_navigation.dart b/packages/get_navigation/lib/get_navigation.dart deleted file mode 100644 index 029912330..000000000 --- a/packages/get_navigation/lib/get_navigation.dart +++ /dev/null @@ -1,14 +0,0 @@ -library get_navigation; - -export 'package:get_core/get_core.dart'; -export 'src/bottomsheet/bottomsheet.dart'; -export 'src/extension_navigation.dart'; -export 'src/root/root_widget.dart'; -export 'src/routes/custom_transition.dart'; -export 'src/routes/default_route.dart'; -export 'src/routes/default_route.dart'; -export 'src/routes/get_route.dart'; -export 'src/routes/observers/route_observer.dart'; -export 'src/routes/transitions_type.dart'; -export 'src/snackbar/snack.dart'; -export 'src/snackbar/snack_route.dart'; diff --git a/packages/get_navigation/lib/src/bottomsheet/bottomsheet.dart b/packages/get_navigation/lib/src/bottomsheet/bottomsheet.dart deleted file mode 100644 index 11707dcd7..000000000 --- a/packages/get_navigation/lib/src/bottomsheet/bottomsheet.dart +++ /dev/null @@ -1,332 +0,0 @@ -import 'package:flutter/material.dart'; - -class GetModalBottomSheetRoute extends PopupRoute { - GetModalBottomSheetRoute({ - this.builder, - this.theme, - this.barrierLabel, - this.backgroundColor, - this.isPersistent, - this.elevation, - this.shape, - this.removeTop = true, - this.clipBehavior, - this.modalBarrierColor, - this.isDismissible = true, - this.enableDrag = true, - @required this.isScrollControlled, - RouteSettings settings, - this.enterBottomSheetDuration = const Duration(milliseconds: 250), - this.exitBottomSheetDuration = const Duration(milliseconds: 200), - }) : assert(isScrollControlled != null), - name = "BOTTOMSHEET: ${builder.hashCode}", - assert(isDismissible != null), - assert(enableDrag != null), - super(settings: settings); - final bool isPersistent; - final WidgetBuilder builder; - final ThemeData theme; - final bool isScrollControlled; - final Color backgroundColor; - final double elevation; - final ShapeBorder shape; - final Clip clipBehavior; - final Color modalBarrierColor; - final bool isDismissible; - final bool enableDrag; - final String name; - final Duration enterBottomSheetDuration; - final Duration exitBottomSheetDuration; - // remove safearea from top - final bool removeTop; - - @override - Duration get transitionDuration => Duration(milliseconds: 700); - - @override - bool get barrierDismissible => isDismissible; - - @override - final String barrierLabel; - - @override - Color get barrierColor => modalBarrierColor ?? Colors.black54; - - AnimationController _animationController; - - @override - AnimationController createAnimationController() { - assert(_animationController == null); - _animationController = - BottomSheet.createAnimationController(navigator.overlay); - _animationController.duration = enterBottomSheetDuration; - _animationController.reverseDuration = exitBottomSheetDuration; - return _animationController; - } - - @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { - final sheetTheme = - theme?.bottomSheetTheme ?? Theme.of(context).bottomSheetTheme; - // By definition, the bottom sheet is aligned to the bottom of the page - // and isn't exposed to the top padding of the MediaQuery. - Widget bottomSheet = MediaQuery.removePadding( - context: context, - removeTop: removeTop, - child: Padding( - padding: - EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), - child: _GetModalBottomSheet( - route: this, - backgroundColor: backgroundColor ?? - sheetTheme?.modalBackgroundColor ?? - sheetTheme?.backgroundColor, - elevation: - elevation ?? sheetTheme?.modalElevation ?? sheetTheme?.elevation, - shape: shape, - clipBehavior: clipBehavior, - isScrollControlled: isScrollControlled, - enableDrag: enableDrag, - ), - ), - ); - if (theme != null) bottomSheet = Theme(data: theme, child: bottomSheet); - return bottomSheet; - } -} - -class _GetModalBottomSheet extends StatefulWidget { - const _GetModalBottomSheet({ - Key key, - this.route, - this.backgroundColor, - this.elevation, - this.shape, - this.clipBehavior, - this.isScrollControlled = false, - this.enableDrag = true, - this.isPersistent = false, - }) : assert(isScrollControlled != null), - assert(enableDrag != null), - super(key: key); - final bool isPersistent; - final GetModalBottomSheetRoute route; - final bool isScrollControlled; - final Color backgroundColor; - final double elevation; - final ShapeBorder shape; - final Clip clipBehavior; - final bool enableDrag; - - @override - _GetModalBottomSheetState createState() => _GetModalBottomSheetState(); -} - -class _GetModalBottomSheetState extends State<_GetModalBottomSheet> { - String _getRouteLabel(MaterialLocalizations localizations) { - if ((Theme.of(context).platform == TargetPlatform.android) || - (Theme.of(context).platform == TargetPlatform.fuchsia)) { - return localizations.dialogLabel; - } else { - return ''; - } - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - assert(debugCheckHasMaterialLocalizations(context)); - final mediaQuery = MediaQuery.of(context); - final localizations = MaterialLocalizations.of(context); - final routeLabel = _getRouteLabel(localizations); - - return AnimatedBuilder( - animation: widget.route.animation, - builder: (context, child) { - // Disable the initial animation when accessible navigation is on so - // that the semantics are added to the tree at the correct time. - final animationValue = mediaQuery.accessibleNavigation - ? 1.0 - : widget.route.animation.value; - return Semantics( - scopesRoute: true, - namesRoute: true, - label: routeLabel, - explicitChildNodes: true, - child: ClipRect( - child: CustomSingleChildLayout( - delegate: _GetModalBottomSheetLayout( - animationValue, widget.isScrollControlled), - child: widget.isPersistent == false - ? BottomSheet( - animationController: widget.route._animationController, - onClosing: () { - if (widget.route.isCurrent) { - Navigator.pop(context); - } - }, - builder: widget.route.builder, - backgroundColor: widget.backgroundColor, - elevation: widget.elevation, - shape: widget.shape, - clipBehavior: widget.clipBehavior, - enableDrag: widget.enableDrag, - ) - : Scaffold( - bottomSheet: BottomSheet( - animationController: - widget.route._animationController, - onClosing: () { - // if (widget.route.isCurrent) { - // Navigator.pop(context); - // } - }, - builder: widget.route.builder, - backgroundColor: widget.backgroundColor, - elevation: widget.elevation, - shape: widget.shape, - clipBehavior: widget.clipBehavior, - enableDrag: widget.enableDrag, - ), - )), - ), - ); - }, - ); - } -} - -class _GetPerModalBottomSheet extends StatefulWidget { - const _GetPerModalBottomSheet({ - Key key, - this.route, - this.isPersistent, - this.backgroundColor, - this.elevation, - this.shape, - this.clipBehavior, - this.isScrollControlled = false, - this.enableDrag = true, - }) : assert(isScrollControlled != null), - assert(enableDrag != null), - super(key: key); - final bool isPersistent; - final GetModalBottomSheetRoute route; - final bool isScrollControlled; - final Color backgroundColor; - final double elevation; - final ShapeBorder shape; - final Clip clipBehavior; - final bool enableDrag; - - @override - // ignore: lines_longer_than_80_chars - _GetPerModalBottomSheetState createState() => - _GetPerModalBottomSheetState(); -} - -// ignore: lines_longer_than_80_chars -class _GetPerModalBottomSheetState - extends State<_GetPerModalBottomSheet> { - String _getRouteLabel(MaterialLocalizations localizations) { - if ((Theme.of(context).platform == TargetPlatform.android) || - (Theme.of(context).platform == TargetPlatform.fuchsia)) { - return localizations.dialogLabel; - } else { - return ''; - } - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasMediaQuery(context)); - assert(debugCheckHasMaterialLocalizations(context)); - final mediaQuery = MediaQuery.of(context); - final localizations = MaterialLocalizations.of(context); - final routeLabel = _getRouteLabel(localizations); - - return AnimatedBuilder( - animation: widget.route.animation, - builder: (context, child) { - // Disable the initial animation when accessible navigation is on so - // that the semantics are added to the tree at the correct time. - final animationValue = mediaQuery.accessibleNavigation - ? 1.0 - : widget.route.animation.value; - return Semantics( - scopesRoute: true, - namesRoute: true, - label: routeLabel, - explicitChildNodes: true, - child: ClipRect( - child: CustomSingleChildLayout( - delegate: _GetModalBottomSheetLayout( - animationValue, widget.isScrollControlled), - child: widget.isPersistent == false - ? BottomSheet( - animationController: widget.route._animationController, - onClosing: () { - if (widget.route.isCurrent) { - Navigator.pop(context); - } - }, - builder: widget.route.builder, - backgroundColor: widget.backgroundColor, - elevation: widget.elevation, - shape: widget.shape, - clipBehavior: widget.clipBehavior, - enableDrag: widget.enableDrag, - ) - : Scaffold( - bottomSheet: BottomSheet( - animationController: - widget.route._animationController, - onClosing: () { - // if (widget.route.isCurrent) { - // Navigator.pop(context); - // } - }, - builder: widget.route.builder, - backgroundColor: widget.backgroundColor, - elevation: widget.elevation, - shape: widget.shape, - clipBehavior: widget.clipBehavior, - enableDrag: widget.enableDrag, - ), - )), - ), - ); - }, - ); - } -} - -class _GetModalBottomSheetLayout extends SingleChildLayoutDelegate { - _GetModalBottomSheetLayout(this.progress, this.isScrollControlled); - - final double progress; - final bool isScrollControlled; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - return BoxConstraints( - minWidth: constraints.maxWidth, - maxWidth: constraints.maxWidth, - minHeight: 0.0, - maxHeight: isScrollControlled - ? constraints.maxHeight - : constraints.maxHeight * 9.0 / 16.0, - ); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - return Offset(0.0, size.height - childSize.height * progress); - } - - @override - bool shouldRelayout(_GetModalBottomSheetLayout oldDelegate) { - return progress != oldDelegate.progress; - } -} diff --git a/packages/get_navigation/lib/src/dialog/dialog_route.dart b/packages/get_navigation/lib/src/dialog/dialog_route.dart deleted file mode 100644 index 5ddb50f45..000000000 --- a/packages/get_navigation/lib/src/dialog/dialog_route.dart +++ /dev/null @@ -1,78 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_state_manager/get_state_manager.dart'; - -class GetDialogRoute extends PopupRoute { - GetDialogRoute({ - @required RoutePageBuilder pageBuilder, - bool barrierDismissible = true, - String barrierLabel, - Color barrierColor = const Color(0x80000000), - Duration transitionDuration = const Duration(milliseconds: 200), - RouteTransitionsBuilder transitionBuilder, - RouteSettings settings, - }) : assert(barrierDismissible != null), - widget = pageBuilder, - name = "DIALOG: ${pageBuilder.hashCode}", - _barrierDismissible = barrierDismissible, - _barrierLabel = barrierLabel, - _barrierColor = barrierColor, - _transitionDuration = transitionDuration, - _transitionBuilder = transitionBuilder, - super(settings: settings); - - final RoutePageBuilder widget; - - @override - bool get barrierDismissible => _barrierDismissible; - final bool _barrierDismissible; - - final String name; - - @override - void dispose() { - if (Get.smartManagement != SmartManagement.onlyBuilder) { - WidgetsBinding.instance.addPostFrameCallback( - (_) => GetInstance().removeDependencyByRoute(name)); - } - super.dispose(); - } - - @override - String get barrierLabel => _barrierLabel; - final String _barrierLabel; - - @override - Color get barrierColor => _barrierColor; - final Color _barrierColor; - - @override - Duration get transitionDuration => _transitionDuration; - final Duration _transitionDuration; - - final RouteTransitionsBuilder _transitionBuilder; - - @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { - return Semantics( - child: widget(context, animation, secondaryAnimation), - scopesRoute: true, - explicitChildNodes: true, - ); - } - - @override - Widget buildTransitions(BuildContext context, Animation animation, - Animation secondaryAnimation, Widget child) { - if (_transitionBuilder == null) { - return FadeTransition( - opacity: CurvedAnimation( - parent: animation, - curve: Curves.linear, - ), - child: child); - } // Some default transition - return _transitionBuilder(context, animation, secondaryAnimation, child); - } -} diff --git a/packages/get_navigation/lib/src/extension_navigation.dart b/packages/get_navigation/lib/src/extension_navigation.dart deleted file mode 100644 index 1ac836a40..000000000 --- a/packages/get_navigation/lib/src/extension_navigation.dart +++ /dev/null @@ -1,1095 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import 'package:get_utils/get_utils.dart'; -import '../get_navigation.dart'; -import 'dialog/dialog_route.dart'; -import 'root/parse_route.dart'; -import 'root/root_controller.dart'; -import 'routes/transitions_type.dart'; - -//TODO: Split this class on "Snackbar" "Dialog" "bottomSheet" -//and "navigation" extensions -extension GetNavigation on GetInterface { - /// **Navigation.push()** shortcut.

- /// - /// Pushes a new [page] to the stack - /// - /// It has the advantage of not needing context, - /// so you can call from your business logic - /// - /// You can set a custom [transition], and a transition [duration]. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// Just like native routing in Flutter, you can push a route - /// as a [fullscreenDialog], - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// If you want the same behavior of ios that pops a route when the user drag, - /// you can set [popGesture] to true - /// - /// If you're using the [Bindings] api, you must define it here - /// - /// By default, GetX will prevent you from push a route that you already in, - /// if you want to push anyway, set [preventDuplicates] to false - Future to( - Widget page, { - bool opaque, - Transition transition, - Curve curve, - Duration duration, - int id, - bool fullscreenDialog = false, - dynamic arguments, - Bindings binding, - bool preventDuplicates = true, - bool popGesture, - }) { - var routeName = "/${page.runtimeType.toString()}"; - if (preventDuplicates && routeName == currentRoute) { - return null; - } - return global(id)?.currentState?.push( - GetPageRoute( - opaque: opaque ?? true, - page: () => page, - routeName: routeName, - settings: RouteSettings( - // name: forceRouteName ? '${a.runtimeType}' : '', - arguments: arguments, - ), - popGesture: popGesture ?? defaultPopGesture, - transition: transition ?? defaultTransition, - curve: curve ?? defaultTransitionCurve, - fullscreenDialog: fullscreenDialog, - binding: binding, - transitionDuration: duration ?? defaultTransitionDuration, - ), - ); - } - - /// **Navigation.pushNamed()** shortcut.

- /// - /// Pushes a new named [page] to the stack. - /// - /// It has the advantage of not needing context, so you can call - /// from your business logic. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// By default, GetX will prevent you from push a route that you already in, - /// if you want to push anyway, set [preventDuplicates] to false - /// - /// Note: Always put a slash on the route ('/page1'), to avoid unnexpected errors - Future toNamed( - String page, { - dynamic arguments, - int id, - bool preventDuplicates = true, - }) { - if (preventDuplicates && page == currentRoute) { - return null; - } - return global(id)?.currentState?.pushNamed(page, arguments: arguments); - } - - /// **Navigation.pushReplacementNamed()** shortcut.

- /// - /// Pop the current named [page] in the stack and push a new one in its place - /// - /// It has the advantage of not needing context, so you can call - /// from your business logic. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// By default, GetX will prevent you from push a route that you already in, - /// if you want to push anyway, set [preventDuplicates] to false - /// - /// Note: Always put a slash on the route ('/page1'), to avoid unnexpected errors - Future offNamed( - String page, { - dynamic arguments, - int id, - bool preventDuplicates = true, - }) { - if (preventDuplicates && page == currentRoute) { - return null; - } - return global(id) - ?.currentState - ?.pushReplacementNamed(page, arguments: arguments); - } - - /// **Navigation.popUntil()** shortcut.

- /// - /// Calls pop several times in the stack until [predicate] returns true - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// [predicate] can be used like this: - /// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page, - /// - /// or also like this: - /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the - /// dialog is closed - void until(RoutePredicate predicate, {int id}) { - // if (key.currentState.mounted) // add this if appear problems on future with route navigate - // when widget don't mounted - return global(id)?.currentState?.popUntil(predicate); - } - - /// **Navigation.pushAndRemoveUntil()** shortcut.

- /// - /// Push the given [page], and then pop several pages in the stack until - /// [predicate] returns true - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// Obs: unlike other get methods, this one you need to send a function - /// that returns the widget to the page argument, like this: - /// Get.offUntil( () => HomePage() ) - /// - /// [predicate] can be used like this: - /// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page, - /// - /// or also like this: - /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog - /// is closed - Future offUntil(Route page, RoutePredicate predicate, {int id}) { - // if (key.currentState.mounted) // add this if appear problems on future with route navigate - // when widget don't mounted - return global(id)?.currentState?.pushAndRemoveUntil(page, predicate); - } - - /// **Navigation.pushNamedAndRemoveUntil()** shortcut.

- /// - /// Push the given named [page], and then pop several pages in the stack - /// until [predicate] returns true - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// [predicate] can be used like this: - /// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page, - /// or also like - /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog - /// is closed - /// - /// Note: Always put a slash on the route ('/page1'), to avoid unnexpected errors - Future offNamedUntil( - String page, - RoutePredicate predicate, { - int id, - dynamic arguments, - }) { - return global(id) - ?.currentState - ?.pushNamedAndRemoveUntil(page, predicate, arguments: arguments); - } - - /// **Navigation.popAndPushNamed()** shortcut.

- /// - /// Pop the current named page and pushes a new [page] to the stack - /// in its place - /// - /// You can send any type of value to the other route in the [arguments]. - /// It is very similar to `offNamed()` but use a different approach - /// - /// The `offNamed()` pop a page, and goes to the next. The - /// `offAndToNamed()` goes to the next page, and removes the previous one. - /// The route transition animation is different. - Future offAndToNamed( - String page, { - dynamic arguments, - int id, - dynamic result, - }) { - return global(id) - ?.currentState - ?.popAndPushNamed(page, arguments: arguments, result: result); - } - - /// **Navigation.removeRoute()** shortcut.

- /// - /// Remove a specific [route] from the stack - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - void removeRoute(Route route, {int id}) { - return global(id)?.currentState?.removeRoute(route); - } - - /// **Navigation.pushNamedAndRemoveUntil()** shortcut.

- /// - /// Push a named [page] and pop several pages in the stack - /// until [predicate] returns true. [predicate] is optional - /// - /// It has the advantage of not needing context, so you can - /// call from your business logic. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// [predicate] can be used like this: - /// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page, - /// or also like - /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog - /// is closed - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors - Future offAllNamed( - String newRouteName, { - RoutePredicate predicate, - dynamic arguments, - int id, - }) { - return global(id)?.currentState?.pushNamedAndRemoveUntil( - newRouteName, - predicate ?? (_) => false, - arguments: arguments, - ); - } - - /// Returns true if a Snackbar, Dialog or BottomSheet is currently OPEN - bool get isOverlaysOpen => - (isSnackbarOpen || isDialogOpen || isBottomSheetOpen); - - /// Returns true if there is no Snackbar, Dialog or BottomSheet open - bool get isOverlaysClosed => - (!isSnackbarOpen && !isDialogOpen && !isBottomSheetOpen); - - /// **Navigation.popUntil()** shortcut.

- /// - /// Pop the current page, snackbar, dialog or bottomsheet in the stack - /// - /// if your set [closeOverlays] to true, Get.back() will close the - /// currently open snackbar/dialog/bottomsheet AND the current page - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// It has the advantage of not needing context, so you can call - /// from your business logic. - void back({ - dynamic result, - bool closeOverlays = false, - bool canPop = true, - int id, - }) { - if (closeOverlays && isOverlaysOpen) { - navigator?.popUntil((route) { - return (isOverlaysClosed); - }); - } - if (canPop) { - if (global(id)?.currentState?.canPop() == true) { - global(id)?.currentState?.pop(result); - } - } else { - global(id)?.currentState?.pop(result); - } - } - - /// **Navigation.popUntil()** (with predicate) shortcut .

- /// - /// Close as many routes as defined by [times] - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - void close(int times, [int id]) { - if ((times == null) || (times < 1)) { - times = 1; - } - var count = 0; - var back = global(id)?.currentState?.popUntil((route) => count++ == times); - - return back; - } - - /// **Navigation.pushReplacement()** shortcut .

- /// - /// Pop the current page and pushes a new [page] to the stack - /// - /// It has the advantage of not needing context, - /// so you can call from your business logic - /// - /// You can set a custom [transition], define a Tween [curve], - /// and a transition [duration]. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// Just like native routing in Flutter, you can push a route - /// as a [fullscreenDialog], - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// If you want the same behavior of ios that pops a route when the user drag, - /// you can set [popGesture] to true - /// - /// If you're using the [Bindings] api, you must define it here - /// - /// By default, GetX will prevent you from push a route that you already in, - /// if you want to push anyway, set [preventDuplicates] to false - Future off( - Widget page, { - bool opaque = false, - Transition transition, - Curve curve, - bool popGesture, - int id, - dynamic arguments, - Bindings binding, - bool fullscreenDialog = false, - bool preventDuplicates = true, - Duration duration, - }) { - var routeName = "/${page.runtimeType.toString()}"; - if (preventDuplicates && routeName == currentRoute) { - return null; - } - return global(id)?.currentState?.pushReplacement(GetPageRoute( - opaque: opaque ?? true, - page: () => page, - binding: binding, - settings: RouteSettings(arguments: arguments), - routeName: routeName, - fullscreenDialog: fullscreenDialog, - popGesture: popGesture ?? defaultPopGesture, - transition: transition ?? defaultTransition, - curve: curve ?? defaultTransitionCurve, - transitionDuration: duration ?? defaultTransitionDuration)); - } - - /// **Navigation.pushAndRemoveUntil()** shortcut .

- /// - /// Push a [page] and pop several pages in the stack - /// until [predicate] returns true. [predicate] is optional - /// - /// It has the advantage of not needing context, - /// so you can call from your business logic - /// - /// You can set a custom [transition], a [curve] and a transition [duration]. - /// - /// You can send any type of value to the other route in the [arguments]. - /// - /// Just like native routing in Flutter, you can push a route - /// as a [fullscreenDialog], - /// - /// [predicate] can be used like this: - /// `Get.until((route) => Get.currentRoute == '/home')`so when you get to home page, - /// or also like - /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the dialog - /// is closed - /// - /// [id] is for when you are using nested navigation, - /// as explained in documentation - /// - /// If you want the same behavior of ios that pops a route when the user drag, - /// you can set [popGesture] to true - /// - /// If you're using the [Bindings] api, you must define it here - /// - /// By default, GetX will prevent you from push a route that you already in, - /// if you want to push anyway, set [preventDuplicates] to false - Future offAll( - Widget page, { - RoutePredicate predicate, - bool opaque = false, - bool popGesture, - int id, - dynamic arguments, - Bindings binding, - bool fullscreenDialog = false, - Transition transition, - Curve curve, - Duration duration, - }) { - var routeName = "/${page.runtimeType.toString()}"; - - return global(id)?.currentState?.pushAndRemoveUntil( - GetPageRoute( - opaque: opaque ?? true, - popGesture: popGesture ?? defaultPopGesture, - page: () => page, - binding: binding, - settings: RouteSettings(arguments: arguments), - fullscreenDialog: fullscreenDialog, - routeName: routeName, - transition: transition ?? defaultTransition, - curve: curve ?? defaultTransitionCurve, - transitionDuration: duration ?? defaultTransitionDuration, - ), - predicate ?? (route) => false); - } - - /// Show a dialog. - /// You can pass a [transitionDuration] and/or [transitionCurve], - /// overriding the defaults when the dialog shows up and closes. - /// When the dialog closes, uses those animations in reverse. - Future dialog( - Widget widget, { - bool barrierDismissible = true, - Color barrierColor, - bool useSafeArea = true, - bool useRootNavigator = true, - RouteSettings routeSettings, - Duration transitionDuration, - Curve transitionCurve, - }) { - assert(widget != null); - assert(barrierDismissible != null); - assert(useSafeArea != null); - assert(useRootNavigator != null); - assert(debugCheckHasMaterialLocalizations(context)); - - final theme = Theme.of(context, shadowThemeOnly: true); - return generalDialog( - pageBuilder: (buildContext, animation, secondaryAnimation) { - final pageChild = widget; - Widget dialog = Builder(builder: (context) { - return theme != null - ? Theme(data: theme, child: pageChild) - : pageChild; - }); - if (useSafeArea) { - dialog = SafeArea(child: dialog); - } - return dialog; - }, - barrierDismissible: barrierDismissible, - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - barrierColor: barrierColor ?? Colors.black54, - transitionDuration: transitionDuration ?? defaultDialogTransitionDuration, - transitionBuilder: (context, animation, secondaryAnimation, child) { - return FadeTransition( - opacity: CurvedAnimation( - parent: animation, - curve: transitionCurve ?? defaultDialogTransitionCurve, - ), - child: child, - ); - }, - useRootNavigator: useRootNavigator, - routeSettings: routeSettings, - ); - } - - /// Api from showGeneralDialog with no context - Future generalDialog({ - @required RoutePageBuilder pageBuilder, - bool barrierDismissible = false, - String barrierLabel, - Color barrierColor = const Color(0x80000000), - Duration transitionDuration = const Duration(milliseconds: 200), - RouteTransitionsBuilder transitionBuilder, - bool useRootNavigator = true, - RouteSettings routeSettings, - }) { - assert(pageBuilder != null); - assert(useRootNavigator != null); - assert(!barrierDismissible || barrierLabel != null); - return Navigator.of(overlayContext, rootNavigator: useRootNavigator) - .push(GetDialogRoute( - pageBuilder: pageBuilder, - barrierDismissible: barrierDismissible, - barrierLabel: barrierLabel, - barrierColor: barrierColor, - transitionDuration: transitionDuration, - transitionBuilder: transitionBuilder, - settings: routeSettings, - )); - } - - /// Custom UI Dialog. - Future defaultDialog({ - String title = "Alert", - TextStyle titleStyle, - Widget content, - VoidCallback onConfirm, - VoidCallback onCancel, - VoidCallback onCustom, - Color cancelTextColor, - Color confirmTextColor, - String textConfirm, - String textCancel, - String textCustom, - Widget confirm, - Widget cancel, - Widget custom, - Color backgroundColor, - bool barrierDismissible = true, - Color buttonColor, - String middleText = "Dialog made in 3 lines of code", - TextStyle middleTextStyle, - double radius = 20.0, - // ThemeData themeData, - List actions, - }) { - var leanCancel = onCancel != null || textCancel != null; - var leanConfirm = onConfirm != null || textConfirm != null; - actions ??= []; - - if (cancel != null) { - actions.add(cancel); - } else { - if (leanCancel) { - actions.add(FlatButton( - materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - onPressed: () { - onCancel?.call(); - back(); - }, - padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8), - child: Text( - textCancel ?? "Cancel", - style: TextStyle(color: cancelTextColor ?? theme.accentColor), - ), - shape: RoundedRectangleBorder( - side: BorderSide( - color: buttonColor ?? theme.accentColor, - width: 2, - style: BorderStyle.solid), - borderRadius: BorderRadius.circular(100)), - )); - } - } - if (confirm != null) { - actions.add(confirm); - } else { - if (leanConfirm) { - actions.add(FlatButton( - materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - color: buttonColor ?? theme.accentColor, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(100)), - child: Text( - textConfirm ?? "Ok", - style: TextStyle(color: confirmTextColor ?? theme.primaryColor), - ), - onPressed: () { - onConfirm?.call(); - })); - } - } - - return dialog( - AlertDialog( - titlePadding: EdgeInsets.all(8), - contentPadding: EdgeInsets.all(8), - backgroundColor: backgroundColor ?? theme.dialogBackgroundColor, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(radius))), - title: Text(title, textAlign: TextAlign.center, style: titleStyle), - content: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - content ?? - Text(middleText ?? "", - textAlign: TextAlign.center, style: middleTextStyle), - SizedBox(height: 16), - ButtonTheme( - minWidth: 78.0, - height: 34.0, - child: Wrap( - alignment: WrapAlignment.center, - spacing: 8, - runSpacing: 8, - children: actions, - ), - ) - ], - ), - // actions: actions, // ?? [cancelButton, confirmButton], - buttonPadding: EdgeInsets.zero, - ), - barrierDismissible: barrierDismissible, - ); - } - - Future bottomSheet( - Widget bottomsheet, { - Color backgroundColor, - double elevation, - bool persistent = true, - ShapeBorder shape, - Clip clipBehavior, - Color barrierColor, - bool ignoreSafeArea, - bool isScrollControlled = false, - bool useRootNavigator = false, - bool isDismissible = true, - bool enableDrag = true, - RouteSettings settings, - Duration enterBottomSheetDuration, - Duration exitBottomSheetDuration, - }) { - assert(bottomsheet != null); - assert(persistent != null); - assert(isScrollControlled != null); - assert(useRootNavigator != null); - assert(isDismissible != null); - assert(enableDrag != null); - - return Navigator.of(overlayContext, rootNavigator: useRootNavigator) - .push(GetModalBottomSheetRoute( - builder: (_) => bottomsheet, - isPersistent: persistent, - theme: Theme.of(key.currentContext, shadowThemeOnly: true), - isScrollControlled: isScrollControlled, - barrierLabel: - MaterialLocalizations.of(key.currentContext).modalBarrierDismissLabel, - backgroundColor: backgroundColor ?? Colors.transparent, - elevation: elevation, - shape: shape, - removeTop: ignoreSafeArea ?? true, - clipBehavior: clipBehavior, - isDismissible: isDismissible, - modalBarrierColor: barrierColor, - settings: settings, - enableDrag: enableDrag, - )); - } - - void rawSnackbar({ - String title, - String message, - Widget titleText, - Widget messageText, - Widget icon, - bool instantInit = true, - bool shouldIconPulse = true, - double maxWidth, - EdgeInsets margin = const EdgeInsets.all(0.0), - EdgeInsets padding = const EdgeInsets.all(16), - double borderRadius = 0.0, - Color borderColor, - double borderWidth = 1.0, - Color backgroundColor = const Color(0xFF303030), - Color leftBarIndicatorColor, - List boxShadows, - Gradient backgroundGradient, - FlatButton mainButton, - OnTap onTap, - Duration duration = const Duration(seconds: 3), - bool isDismissible = true, - SnackDismissDirection dismissDirection = SnackDismissDirection.VERTICAL, - bool showProgressIndicator = false, - AnimationController progressIndicatorController, - Color progressIndicatorBackgroundColor, - Animation progressIndicatorValueColor, - SnackPosition snackPosition = SnackPosition.BOTTOM, - SnackStyle snackStyle = SnackStyle.FLOATING, - Curve forwardAnimationCurve = Curves.easeOutCirc, - Curve reverseAnimationCurve = Curves.easeOutCirc, - Duration animationDuration = const Duration(seconds: 1), - SnackbarStatusCallback snackbarStatus, - double barBlur = 0.0, - double overlayBlur = 0.0, - Color overlayColor, - Form userInputForm, - }) async { - final getBar = GetBar( - snackbarStatus: snackbarStatus, - title: title, - message: message, - titleText: titleText, - messageText: messageText, - snackPosition: snackPosition, - borderRadius: borderRadius, - margin: margin, - duration: duration, - barBlur: barBlur, - backgroundColor: backgroundColor, - icon: icon, - shouldIconPulse: shouldIconPulse, - maxWidth: maxWidth, - padding: padding, - borderColor: borderColor, - borderWidth: borderWidth, - leftBarIndicatorColor: leftBarIndicatorColor, - boxShadows: boxShadows, - backgroundGradient: backgroundGradient, - mainButton: mainButton, - onTap: onTap, - isDismissible: isDismissible, - dismissDirection: dismissDirection, - showProgressIndicator: showProgressIndicator ?? false, - progressIndicatorController: progressIndicatorController, - progressIndicatorBackgroundColor: progressIndicatorBackgroundColor, - progressIndicatorValueColor: progressIndicatorValueColor, - snackStyle: snackStyle, - forwardAnimationCurve: forwardAnimationCurve, - reverseAnimationCurve: reverseAnimationCurve, - animationDuration: animationDuration, - overlayBlur: overlayBlur, - overlayColor: overlayColor, - userInputForm: userInputForm, - ); - - if (instantInit) { - getBar.show(); - } else { - SchedulerBinding.instance.addPostFrameCallback((_) { - getBar.show(); - }); - } - } - - Future showSnackbar(GetBar snackbar) { - return key?.currentState?.push(SnackRoute(snack: snackbar)); - } - - void snackbar( - String title, - String message, { - Color colorText, - Duration duration, - - /// with instantInit = false you can put snackbar on initState - bool instantInit = true, - SnackPosition snackPosition, - Widget titleText, - Widget messageText, - Widget icon, - bool shouldIconPulse, - double maxWidth, - EdgeInsets margin, - EdgeInsets padding, - double borderRadius, - Color borderColor, - double borderWidth, - Color backgroundColor, - Color leftBarIndicatorColor, - List boxShadows, - Gradient backgroundGradient, - FlatButton mainButton, - OnTap onTap, - bool isDismissible, - bool showProgressIndicator, - SnackDismissDirection dismissDirection, - AnimationController progressIndicatorController, - Color progressIndicatorBackgroundColor, - Animation progressIndicatorValueColor, - SnackStyle snackStyle, - Curve forwardAnimationCurve, - Curve reverseAnimationCurve, - Duration animationDuration, - double barBlur, - double overlayBlur, - SnackbarStatusCallback snackbarStatus, - Color overlayColor, - Form userInputForm, - }) async { - final getBar = GetBar( - snackbarStatus: snackbarStatus, - titleText: (title == null) - ? null - : titleText ?? - Text( - title, - style: TextStyle( - color: colorText ?? iconColor ?? Colors.black, - fontWeight: FontWeight.w800, - fontSize: 16, - ), - ), - messageText: messageText ?? - Text( - message, - style: TextStyle( - color: colorText ?? iconColor ?? Colors.black, - fontWeight: FontWeight.w300, - fontSize: 14, - ), - ), - snackPosition: snackPosition ?? SnackPosition.TOP, - borderRadius: borderRadius ?? 15, - margin: margin ?? EdgeInsets.symmetric(horizontal: 10), - duration: duration ?? Duration(seconds: 3), - barBlur: barBlur ?? 7.0, - backgroundColor: backgroundColor ?? Colors.grey.withOpacity(0.2), - icon: icon, - shouldIconPulse: shouldIconPulse ?? true, - maxWidth: maxWidth, - padding: padding ?? EdgeInsets.all(16), - borderColor: borderColor, - borderWidth: borderWidth, - leftBarIndicatorColor: leftBarIndicatorColor, - boxShadows: boxShadows, - backgroundGradient: backgroundGradient, - mainButton: mainButton, - onTap: onTap, - isDismissible: isDismissible ?? true, - dismissDirection: dismissDirection ?? SnackDismissDirection.VERTICAL, - showProgressIndicator: showProgressIndicator ?? false, - progressIndicatorController: progressIndicatorController, - progressIndicatorBackgroundColor: progressIndicatorBackgroundColor, - progressIndicatorValueColor: progressIndicatorValueColor, - snackStyle: snackStyle ?? SnackStyle.FLOATING, - forwardAnimationCurve: forwardAnimationCurve ?? Curves.easeOutCirc, - reverseAnimationCurve: reverseAnimationCurve ?? Curves.easeOutCirc, - animationDuration: animationDuration ?? Duration(seconds: 1), - overlayBlur: overlayBlur ?? 0.0, - overlayColor: overlayColor ?? Colors.transparent, - userInputForm: userInputForm); - - if (instantInit) { - showSnackbar(getBar); - } else { - routing.isSnackbar = true; - SchedulerBinding.instance.addPostFrameCallback((_) { - showSnackbar(getBar); - }); - } - } - - void addPages(List getPages) { - if (getPages != null) { - if (routeTree == null) { - routeTree = ParseRouteTree(); - } - - for (final element in getPages) { - routeTree.addRoute(element); - } - } - } - - void addPage(GetPage getPage) { - if (getPage != null) { - if (routeTree == null) routeTree = ParseRouteTree(); - routeTree.addRoute(getPage); - } - } - - /// change default config of Get - void config( - {bool enableLog, - LogWriterCallback logWriterCallback, - bool defaultPopGesture, - bool defaultOpaqueRoute, - Duration defaultDurationTransition, - bool defaultGlobalState, - Transition defaultTransition}) { - if (enableLog != null) { - Get.isLogEnable = enableLog; - } - if (logWriterCallback != null) { - Get.log = logWriterCallback; - } - if (defaultPopGesture != null) { - getxController.defaultPopGesture = defaultPopGesture; - } - if (defaultOpaqueRoute != null) { - getxController.defaultOpaqueRoute = defaultOpaqueRoute; - } - if (defaultTransition != null) { - getxController.defaultTransition = defaultTransition; - } - - if (defaultDurationTransition != null) { - getxController.defaultTransitionDuration = defaultDurationTransition; - } - } - - void updateLocale(Locale l) { - Get.locale = l; - forceAppUpdate(); - } - - void forceAppUpdate() { - void restart(Element element) { - element.markNeedsBuild(); - element.visitChildren(restart); - } - - restart(Get.context as Element); - } - - void appUpdate() => getxController.update(); - - void changeTheme(ThemeData theme) { - getxController.setTheme(theme); - } - - void changeThemeMode(ThemeMode themeMode) { - getxController.setThemeMode(themeMode); - } - - GlobalKey addKey(GlobalKey newKey) { - getxController.key = newKey; - return key; - } - - GlobalKey nestedKey(int key) { - keys.putIfAbsent(key, () => GlobalKey()); - return keys[key]; - } - - GlobalKey global(int k) { - GlobalKey _key; - if (k == null) { - _key = key; - } else { - if (!keys.containsKey(k)) { - throw 'Route id ($k) not found'; - } - _key = keys[k]; - } - - if (_key.currentContext == null) { - throw """You are trying to use contextless navigation without - a GetMaterialApp or Get.key. - If you are testing your app, you can use: - [Get.testMode = true], or if you are running your app on - a physical device or emulator, you must exchange your [MaterialApp] - for a [GetMaterialApp]. - """; - } - - return _key; - } - - @Deprecated(''' -Since version 2.8 it is possible to access the properties -[Get.arguments] and [Get.currentRoute] directly. -[routeSettings] is useless and should not be used.''') - RouteSettings get routeSettings => null; - - /// give current arguments - dynamic get arguments => routing.args; - - /// give name from current route - String get currentRoute => routing.current; - - /// give name from previous route - String get previousRoute => routing.previous; - - /// check if snackbar is open - bool get isSnackbarOpen => routing.isSnackbar; - - /// check if dialog is open - bool get isDialogOpen => routing.isDialog; - - /// check if bottomsheet is open - bool get isBottomSheetOpen => routing.isBottomSheet; - - /// check a raw current route - Route get rawRoute => routing.route; - - /// check if popGesture is enable - bool get isPopGestureEnable => defaultPopGesture; - - /// check if default opaque route is enable - bool get isOpaqueRouteDefault => defaultOpaqueRoute; - - /// give access to currentContext - BuildContext get context => key?.currentContext; - - /// give access to current Overlay Context - BuildContext get overlayContext => key?.currentState?.overlay?.context; - - /// give access to Theme.of(context) - ThemeData get theme { - ThemeData _theme; - if (context != null) { - _theme = Theme.of(context); - } - return _theme; - } - - /// give access to TextTheme.of(context) - TextTheme get textTheme => theme?.textTheme; - - /// give access to Mediaquery.of(context) - MediaQueryData get mediaQuery => MediaQuery.of(context); - - /// Check if dark mode theme is enable - bool get isDarkMode => (theme.brightness == Brightness.dark); - - /// Check if dark mode theme is enable on platform on android Q+ - bool get isPlatformDarkMode => - (mediaQuery.platformBrightness == Brightness.dark); - - /// give access to Theme.of(context).iconTheme.color - Color get iconColor => theme?.iconTheme?.color; - - /// give access to FocusScope.of(context) - FocusNode get focusScope => FocusManager.instance.primaryFocus; - - /// give access to Immutable MediaQuery.of(context).size.height - double get height => MediaQuery.of(context).size.height; - - /// give access to Immutable MediaQuery.of(context).size.width - double get width => MediaQuery.of(context).size.width; - - GlobalKey get key { - final _key = getxController?.key; - - return _key; - } - - Map> get keys => getxController?.keys; - - GetMaterialController get rootController => getxController; - - bool get defaultPopGesture => getxController.defaultPopGesture; - bool get defaultOpaqueRoute => getxController.defaultOpaqueRoute; - - Transition get defaultTransition => getxController.defaultTransition; - - Duration get defaultTransitionDuration { - return getxController.defaultTransitionDuration; - } - - Curve get defaultTransitionCurve => getxController.defaultTransitionCurve; - - Curve get defaultDialogTransitionCurve { - return getxController.defaultDialogTransitionCurve; - } - - Duration get defaultDialogTransitionDuration { - return getxController.defaultDialogTransitionDuration; - } - - Routing get routing => getxController.routing; - - Map get parameters => getxController.parameters; - set parameters(Map newParameters) => - getxController.parameters = newParameters; - - ParseRouteTree get routeTree => getxController.routeTree; - set routeTree(ParseRouteTree tree) => getxController.routeTree = tree; - - CustomTransition get customTransition => getxController.customTransition; - set customTransition(CustomTransition newTransition) => - getxController.customTransition = newTransition; - - bool get testMode => getxController.testMode; - set testMode(bool isTest) => getxController.testMode = isTest; - - static GetMaterialController getxController = GetMaterialController(); -} - -/// It replaces the Flutter Navigator, but needs no context. -/// You can to use navigator.push(YourRoute()) rather -/// Navigator.push(context, YourRoute()); -NavigatorState get navigator => GetNavigation(Get).key.currentState; diff --git a/packages/get_navigation/lib/src/root/parse_route.dart b/packages/get_navigation/lib/src/root/parse_route.dart deleted file mode 100644 index d71d660d5..000000000 --- a/packages/get_navigation/lib/src/root/parse_route.dart +++ /dev/null @@ -1,226 +0,0 @@ -import 'package:flutter/widgets.dart'; - -import '../routes/get_route.dart'; - -class ParseRouteTree { - final List<_ParseRouteTreeNode> _nodes = <_ParseRouteTreeNode>[]; - - // bool _hasDefaultRoute = false; - - void addRoute(GetPage route) { - var path = route.name; - - if (path == Navigator.defaultRouteName) { - // if (_hasDefaultRoute) { - // throw ("Default route was already defined"); - // } - var node = _ParseRouteTreeNode(path, _ParseRouteTreeNodeType.component); - node.routes = [route]; - _nodes.add(node); - // _hasDefaultRoute = true; - return; - } - if (path.startsWith("/")) { - path = path.substring(1); - } - var pathComponents = path.split('/'); - _ParseRouteTreeNode parent; - for (var i = 0; i < pathComponents.length; i++) { - var component = pathComponents[i]; - var node = _nodeForComponent(component, parent); - if (node == null) { - var type = _typeForComponent(component); - node = _ParseRouteTreeNode(component, type); - node.parent = parent; - if (parent == null) { - _nodes.add(node); - } else { - parent.nodes.add(node); - } - } - if (i == pathComponents.length - 1) { - if (node.routes == null) { - node.routes = [route]; - } else { - node.routes.add(route); - } - } - parent = node; - } - } - - _GetPageMatch matchRoute(String path) { - var usePath = path; - if (usePath.startsWith("/")) { - usePath = path.substring(1); - } - - // should take off url parameters first.. - final uri = Uri.tryParse(usePath); -// List components = usePath.split("/"); - var components = uri.pathSegments; - if (path == Navigator.defaultRouteName) { - components = ["/"]; - } - var nodeMatches = <_ParseRouteTreeNode, _ParseRouteTreeNodeMatch>{}; - var nodesToCheck = _nodes; - for (final checkComponent in components) { - final currentMatches = <_ParseRouteTreeNode, _ParseRouteTreeNodeMatch>{}; - final nextNodes = <_ParseRouteTreeNode>[]; - for (final node in nodesToCheck) { - var pathPart = checkComponent; - var queryMap = {}; - - if (checkComponent.contains("?") && !checkComponent.contains("=")) { - var splitParam = checkComponent.split("?"); - pathPart = splitParam[0]; - queryMap = {pathPart: splitParam[1]}; - } else if (checkComponent.contains("?")) { - var splitParam = checkComponent.split("?"); - var splitParam2 = splitParam[1].split("="); - if (!splitParam2[1].contains("&")) { - pathPart = splitParam[0]; - queryMap = {splitParam2[0]: splitParam2[1]}; - } else { - pathPart = splitParam[0]; - final second = splitParam[1]; - var other = second.split(RegExp(r"[&,=]")); - for (var i = 0; i < (other.length - 1); i++) { - var isOdd = (i % 2 == 0); - if (isOdd) { - queryMap.addAll({other[0 + i]: other[1 + i]}); - } - } - } - } - - final isMatch = (node.part == pathPart || node.isParameter()); - if (isMatch) { - final parentMatch = nodeMatches[node.parent]; - final match = _ParseRouteTreeNodeMatch.fromMatch(parentMatch, node); - - // TODO: find a way to clean this implementation. - match.parameters.addAll(uri.queryParameters); - - if (node.isParameter()) { - final paramKey = node.part.substring(1); - match.parameters[paramKey] = pathPart; - } - if (queryMap != null) { - match.parameters.addAll(queryMap); - } - - currentMatches[node] = match; - if (node.nodes != null) { - nextNodes.addAll(node.nodes); - } - } - } - nodeMatches = currentMatches; - nodesToCheck = nextNodes; - if (currentMatches.values.length == 0) { - return null; - } - } - var matches = nodeMatches.values.toList(); - if (matches.length > 0) { - var match = matches.first; - var nodeToUse = match.node; - - if (nodeToUse != null && - nodeToUse.routes != null && - nodeToUse.routes.length > 0) { - var routes = nodeToUse.routes; - var routeMatch = _GetPageMatch(routes[0]); - - routeMatch.parameters = match.parameters; - - return routeMatch; - } - } - return null; - } - - _ParseRouteTreeNode _nodeForComponent( - String component, - _ParseRouteTreeNode parent, - ) { - var nodes = _nodes; - if (parent != null) { - nodes = parent.nodes; - } - for (var node in nodes) { - if (node.part == component) { - return node; - } - } - return null; - } - - _ParseRouteTreeNodeType _typeForComponent(String component) { - var type = _ParseRouteTreeNodeType.component; - if (_isParameterComponent(component)) { - type = _ParseRouteTreeNodeType.parameter; - } - return type; - } - - bool _isParameterComponent(String component) { - return component.startsWith(":"); - } - - Map parseQueryString(String query) { - var search = RegExp('([^&=]+)=?([^&]*)'); - var params = {}; - if (query.startsWith('?')) query = query.substring(1); - decode(String s) => Uri.decodeComponent(s.replaceAll('+', ' ')); - - for (Match match in search.allMatches(query)) { - var key = decode(match.group(1)); - final value = decode(match.group(2)); - params[key] = value; - } - return params; - } -} - -class _ParseRouteTreeNodeMatch { - _ParseRouteTreeNodeMatch(this.node); - - _ParseRouteTreeNodeMatch.fromMatch( - _ParseRouteTreeNodeMatch match, this.node) { - parameters = {}; - if (match != null) { - parameters.addAll(match.parameters); - } - } - - _ParseRouteTreeNode node; - Map parameters = {}; -} - -class _ParseRouteTreeNode { - _ParseRouteTreeNode(this.part, this.type); - - String part; - _ParseRouteTreeNodeType type; - List routes = []; - List<_ParseRouteTreeNode> nodes = <_ParseRouteTreeNode>[]; - _ParseRouteTreeNode parent; - - bool isParameter() { - return type == _ParseRouteTreeNodeType.parameter; - } -} - -class _GetPageMatch { - _GetPageMatch(this.route); - - GetPage route; - Map parameters = {}; -} - -enum _ParseRouteTreeNodeType { - component, - parameter, -} diff --git a/packages/get_navigation/lib/src/root/root_controller.dart b/packages/get_navigation/lib/src/root/root_controller.dart deleted file mode 100644 index 7c0265ee9..000000000 --- a/packages/get_navigation/lib/src/root/root_controller.dart +++ /dev/null @@ -1,52 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import 'package:get_utils/get_utils.dart'; -import '../routes/custom_transition.dart'; -import '../routes/observers/route_observer.dart'; -import '../routes/transitions_type.dart'; -import 'parse_route.dart'; - -class GetMaterialController extends GetxController { - bool testMode = false; - Key unikey; - ThemeData theme; - ThemeMode themeMode; - - bool defaultPopGesture = GetPlatform.isIOS; - bool defaultOpaqueRoute = true; - - Transition defaultTransition; - Duration defaultTransitionDuration = Duration(milliseconds: 300); - Curve defaultTransitionCurve = Curves.easeOutQuad; - - Curve defaultDialogTransitionCurve = Curves.easeOutQuad; - - Duration defaultDialogTransitionDuration = Duration(milliseconds: 300); - - final routing = Routing(); - - Map parameters = {}; - - ParseRouteTree routeTree; - - CustomTransition customTransition; - - GlobalKey key = GlobalKey(); - - Map> keys = {}; - - void setTheme(ThemeData value) { - theme = value; - update(); - } - - void setThemeMode(ThemeMode value) { - themeMode = value; - update(); - } - - void restartApp() { - unikey = UniqueKey(); - update(); - } -} diff --git a/packages/get_navigation/lib/src/root/root_widget.dart b/packages/get_navigation/lib/src/root/root_widget.dart deleted file mode 100644 index 100ea61a7..000000000 --- a/packages/get_navigation/lib/src/root/root_widget.dart +++ /dev/null @@ -1,300 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import 'package:get_utils/get_utils.dart'; -import '../../get_navigation.dart'; -import 'root_controller.dart'; - -class GetMaterialApp extends StatelessWidget { - const GetMaterialApp({ - Key key, - this.navigatorKey, - this.home, - this.routes = const {}, - this.initialRoute, - this.onGenerateRoute, - this.onGenerateInitialRoutes, - this.onUnknownRoute, - this.navigatorObservers = const [], - this.builder, - this.translationsKeys, - this.translations, - this.textDirection, - this.title = '', - this.onGenerateTitle, - this.color, - this.customTransition, - this.onInit, - this.onDispose, - this.theme, - this.darkTheme, - this.themeMode = ThemeMode.system, - this.locale, - this.fallbackLocale, - this.localizationsDelegates, - this.localeListResolutionCallback, - this.localeResolutionCallback, - this.supportedLocales = const [Locale('en', 'US')], - this.debugShowMaterialGrid = false, - this.showPerformanceOverlay = false, - this.checkerboardRasterCacheImages = false, - this.checkerboardOffscreenLayers = false, - this.showSemanticsDebugger = false, - this.debugShowCheckedModeBanner = true, - this.shortcuts, - this.smartManagement = SmartManagement.full, - this.initialBinding, - this.unknownRoute, - this.routingCallback, - this.defaultTransition, - // this.actions, - this.getPages, - this.opaqueRoute, - this.enableLog, - this.logWriterCallback, - this.popGesture, - this.transitionDuration, - this.defaultGlobalState, - }) : assert(routes != null), - assert(navigatorObservers != null), - assert(title != null), - assert(debugShowMaterialGrid != null), - assert(showPerformanceOverlay != null), - assert(checkerboardRasterCacheImages != null), - assert(checkerboardOffscreenLayers != null), - assert(showSemanticsDebugger != null), - assert(debugShowCheckedModeBanner != null), - super(key: key); - - final GlobalKey navigatorKey; - final Widget home; - final Map routes; - final String initialRoute; - final RouteFactory onGenerateRoute; - final InitialRouteListFactory onGenerateInitialRoutes; - final RouteFactory onUnknownRoute; - final List navigatorObservers; - final TransitionBuilder builder; - final String title; - final GenerateAppTitle onGenerateTitle; - final ThemeData theme; - final ThemeData darkTheme; - final ThemeMode themeMode; - final CustomTransition customTransition; - final Color color; - final Map> translationsKeys; - final Translations translations; - final TextDirection textDirection; - final Locale locale; - final Locale fallbackLocale; - final Iterable> localizationsDelegates; - final LocaleListResolutionCallback localeListResolutionCallback; - final LocaleResolutionCallback localeResolutionCallback; - final Iterable supportedLocales; - final bool showPerformanceOverlay; - final bool checkerboardRasterCacheImages; - final bool checkerboardOffscreenLayers; - final bool showSemanticsDebugger; - final bool debugShowCheckedModeBanner; - final Map shortcuts; - - // final Map actions; - final bool debugShowMaterialGrid; - final Function(Routing) routingCallback; - final Transition defaultTransition; - final bool opaqueRoute; - final VoidCallback onInit; - final VoidCallback onDispose; - final bool enableLog; - final LogWriterCallback logWriterCallback; - final bool popGesture; - final SmartManagement smartManagement; - final Bindings initialBinding; - final Duration transitionDuration; - final bool defaultGlobalState; - final List getPages; - final GetPage unknownRoute; - - Route generator(RouteSettings settings) { - final match = Get.routeTree.matchRoute(settings.name); - Get.parameters = match?.parameters; - - if (match?.route == null) { - return GetPageRoute( - page: unknownRoute.page, - parameter: unknownRoute.parameter, - settings: - RouteSettings(name: settings.name, arguments: settings.arguments), - curve: unknownRoute.curve, - opaque: unknownRoute.opaque, - customTransition: unknownRoute.customTransition, - binding: unknownRoute.binding, - bindings: unknownRoute.bindings, - transitionDuration: - (unknownRoute.transitionDuration ?? Get.defaultTransitionDuration), - transition: unknownRoute.transition, - popGesture: unknownRoute.popGesture, - fullscreenDialog: unknownRoute.fullscreenDialog, - ); - } - - return GetPageRoute( - page: match.route.page, - parameter: match.route.parameter, - settings: - RouteSettings(name: settings.name, arguments: settings.arguments), - curve: match.route.curve, - opaque: match.route.opaque, - customTransition: match.route.customTransition, - binding: match.route.binding, - bindings: match.route.bindings, - transitionDuration: - (match.route.transitionDuration ?? Get.defaultTransitionDuration), - transition: match.route.transition, - popGesture: match.route.popGesture, - fullscreenDialog: match.route.fullscreenDialog, - ); - } - - List> initialRoutesGenerate(String name) { - final match = Get.routeTree.matchRoute(name); - Get.parameters = match?.parameters; - - //Route can be nullable, just pass the unknown route - if (match?.route == null) { - return [ - GetPageRoute( - page: unknownRoute.page, - parameter: unknownRoute.parameter, - settings: RouteSettings(name: name, arguments: null), - curve: unknownRoute.curve, - opaque: unknownRoute.opaque, - customTransition: unknownRoute.customTransition, - binding: unknownRoute.binding, - bindings: unknownRoute.bindings, - transitionDuration: (unknownRoute.transitionDuration ?? - Get.defaultTransitionDuration), - transition: unknownRoute.transition, - popGesture: unknownRoute.popGesture, - fullscreenDialog: unknownRoute.fullscreenDialog, - ) - ]; - } - - return [ - GetPageRoute( - page: match.route.page, - parameter: match.route.parameter, - settings: RouteSettings(name: name, arguments: null), - curve: match.route.curve, - opaque: match.route.opaque, - binding: match.route.binding, - bindings: match.route.bindings, - transitionDuration: - (match.route.transitionDuration ?? Get.defaultTransitionDuration), - transition: match.route.transition, - popGesture: match.route.popGesture, - fullscreenDialog: match.route.fullscreenDialog, - ) - ]; - } - - @override - Widget build(BuildContext context) { - return GetBuilder( - init: Get.rootController, - dispose: (d) { - onDispose?.call(); - }, - initState: (i) { - if (locale != null) Get.locale = locale; - - if (fallbackLocale != null) Get.fallbackLocale = fallbackLocale; - - if (translations != null) { - Get.addTranslations(translations.keys); - } else if (translationsKeys != null) { - Get.addTranslations(translationsKeys); - } - - Get.customTransition = customTransition; - - initialBinding?.dependencies(); - Get.addPages(getPages); - Get.smartManagement = smartManagement; - onInit?.call(); - - Get.config( - enableLog: enableLog ?? Get.isLogEnable, - logWriterCallback: logWriterCallback, - defaultTransition: defaultTransition ?? Get.defaultTransition, - defaultOpaqueRoute: opaqueRoute ?? Get.isOpaqueRouteDefault, - defaultPopGesture: popGesture ?? Get.isPopGestureEnable, - defaultDurationTransition: - transitionDuration ?? Get.defaultTransitionDuration, - ); - }, - builder: (_) { - return MaterialApp( - key: _.unikey, - navigatorKey: - (navigatorKey == null ? Get.key : Get.addKey(navigatorKey)), - home: home, - routes: routes ?? const {}, - initialRoute: initialRoute, - onGenerateRoute: (getPages != null ? generator : onGenerateRoute), - onGenerateInitialRoutes: (getPages == null || home != null) - ? onGenerateInitialRoutes - : initialRoutesGenerate, - onUnknownRoute: onUnknownRoute, - navigatorObservers: (navigatorObservers == null - ? [GetObserver(routingCallback, Get.routing)] - : [GetObserver(routingCallback, Get.routing)] - ..addAll(navigatorObservers)), - builder: (context, child) { - return Directionality( - textDirection: textDirection ?? - (rtlLanguages.contains(Get.locale?.languageCode) - ? TextDirection.rtl - : TextDirection.ltr), - child: builder == null ? child : builder(context, child), - ); - }, - title: title ?? '', - onGenerateTitle: onGenerateTitle, - color: color, - theme: _.theme ?? theme ?? ThemeData.fallback(), - darkTheme: darkTheme, - themeMode: _.themeMode ?? themeMode ?? ThemeMode.system, - locale: Get.locale ?? locale, - localizationsDelegates: localizationsDelegates, - localeListResolutionCallback: localeListResolutionCallback, - localeResolutionCallback: localeResolutionCallback, - supportedLocales: - supportedLocales ?? const [Locale('en', 'US')], - debugShowMaterialGrid: debugShowMaterialGrid ?? false, - showPerformanceOverlay: showPerformanceOverlay ?? false, - checkerboardRasterCacheImages: - checkerboardRasterCacheImages ?? false, - checkerboardOffscreenLayers: checkerboardOffscreenLayers ?? false, - showSemanticsDebugger: showSemanticsDebugger ?? false, - debugShowCheckedModeBanner: debugShowCheckedModeBanner ?? true, - shortcuts: shortcuts, - // actions: actions, - ); - }); - } -} - -const List rtlLanguages = [ - 'ar', // Arabic - 'fa', // Farsi - 'he', // Hebrew - 'ps', // Pashto - 'ur', -]; - -abstract class Translations { - Map> get keys; -} diff --git a/packages/get_navigation/lib/src/routes/custom_transition.dart b/packages/get_navigation/lib/src/routes/custom_transition.dart deleted file mode 100644 index b3e7d855d..000000000 --- a/packages/get_navigation/lib/src/routes/custom_transition.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flutter/widgets.dart'; - -// ignore: one_member_abstracts -abstract class CustomTransition { - Widget buildTransition( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child, - ); -} diff --git a/packages/get_navigation/lib/src/routes/default_route.dart b/packages/get_navigation/lib/src/routes/default_route.dart deleted file mode 100644 index 1e182ee17..000000000 --- a/packages/get_navigation/lib/src/routes/default_route.dart +++ /dev/null @@ -1,602 +0,0 @@ -import 'dart:math'; -import 'dart:ui' show lerpDouble; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import '../../get_navigation.dart'; -import 'custom_transition.dart'; -import 'default_transitions.dart'; -import 'transitions_type.dart'; - -class GetPageRoute extends PageRoute { - GetPageRoute({ - RouteSettings settings, - this.transitionDuration = const Duration(milliseconds: 300), - this.opaque = true, - this.parameter, - this.curve, - this.alignment, - this.transition, - this.popGesture, - this.customTransition, - this.barrierDismissible = false, - this.barrierColor, - this.binding, - this.bindings, - this.routeName, - this.page, - this.barrierLabel, - this.maintainState = true, - bool fullscreenDialog = false, - }) : assert(opaque != null), - assert(barrierDismissible != null), - assert(maintainState != null), - assert(fullscreenDialog != null), - super(settings: settings, fullscreenDialog: fullscreenDialog); - - @override - final Duration transitionDuration; - - final GetPageBuilder page; - - final String routeName; - - final CustomTransition customTransition; - - final Bindings binding; - - final Map parameter; - - final List bindings; - - @override - final bool opaque; - - final bool popGesture; - - @override - final bool barrierDismissible; - - final Transition transition; - - final Curve curve; - - final Alignment alignment; - - @override - final Color barrierColor; - - @override - final String barrierLabel; - - @override - final bool maintainState; - - @override - bool canTransitionTo(TransitionRoute nextRoute) { - // Don't perform outgoing animation if the next route is a - // fullscreen dialog. - return nextRoute is PageRoute && !nextRoute.fullscreenDialog; - } - - static bool _isPopGestureEnabled(PageRoute route) { - // ignore: lines_longer_than_80_chars - if (route.isFirst || - route.willHandlePopInternally || - route.hasScopedWillPopCallback || - route.fullscreenDialog || - route.animation.status != AnimationStatus.completed || - route.secondaryAnimation.status != AnimationStatus.dismissed || - isPopGestureInProgress(route)) return false; - - return true; - } - - static _CupertinoBackGestureController _startPopGesture( - PageRoute route) { - assert(_isPopGestureEnabled(route)); - - return _CupertinoBackGestureController( - navigator: route.navigator, - controller: route.controller, - ); - } - - @override - Widget buildPage( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - ) { - Get.reference = settings.name ?? routeName; - binding?.dependencies(); - if (bindings != null) { - for (final binding in bindings) { - binding.dependencies(); - } - } - // final pageWidget = page(); - return page(); - } - - static bool isPopGestureInProgress(PageRoute route) { - return route.navigator.userGestureInProgress; - } - - bool get popGestureInProgress => isPopGestureInProgress(this); - - @override - Widget buildTransitions(BuildContext context, Animation animation, - Animation secondaryAnimation, Widget child) { - final finalCurve = curve ?? Get.defaultTransitionCurve; - final hasCurve = curve != null; - if (fullscreenDialog && transition == null) { - /// by default, if no curve is defined, use Cupertino transition in the - /// default way (no linearTransition)... otherwise take the curve passed. - return CupertinoFullscreenDialogTransition( - primaryRouteAnimation: hasCurve - ? CurvedAnimation(parent: animation, curve: finalCurve) - : animation, - secondaryRouteAnimation: secondaryAnimation, - child: child, - linearTransition: hasCurve); - } - if (customTransition != null) { - return customTransition.buildTransition( - context, - finalCurve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child, - ); - } - - /// Apply the curve by default... - final iosAnimation = animation; - animation = CurvedAnimation(parent: animation, curve: finalCurve); - - switch (transition ?? Get.defaultTransition) { - case Transition.leftToRight: - return SlideLeftTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.downToUp: - return SlideDownTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.upToDown: - return SlideTopTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.noTransition: - return popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child; - - case Transition.rightToLeft: - return SlideRightTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.zoom: - return ZoomInTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.fadeIn: - return FadeInTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.rightToLeftWithFade: - return RightToLeftFadeTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.leftToRightWithFade: - return LeftToRightFadeTransition().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.cupertino: - return CupertinoPageTransitionsBuilder().buildTransitions( - this, - context, - iosAnimation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.size: - return SizeTransitions().buildTransitions( - context, - curve, - alignment, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.fade: - return FadeUpwardsPageTransitionsBuilder().buildTransitions( - this, - context, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.topLevel: - return ZoomPageTransitionsBuilder().buildTransitions( - this, - context, - animation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - case Transition.native: - return PageTransitionsTheme().buildTransitions( - this, - context, - iosAnimation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - - default: - if (Get.customTransition != null) { - return Get.customTransition.buildTransition( - context, curve, alignment, animation, secondaryAnimation, child); - } - - return PageTransitionsTheme().buildTransitions( - this, - context, - iosAnimation, - secondaryAnimation, - popGesture ?? Get.defaultPopGesture - ? _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(this), - onStartPopGesture: () => _startPopGesture(this), - child: child) - : child); - } - } - - @override - void dispose() { - if (Get.smartManagement != SmartManagement.onlyBuilder) { - WidgetsBinding.instance.addPostFrameCallback((_) => GetInstance() - .removeDependencyByRoute("${settings?.name ?? routeName}")); - } - super.dispose(); - } -} - -const double _kBackGestureWidth = 20.0; -const double _kMinFlingVelocity = 1.0; -const int _kMaxDroppedSwipePageForwardAnimationTime = 800; // Milliseconds. - -// The maximum time for a page to get reset to it's original position if the -// user releases a page mid swipe. -const int _kMaxPageBackAnimationTime = 300; - -class _CupertinoBackGestureDetector extends StatefulWidget { - const _CupertinoBackGestureDetector({ - Key key, - @required this.enabledCallback, - @required this.onStartPopGesture, - @required this.child, - }) : assert(enabledCallback != null), - assert(onStartPopGesture != null), - assert(child != null), - super(key: key); - - final Widget child; - - final ValueGetter enabledCallback; - - final ValueGetter<_CupertinoBackGestureController> onStartPopGesture; - - @override - _CupertinoBackGestureDetectorState createState() => - _CupertinoBackGestureDetectorState(); -} - -class _CupertinoBackGestureDetectorState - extends State<_CupertinoBackGestureDetector> { - _CupertinoBackGestureController _backGestureController; - - HorizontalDragGestureRecognizer _recognizer; - - @override - void initState() { - super.initState(); - _recognizer = HorizontalDragGestureRecognizer(debugOwner: this) - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..onCancel = _handleDragCancel; - } - - @override - void dispose() { - _recognizer.dispose(); - super.dispose(); - } - - void _handleDragStart(DragStartDetails details) { - assert(mounted); - assert(_backGestureController == null); - _backGestureController = widget.onStartPopGesture(); - } - - void _handleDragUpdate(DragUpdateDetails details) { - assert(mounted); - assert(_backGestureController != null); - _backGestureController.dragUpdate( - _convertToLogical(details.primaryDelta / context.size.width)); - } - - void _handleDragEnd(DragEndDetails details) { - assert(mounted); - assert(_backGestureController != null); - _backGestureController.dragEnd(_convertToLogical( - details.velocity.pixelsPerSecond.dx / context.size.width)); - _backGestureController = null; - } - - void _handleDragCancel() { - assert(mounted); - // This can be called even if start is not called, paired with - // the "down" event that we don't consider here. - _backGestureController?.dragEnd(0.0); - _backGestureController = null; - } - - void _handlePointerDown(PointerDownEvent event) { - if (widget.enabledCallback()) _recognizer.addPointer(event); - } - - double _convertToLogical(double value) { - switch (Directionality.of(context)) { - case TextDirection.rtl: - return -value; - case TextDirection.ltr: - return value; - } - // FIXME: shouldn't we return a default here? - // or perhaps throw error - // ignore: avoid_returning_null - return null; - } - - @override - Widget build(BuildContext context) { - assert(debugCheckHasDirectionality(context)); - // For devices with notches, the drag area needs to be larger on the side - // that has the notch. - var dragAreaWidth = Directionality.of(context) == TextDirection.ltr - ? MediaQuery.of(context).padding.left - : MediaQuery.of(context).padding.right; - dragAreaWidth = max(dragAreaWidth, _kBackGestureWidth); - return Stack( - fit: StackFit.passthrough, - children: [ - widget.child, - PositionedDirectional( - start: 0.0, - width: dragAreaWidth, - top: 0.0, - bottom: 0.0, - child: Listener( - onPointerDown: _handlePointerDown, - behavior: HitTestBehavior.translucent, - ), - ), - ], - ); - } -} - -class _CupertinoBackGestureController { - /// Creates a controller for an iOS-style back gesture. - /// - /// The [navigator] and [controller] arguments must not be null. - _CupertinoBackGestureController({ - @required this.navigator, - @required this.controller, - }) : assert(navigator != null), - assert(controller != null) { - navigator.didStartUserGesture(); - } - - final AnimationController controller; - final NavigatorState navigator; - - /// The drag gesture has changed by [fractionalDelta]. The total range of the - /// drag should be 0.0 to 1.0. - void dragUpdate(double delta) { - controller.value -= delta; - } - - /// The drag gesture has ended with a horizontal motion of - /// [fractionalVelocity] as a fraction of screen width per second. - void dragEnd(double velocity) { - // Fling in the appropriate direction. - // AnimationController.fling is guaranteed to - // take at least one frame. - // - // This curve has been determined through rigorously eyeballing native iOS - // animations. - const Curve animationCurve = Curves.fastLinearToSlowEaseIn; - bool animateForward; - - // If the user releases the page before mid screen with sufficient velocity, - // or after mid screen, we should animate the page out. Otherwise, the page - // should be animated back in. - if (velocity.abs() >= _kMinFlingVelocity) { - animateForward = velocity <= 0; - } else { - animateForward = controller.value > 0.5; - } - - if (animateForward) { - // The closer the panel is to dismissing, the shorter the animation is. - // We want to cap the animation time, but we want to use a linear curve - // to determine it. - final droppedPageForwardAnimationTime = min( - lerpDouble( - _kMaxDroppedSwipePageForwardAnimationTime, - 0, - controller.value, - ).floor(), - _kMaxPageBackAnimationTime, - ); - controller.animateTo(1.0, - duration: Duration(milliseconds: droppedPageForwardAnimationTime), - curve: animationCurve); - } else { - // This route is destined to pop at this point. Reuse navigator's pop. - navigator.pop(); - - // The popping may have finished inline if already at the target - // destination. - if (controller.isAnimating) { - // Otherwise, use a custom popping animation duration and curve. - final droppedPageBackAnimationTime = lerpDouble( - 0, - _kMaxDroppedSwipePageForwardAnimationTime, - controller.value, - ).floor(); - controller.animateBack( - 0.0, - duration: Duration(milliseconds: droppedPageBackAnimationTime), - curve: animationCurve, - ); - } - } - - if (controller.isAnimating) { - // Keep the userGestureInProgress in true state so we don't change the - // curve of the page transition mid-flight since CupertinoPageTransition - // depends on userGestureInProgress. - AnimationStatusListener animationStatusCallback; - animationStatusCallback = (status) { - navigator.didStopUserGesture(); - controller.removeStatusListener(animationStatusCallback); - }; - controller.addStatusListener(animationStatusCallback); - } else { - navigator.didStopUserGesture(); - } - } -} diff --git a/packages/get_navigation/lib/src/routes/default_transitions.dart b/packages/get_navigation/lib/src/routes/default_transitions.dart deleted file mode 100644 index 992c3914a..000000000 --- a/packages/get_navigation/lib/src/routes/default_transitions.dart +++ /dev/null @@ -1,187 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; - -class LeftToRightFadeTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: const Offset(-1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: FadeTransition( - opacity: animation, - child: SlideTransition( - position: Tween( - begin: Offset.zero, - end: const Offset(1.0, 0.0), - ).animate(secondaryAnimation), - child: child), - ), - ); - } -} - -class RightToLeftFadeTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: const Offset(1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: FadeTransition( - opacity: animation, - child: SlideTransition( - position: Tween( - begin: Offset.zero, - end: const Offset(-1.0, 0.0), - ).animate(secondaryAnimation), - child: child), - ), - ); - } -} - -class NoTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return child; - } -} - -class FadeInTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return FadeTransition(opacity: animation, child: child); - } -} - -class SlideDownTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: Offset(0.0, 1.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - } -} - -class SlideLeftTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: Offset(-1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - } -} - -class SlideRightTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: Offset(1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - } -} - -class SlideTopTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return SlideTransition( - position: Tween( - begin: Offset(0.0, -1.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - } -} - -class ZoomInTransition { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return ScaleTransition( - scale: animation, - child: child, - ); - } -} - -class SizeTransitions { - Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return Align( - alignment: Alignment.center, - child: SizeTransition( - sizeFactor: CurvedAnimation( - parent: animation, - curve: curve, - ), - child: child, - ), - ); - } -} - diff --git a/packages/get_navigation/lib/src/routes/get_route.dart b/packages/get_navigation/lib/src/routes/get_route.dart deleted file mode 100644 index 95714fb54..000000000 --- a/packages/get_navigation/lib/src/routes/get_route.dart +++ /dev/null @@ -1,45 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import 'custom_transition.dart'; -import 'transitions_type.dart'; - -class GetPage { - final String name; - final GetPageBuilder page; - final bool popGesture; - final Map parameter; - final String title; - final Transition transition; - final Curve curve; - final Alignment alignment; - final bool maintainState; - final bool opaque; - final Bindings binding; - final List bindings; - final CustomTransition customTransition; - final Duration transitionDuration; - final bool fullscreenDialog; - final RouteSettings settings; - - const GetPage({ - @required this.name, - @required this.page, - this.title, - this.settings, - this.maintainState = true, - this.curve = Curves.linear, - this.alignment, - this.parameter, - this.opaque = true, - this.transitionDuration, - this.popGesture, - this.binding, - this.bindings, - this.transition, - this.customTransition, - this.fullscreenDialog = false, - }) : assert(page != null), - assert(name != null), - assert(maintainState != null), - assert(fullscreenDialog != null); -} diff --git a/packages/get_navigation/lib/src/routes/observers/route_observer.dart b/packages/get_navigation/lib/src/routes/observers/route_observer.dart deleted file mode 100644 index 91302999a..000000000 --- a/packages/get_navigation/lib/src/routes/observers/route_observer.dart +++ /dev/null @@ -1,207 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:get_core/get_core.dart'; -import '../../../get_navigation.dart'; -import '../../dialog/dialog_route.dart'; -import '../../snackbar/snack_route.dart'; -import '../default_route.dart'; - -class Routing { - String current; - String previous; - dynamic args; - String removed; - Route route; - bool isBack; - bool isSnackbar; - bool isBottomSheet; - bool isDialog; - - Routing({ - this.current = '', - this.previous = '', - this.args, - this.removed = '', - this.route, - this.isBack, - this.isSnackbar, - this.isBottomSheet, - this.isDialog, - }); - - void update(void fn(Routing value)) { - fn(this); - } -} - -/// Extracts the name of a route based on it's instance type -/// or null if not possible. -String _extractRouteName(Route route) { - if (route?.settings?.name != null) { - return route.settings.name; - } - - if (route is GetPageRoute) { - return route.routeName; - } - - if (route is GetDialogRoute) { - return route.name; - } - - if (route is GetModalBottomSheetRoute) { - return route.name; - } - - return null; -} - -/// This is basically a util for rules about 'what a route is' -class _RouteData { - final bool isGetPageRoute; - final bool isSnackbar; - final bool isBottomSheet; - final bool isDialog; - final String name; - - _RouteData({ - @required this.name, - @required this.isGetPageRoute, - @required this.isSnackbar, - @required this.isBottomSheet, - @required this.isDialog, - }); - - factory _RouteData.ofRoute(Route route) { - return _RouteData( - name: _extractRouteName(route), - isGetPageRoute: route is GetPageRoute, - isSnackbar: route is SnackRoute, - isDialog: route is GetDialogRoute, - isBottomSheet: route is GetModalBottomSheetRoute, - ); - } -} - -class GetObserver extends NavigatorObserver { - final Function(Routing) routing; - - GetObserver([this.routing, this._routeSend]); - - final Routing _routeSend; - - @override - void didPush(Route route, Route previousRoute) { - super.didPush(route, previousRoute); - final newRoute = _RouteData.ofRoute(route); - - if (newRoute.isSnackbar) { - Get.log("OPEN SNACKBAR ${newRoute.name}"); - } else if (newRoute.isBottomSheet || newRoute.isDialog) { - Get.log("OPEN ${newRoute.name}"); - } else if (newRoute.isGetPageRoute) { - Get.log("GOING TO ROUTE ${newRoute.name}"); - } - - Get.reference = newRoute.name; - _routeSend?.update((value) { - // Only PageRoute is allowed to change current value - if (route is PageRoute) { - value.current = newRoute.name ?? ''; - } - - value.args = route?.settings?.arguments; - value.route = route; - value.isBack = false; - value.removed = ''; - value.previous = _extractRouteName(previousRoute) ?? ''; - value.isSnackbar = newRoute.isSnackbar; - value.isBottomSheet = newRoute.isBottomSheet; - value.isDialog = newRoute.isDialog; - }); - - if (routing != null) { - routing(_routeSend); - } - } - - @override - void didPop(Route route, Route previousRoute) { - super.didPop(route, previousRoute); - final newRoute = _RouteData.ofRoute(route); - - if (newRoute.isSnackbar) { - Get.log("CLOSE SNACKBAR ${newRoute.name}"); - } else if (newRoute.isBottomSheet || newRoute.isDialog) { - Get.log("CLOSE ${newRoute.name}"); - } else if (newRoute.isGetPageRoute) { - Get.log("CLOSE TO ROUTE ${newRoute.name}"); - } - - Get.reference = newRoute.name; - // Here we use a 'inverse didPush set', meaning that we use - // previous route instead of 'route' because this is - // a 'inverse push' - _routeSend?.update((value) { - // Only PageRoute is allowed to change current value - if (previousRoute is PageRoute) { - value.current = _extractRouteName(previousRoute) ?? ''; - } - - value.args = route?.settings?.arguments; - value.route = previousRoute; - value.isBack = true; - value.removed = ''; - value.previous = newRoute.name ?? ''; - value.isSnackbar = false; - value.isBottomSheet = false; - value.isDialog = false; - }); - - routing?.call(_routeSend); - } - - @override - void didReplace({Route newRoute, Route oldRoute}) { - super.didReplace(newRoute: newRoute, oldRoute: oldRoute); - final newName = _extractRouteName(newRoute); - final oldName = _extractRouteName(oldRoute); - - Get.log("REPLACE ROUTE $oldName"); - Get.log("NEW ROUTE $newName"); - - Get.reference = newName; - _routeSend?.update((value) { - // Only PageRoute is allowed to change current value - if (newRoute is PageRoute) { - value.current = newName ?? ''; - } - - value.args = newRoute?.settings?.arguments; - value.route = newRoute; - value.isBack = false; - value.removed = ''; - value.previous = '$oldName'; - value.isSnackbar = false; - value.isBottomSheet = false; - value.isDialog = false; - }); - - routing?.call(_routeSend); - } - - @override - void didRemove(Route route, Route previousRoute) { - super.didRemove(route, previousRoute); - final routeName = _extractRouteName(route); - - Get.log("REMOVING ROUTE $routeName"); - _routeSend?.update((value) { - value.route = previousRoute; - value.isBack = false; - value.removed = routeName ?? ''; - value.previous = routeName ?? ''; - }); - - routing?.call(_routeSend); - } -} diff --git a/packages/get_navigation/lib/src/routes/transitions_component.dart b/packages/get_navigation/lib/src/routes/transitions_component.dart deleted file mode 100644 index bf735e5cb..000000000 --- a/packages/get_navigation/lib/src/routes/transitions_component.dart +++ /dev/null @@ -1,13 +0,0 @@ -import 'package:flutter/widgets.dart'; - -class TransitionComponent { - Widget buildChildWithTransition( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return child; - } -} diff --git a/packages/get_navigation/lib/src/routes/transitions_type.dart b/packages/get_navigation/lib/src/routes/transitions_type.dart deleted file mode 100644 index 47bee2413..000000000 --- a/packages/get_navigation/lib/src/routes/transitions_type.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:flutter/widgets.dart'; - -enum Transition { - fade, - fadeIn, - rightToLeft, - leftToRight, - upToDown, - downToUp, - rightToLeftWithFade, - leftToRightWithFade, - zoom, - topLevel, - noTransition, - cupertino, - cupertinoDialog, - size, - native -} - -typedef GetPageBuilder = Widget Function(); diff --git a/packages/get_navigation/lib/src/snackbar/snack.dart b/packages/get_navigation/lib/src/snackbar/snack.dart deleted file mode 100644 index e6d0d24f5..000000000 --- a/packages/get_navigation/lib/src/snackbar/snack.dart +++ /dev/null @@ -1,688 +0,0 @@ -import 'dart:async'; -import 'dart:ui'; -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:get_core/get_core.dart'; -import '../../get_navigation.dart'; - -typedef SnackbarStatusCallback = void Function(SnackbarStatus status); -typedef OnTap = void Function(GetBar snack); - -// ignore: must_be_immutable -class GetBar extends StatefulWidget { - GetBar({ - Key key, - this.title, - this.message, - this.titleText, - this.messageText, - this.icon, - this.shouldIconPulse = true, - this.maxWidth, - this.margin = const EdgeInsets.all(0.0), - this.padding = const EdgeInsets.all(16), - this.borderRadius = 0.0, - this.borderColor, - this.borderWidth = 1.0, - this.backgroundColor = const Color(0xFF303030), - this.leftBarIndicatorColor, - this.boxShadows, - this.backgroundGradient, - this.mainButton, - this.onTap, - this.duration, - this.isDismissible = true, - this.dismissDirection = SnackDismissDirection.VERTICAL, - this.showProgressIndicator = false, - this.progressIndicatorController, - this.progressIndicatorBackgroundColor, - this.progressIndicatorValueColor, - this.snackPosition = SnackPosition.BOTTOM, - this.snackStyle = SnackStyle.FLOATING, - this.forwardAnimationCurve = Curves.easeOutCirc, - this.reverseAnimationCurve = Curves.easeOutCirc, - this.animationDuration = const Duration(seconds: 1), - this.barBlur = 0.0, - this.overlayBlur = 0.0, - this.overlayColor = Colors.transparent, - this.userInputForm, - SnackbarStatusCallback snackbarStatus, - }) : super(key: key) { - this.snackbarStatus = snackbarStatus ?? (status) {}; - } - - /// A callback for you to listen to the different Snack status - SnackbarStatusCallback snackbarStatus; - - /// The title displayed to the user - final String title; - - /// The message displayed to the user. - final String message; - - /// Replaces [title]. Although this accepts a [Widget], it is meant - /// to receive [Text] or [RichText] - final Widget titleText; - - /// Replaces [message]. Although this accepts a [Widget], it is meant - /// to receive [Text] or [RichText] - final Widget messageText; - - /// Will be ignored if [backgroundGradient] is not null - final Color backgroundColor; - - /// If not null, shows a left vertical colored bar on notification. - /// It is not possible to use it with a [Form] and I do not recommend - /// using it with [LinearProgressIndicator] - final Color leftBarIndicatorColor; - - /// [boxShadows] The shadows generated by Snack. Leave it null - /// if you don't want a shadow. - /// You can use more than one if you feel the need. - /// Check (this example)[https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/shadows.dart] - final List boxShadows; - - /// Makes [backgroundColor] be ignored. - final Gradient backgroundGradient; - - /// You can use any widget here, but I recommend [Icon] or [Image] as - /// indication of what kind - /// of message you are displaying. Other widgets may break the layout - final Widget icon; - - /// An option to animate the icon (if present). Defaults to true. - final bool shouldIconPulse; - - /// A [FlatButton] widget if you need an action from the user. - final FlatButton mainButton; - - /// A callback that registers the user's click anywhere. - /// An alternative to [mainButton] - final OnTap onTap; - - /// How long until Snack will hide itself (be dismissed). - /// To make it indefinite, leave it null. - final Duration duration; - - /// True if you want to show a [LinearProgressIndicator]. - final bool showProgressIndicator; - - /// An optional [AnimationController] when you want to control the - /// progress of your [LinearProgressIndicator]. - final AnimationController progressIndicatorController; - - /// A [LinearProgressIndicator] configuration parameter. - final Color progressIndicatorBackgroundColor; - - /// A [LinearProgressIndicator] configuration parameter. - final Animation progressIndicatorValueColor; - - /// Determines if the user can swipe or click the overlay - /// (if [overlayBlur] > 0) to dismiss. - /// It is recommended that you set [duration] != null if this is false. - /// If the user swipes to dismiss or clicks the overlay, no value - /// will be returned. - final bool isDismissible; - - /// Used to limit Snack width (usually on large screens) - final double maxWidth; - - /// Adds a custom margin to Snack - final EdgeInsets margin; - - /// Adds a custom padding to Snack - /// The default follows material design guide line - final EdgeInsets padding; - - /// Adds a radius to all corners of Snack. Best combined with [margin]. - /// I do not recommend using it with [showProgressIndicator] - /// or [leftBarIndicatorColor]. - final double borderRadius; - - /// Adds a border to every side of Snack - /// I do not recommend using it with [showProgressIndicator] - /// or [leftBarIndicatorColor]. - final Color borderColor; - - /// Changes the width of the border if [borderColor] is specified - final double borderWidth; - - /// Snack can be based on [SnackPosition.TOP] or on [SnackPosition.BOTTOM] - /// of your screen. - /// [SnackPosition.BOTTOM] is the default. - final SnackPosition snackPosition; - - /// [SnackDismissDirection.VERTICAL] by default. - /// Can also be [SnackDismissDirection.HORIZONTAL] in which case both left - /// and right dismiss are allowed. - final SnackDismissDirection dismissDirection; - - /// Snack can be floating or be grounded to the edge of the screen. - /// If grounded, I do not recommend using [margin] or [borderRadius]. - /// [SnackStyle.FLOATING] is the default - /// If grounded, I do not recommend using a [backgroundColor] with - /// transparency or [barBlur] - final SnackStyle snackStyle; - - /// The [Curve] animation used when show() is called. - /// [Curves.easeOut] is default - final Curve forwardAnimationCurve; - - /// The [Curve] animation used when dismiss() is called. - /// [Curves.fastOutSlowIn] is default - final Curve reverseAnimationCurve; - - /// Use it to speed up or slow down the animation duration - final Duration animationDuration; - - /// Default is 0.0. If different than 0.0, blurs only Snack's background. - /// To take effect, make sure your [backgroundColor] has some opacity. - /// The greater the value, the greater the blur. - final double barBlur; - - /// Default is 0.0. If different than 0.0, creates a blurred - /// overlay that prevents the user from interacting with the screen. - /// The greater the value, the greater the blur. - final double overlayBlur; - - /// Default is [Colors.transparent]. Only takes effect if [overlayBlur] > 0.0. - /// Make sure you use a color with transparency here e.g. - /// Colors.grey[600].withOpacity(0.2). - final Color overlayColor; - - /// A [TextFormField] in case you want a simple user input. - /// Every other widget is ignored if this is not null. - final Form userInputForm; - - /// Show the snack. It's call [SnackbarStatus.OPENING] state - /// followed by [SnackbarStatus.OPEN] - Future show() async { - return Get.showSnackbar(this); - } - - @override - State createState() { - return _GetBarState(); - } -} - -class _GetBarState extends State - with TickerProviderStateMixin { - SnackbarStatus currentStatus; - - AnimationController _fadeController; - Animation _fadeAnimation; - - final Widget _emptyWidget = SizedBox(width: 0.0, height: 0.0); - final double _initialOpacity = 1.0; - final double _finalOpacity = 0.4; - - final Duration _pulseAnimationDuration = Duration(seconds: 1); - - bool _isTitlePresent; - double _messageTopMargin; - - FocusScopeNode _focusNode; - FocusAttachment _focusAttachment; - - @override - void initState() { - super.initState(); - - assert( - ((widget.userInputForm != null || - ((widget.message != null && widget.message.isNotEmpty) || - widget.messageText != null))), - """ -A message is mandatory if you are not using userInputForm. -Set either a message or messageText"""); - - _isTitlePresent = (widget.title != null || widget.titleText != null); - _messageTopMargin = _isTitlePresent ? 6.0 : widget.padding.top; - - _configureLeftBarFuture(); - _configureProgressIndicatorAnimation(); - - if (widget.icon != null && widget.shouldIconPulse) { - _configurePulseAnimation(); - _fadeController?.forward(); - } - - _focusNode = FocusScopeNode(); - _focusAttachment = _focusNode.attach(context); - } - - @override - void dispose() { - _fadeController?.dispose(); - - widget.progressIndicatorController?.removeListener(_progressListener); - widget.progressIndicatorController?.dispose(); - - _focusAttachment.detach(); - _focusNode.dispose(); - super.dispose(); - } - - final Completer _boxHeightCompleter = Completer(); - - void _configureLeftBarFuture() { - SchedulerBinding.instance.addPostFrameCallback( - (_) { - final keyContext = backgroundBoxKey.currentContext; - - if (keyContext != null) { - final box = keyContext.findRenderObject() as RenderBox; - _boxHeightCompleter.complete(box.size); - } - }, - ); - } - - void _configurePulseAnimation() { - _fadeController = - AnimationController(vsync: this, duration: _pulseAnimationDuration); - _fadeAnimation = Tween(begin: _initialOpacity, end: _finalOpacity).animate( - CurvedAnimation( - parent: _fadeController, - curve: Curves.linear, - ), - ); - - _fadeController.addStatusListener((status) { - if (status == AnimationStatus.completed) { - _fadeController.reverse(); - } - if (status == AnimationStatus.dismissed) { - _fadeController.forward(); - } - }); - - _fadeController.forward(); - } - - VoidCallback _progressListener; - - void _configureProgressIndicatorAnimation() { - if (widget.showProgressIndicator && - widget.progressIndicatorController != null) { - _progressListener = () { - setState(() {}); - }; - widget.progressIndicatorController.addListener(_progressListener); - - _progressAnimation = CurvedAnimation( - curve: Curves.linear, parent: widget.progressIndicatorController); - } - } - - @override - Widget build(BuildContext context) { - return Align( - heightFactor: 1.0, - child: Material( - color: widget.snackStyle == SnackStyle.FLOATING - ? Colors.transparent - : widget.backgroundColor, - child: SafeArea( - minimum: widget.snackPosition == SnackPosition.BOTTOM - ? EdgeInsets.only( - // bottom: (GetUtils.isGreaterThan( - // MediaQuery.of(context).viewInsets.bottom, - // MediaQuery.of(context).padding.bottom) - // ? MediaQuery.of(context).viewInsets.bottom - // : MediaQuery.of(context).padding.bottom)) - bottom: MediaQuery.of(context).viewInsets.bottom) - : EdgeInsets.only(top: MediaQuery.of(context).padding.top), - bottom: widget.snackPosition == SnackPosition.BOTTOM, - top: widget.snackPosition == SnackPosition.TOP, - left: false, - right: false, - child: _getSnack(), - ), - ), - ); - } - - Widget _getSnack() { - Widget snack; - - if (widget.userInputForm != null) { - snack = _generateInputSnack(); - } else { - snack = _generateSnack(); - } - - return Stack( - children: [ - FutureBuilder( - future: _boxHeightCompleter.future, - builder: (context, snapshot) { - if (snapshot.hasData) { - return ClipRRect( - borderRadius: BorderRadius.circular(widget.borderRadius), - child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: widget.barBlur, sigmaY: widget.barBlur), - child: Container( - height: snapshot.data.height, - width: snapshot.data.width, - decoration: BoxDecoration( - color: Colors.transparent, - borderRadius: BorderRadius.circular(widget.borderRadius), - ), - ), - ), - ); - } else { - return _emptyWidget; - } - }, - ), - snack, - ], - ); - } - - Widget _generateInputSnack() { - return Container( - key: backgroundBoxKey, - constraints: widget.maxWidth != null - ? BoxConstraints(maxWidth: widget.maxWidth) - : null, - decoration: BoxDecoration( - color: widget.backgroundColor, - gradient: widget.backgroundGradient, - boxShadow: widget.boxShadows, - borderRadius: BorderRadius.circular(widget.borderRadius), - border: widget.borderColor != null - ? Border.all(color: widget.borderColor, width: widget.borderWidth) - : null, - ), - child: Padding( - padding: const EdgeInsets.only( - left: 8.0, right: 8.0, bottom: 8.0, top: 16.0), - child: FocusScope( - child: widget.userInputForm, - node: _focusNode, - autofocus: true, - ), - ), - ); - } - - CurvedAnimation _progressAnimation; - GlobalKey backgroundBoxKey = GlobalKey(); - - Widget _generateSnack() { - return Container( - key: backgroundBoxKey, - constraints: widget.maxWidth != null - ? BoxConstraints(maxWidth: widget.maxWidth) - : null, - decoration: BoxDecoration( - color: widget.backgroundColor, - gradient: widget.backgroundGradient, - boxShadow: widget.boxShadows, - borderRadius: BorderRadius.circular(widget.borderRadius), - border: widget.borderColor != null - ? Border.all(color: widget.borderColor, width: widget.borderWidth) - : null, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - widget.showProgressIndicator - ? LinearProgressIndicator( - value: widget.progressIndicatorController != null - ? _progressAnimation.value - : null, - backgroundColor: widget.progressIndicatorBackgroundColor, - valueColor: widget.progressIndicatorValueColor, - ) - : _emptyWidget, - Row( - mainAxisSize: MainAxisSize.max, - children: _getAppropriateRowLayout(), - ), - ], - ), - ); - } - - List _getAppropriateRowLayout() { - double buttonRightPadding; - var iconPadding = 0.0; - if (widget.padding.right - 12 < 0) { - buttonRightPadding = 4; - } else { - buttonRightPadding = widget.padding.right - 12; - } - - if (widget.padding.left > 16.0) { - iconPadding = widget.padding.left; - } - - if (widget.icon == null && widget.mainButton == null) { - return [ - _buildLeftBarIndicator(), - Expanded( - flex: 1, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - (_isTitlePresent) - ? Padding( - padding: EdgeInsets.only( - top: widget.padding.top, - left: widget.padding.left, - right: widget.padding.right, - ), - child: _getTitleText(), - ) - : _emptyWidget, - Padding( - padding: EdgeInsets.only( - top: _messageTopMargin, - left: widget.padding.left, - right: widget.padding.right, - bottom: widget.padding.bottom, - ), - child: widget.messageText ?? _getDefaultNotificationText(), - ), - ], - ), - ), - ]; - } else if (widget.icon != null && widget.mainButton == null) { - return [ - _buildLeftBarIndicator(), - ConstrainedBox( - constraints: BoxConstraints.tightFor(width: 42.0 + iconPadding), - child: _getIcon(), - ), - Expanded( - flex: 1, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - (_isTitlePresent) - ? Padding( - padding: EdgeInsets.only( - top: widget.padding.top, - left: 4.0, - right: widget.padding.left, - ), - child: _getTitleText(), - ) - : _emptyWidget, - Padding( - padding: EdgeInsets.only( - top: _messageTopMargin, - left: 4.0, - right: widget.padding.right, - bottom: widget.padding.bottom, - ), - child: widget.messageText ?? _getDefaultNotificationText(), - ), - ], - ), - ), - ]; - } else if (widget.icon == null && widget.mainButton != null) { - return [ - _buildLeftBarIndicator(), - Expanded( - flex: 1, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - (_isTitlePresent) - ? Padding( - padding: EdgeInsets.only( - top: widget.padding.top, - left: widget.padding.left, - right: widget.padding.right, - ), - child: _getTitleText(), - ) - : _emptyWidget, - Padding( - padding: EdgeInsets.only( - top: _messageTopMargin, - left: widget.padding.left, - right: 8.0, - bottom: widget.padding.bottom, - ), - child: widget.messageText ?? _getDefaultNotificationText(), - ), - ], - ), - ), - Padding( - padding: EdgeInsets.only(right: buttonRightPadding), - child: _getMainActionButton(), - ), - ]; - } else { - return [ - _buildLeftBarIndicator(), - ConstrainedBox( - constraints: BoxConstraints.tightFor(width: 42.0 + iconPadding), - child: _getIcon(), - ), - Expanded( - flex: 1, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - (_isTitlePresent) - ? Padding( - padding: EdgeInsets.only( - top: widget.padding.top, - left: 4.0, - right: 8.0, - ), - child: _getTitleText(), - ) - : _emptyWidget, - Padding( - padding: EdgeInsets.only( - top: _messageTopMargin, - left: 4.0, - right: 8.0, - bottom: widget.padding.bottom, - ), - child: widget.messageText ?? _getDefaultNotificationText(), - ), - ], - ), - ), - Padding( - padding: EdgeInsets.only(right: buttonRightPadding), - child: _getMainActionButton(), - ) ?? - _emptyWidget, - ]; - } - } - - Widget _buildLeftBarIndicator() { - if (widget.leftBarIndicatorColor != null) { - return FutureBuilder( - future: _boxHeightCompleter.future, - builder: (buildContext, snapshot) { - if (snapshot.hasData) { - return Container( - color: widget.leftBarIndicatorColor, - width: 5.0, - height: snapshot.data.height, - ); - } else { - return _emptyWidget; - } - }, - ); - } else { - return _emptyWidget; - } - } - - Widget _getIcon() { - if (widget.icon != null && widget.icon is Icon && widget.shouldIconPulse) { - return FadeTransition( - opacity: _fadeAnimation, - child: widget.icon, - ); - } else if (widget.icon != null) { - return widget.icon; - } else { - return _emptyWidget; - } - } - - Widget _getTitleText() { - return widget.titleText ?? - Text( - widget.title ?? "", - style: TextStyle( - fontSize: 16.0, color: Colors.white, fontWeight: FontWeight.bold), - ); - } - - Text _getDefaultNotificationText() { - return Text( - widget.message ?? "", - style: TextStyle(fontSize: 14.0, color: Colors.white), - ); - } - - FlatButton _getMainActionButton() { - return widget.mainButton; - } -} - -/// Indicates if snack is going to start at the [TOP] or at the [BOTTOM] -enum SnackPosition { TOP, BOTTOM } - -/// Indicates if snack will be attached to the edge of the screen or not -enum SnackStyle { FLOATING, GROUNDED } - -/// Indicates the direction in which it is possible to dismiss -/// If vertical, dismiss up will be allowed if [SnackPosition.TOP] -/// If vertical, dismiss down will be allowed if [SnackPosition.BOTTOM] -enum SnackDismissDirection { HORIZONTAL, VERTICAL } - -/// Indicates Status of snackbar -/// [SnackbarStatus.OPEN] Snack is fully open, [SnackbarStatus.CLOSED] Snackbar -/// has closed, -/// [SnackbarStatus.OPENING] Starts with the opening animation and ends -/// with the full -/// snackbar display, [SnackbarStatus.CLOSING] Starts with the closing animation -/// and ends -/// with the full snackbar dispose -enum SnackbarStatus { OPEN, CLOSED, OPENING, CLOSING } diff --git a/packages/get_navigation/lib/src/snackbar/snack_route.dart b/packages/get_navigation/lib/src/snackbar/snack_route.dart deleted file mode 100644 index a50bd8288..000000000 --- a/packages/get_navigation/lib/src/snackbar/snack_route.dart +++ /dev/null @@ -1,394 +0,0 @@ -import 'dart:async'; -import 'dart:ui'; -import 'package:flutter/widgets.dart'; -import '../../get_navigation.dart'; -import 'snack.dart'; - -class SnackRoute extends OverlayRoute { - Animation _filterBlurAnimation; - Animation _filterColorAnimation; - - SnackRoute({ - @required this.snack, - RouteSettings settings, - }) : super(settings: settings) { - _builder = Builder(builder: (innerContext) { - return GestureDetector( - child: snack, - onTap: snack.onTap != null ? () => snack.onTap(snack) : null, - ); - }); - - _configureAlignment(snack.snackPosition); - _snackbarStatus = snack.snackbarStatus; - } - - _configureAlignment(SnackPosition snackPosition) { - switch (snack.snackPosition) { - case SnackPosition.TOP: - { - _initialAlignment = Alignment(-1.0, -2.0); - _endAlignment = Alignment(-1.0, -1.0); - break; - } - case SnackPosition.BOTTOM: - { - _initialAlignment = Alignment(-1.0, 2.0); - _endAlignment = Alignment(-1.0, 1.0); - break; - } - } - } - - GetBar snack; - Builder _builder; - - final Completer _transitionCompleter = Completer(); - - SnackbarStatusCallback _snackbarStatus; - Alignment _initialAlignment; - Alignment _endAlignment; - bool _wasDismissedBySwipe = false; - - Timer _timer; - - bool get opaque => false; - - @override - Iterable createOverlayEntries() { - var overlays = []; - - if (snack.overlayBlur > 0.0) { - overlays.add( - OverlayEntry( - builder: (context) { - return GestureDetector( - onTap: snack.isDismissible ? Get.back : null, - child: AnimatedBuilder( - animation: _filterBlurAnimation, - builder: (context, child) { - return BackdropFilter( - filter: ImageFilter.blur( - sigmaX: _filterBlurAnimation.value, - sigmaY: _filterBlurAnimation.value), - child: Container( - constraints: BoxConstraints.expand(), - color: _filterColorAnimation.value, - ), - ); - }, - ), - ); - }, - maintainState: false, - opaque: opaque, - ), - ); - } - - overlays.add( - OverlayEntry( - builder: (context) { - final Widget annotatedChild = Semantics( - child: AlignTransition( - alignment: _animation, - child: snack.isDismissible - ? _getDismissibleSnack(_builder) - : _getSnack(), - ), - focused: false, - container: true, - explicitChildNodes: true, - ); - return annotatedChild; - }, - maintainState: false, - opaque: opaque, - ), - ); - - return overlays; - } - - String dismissibleKeyGen = ""; - - Widget _getDismissibleSnack(Widget child) { - return Dismissible( - direction: _getDismissDirection(), - resizeDuration: null, - confirmDismiss: (_) { - if (currentStatus == SnackbarStatus.OPENING || - currentStatus == SnackbarStatus.CLOSING) { - return Future.value(false); - } - return Future.value(true); - }, - key: Key(dismissibleKeyGen), - onDismissed: (_) { - dismissibleKeyGen += "1"; - _cancelTimer(); - _wasDismissedBySwipe = true; - - if (isCurrent) { - navigator.pop(); - } else { - navigator.removeRoute(this); - } - }, - child: _getSnack(), - ); - } - - Widget _getSnack() { - return Container( - margin: snack.margin, - child: _builder, - ); - } - - DismissDirection _getDismissDirection() { - if (snack.dismissDirection == SnackDismissDirection.HORIZONTAL) { - return DismissDirection.horizontal; - } else { - if (snack.snackPosition == SnackPosition.TOP) { - return DismissDirection.up; - } - return DismissDirection.down; - } - } - - @override - bool get finishedWhenPopped => - _controller.status == AnimationStatus.dismissed; - - /// The animation that drives the route's transition and the previous route's - /// forward transition. - Animation _animation; - - /// The animation controller that the route uses to drive the transitions. - /// - /// The animation itself is exposed by the [animation] property. - AnimationController _controller; - - /// Called to create the animation controller that will drive the transitions - /// to this route from the previous one, and back to the previous route - /// from this one. - AnimationController createAnimationController() { - assert(!_transitionCompleter.isCompleted, - 'Cannot reuse a $runtimeType after disposing it.'); - assert(snack.animationDuration != null && - snack.animationDuration >= Duration.zero); - return AnimationController( - duration: snack.animationDuration, - debugLabel: debugLabel, - vsync: navigator, - ); - } - - /// Called to create the animation that exposes the current progress of - /// the transition controlled by the animation controller created by - /// [createAnimationController()]. - Animation createAnimation() { - assert(!_transitionCompleter.isCompleted, - 'Cannot reuse a $runtimeType after disposing it.'); - assert(_controller != null); - return AlignmentTween(begin: _initialAlignment, end: _endAlignment).animate( - CurvedAnimation( - parent: _controller, - curve: snack.forwardAnimationCurve, - reverseCurve: snack.reverseAnimationCurve, - ), - ); - } - - Animation createBlurFilterAnimation() { - return Tween(begin: 0.0, end: snack.overlayBlur).animate( - CurvedAnimation( - parent: _controller, - curve: Interval( - 0.0, - 0.35, - curve: Curves.easeInOutCirc, - ), - ), - ); - } - - Animation createColorFilterAnimation() { - return ColorTween(begin: Color(0x00000000), end: snack.overlayColor) - .animate( - CurvedAnimation( - parent: _controller, - curve: Interval( - 0.0, - 0.35, - curve: Curves.easeInOutCirc, - ), - ), - ); - } - - T _result; - SnackbarStatus currentStatus; - - void _handleStatusChanged(AnimationStatus status) { - switch (status) { - case AnimationStatus.completed: - currentStatus = SnackbarStatus.OPEN; - _snackbarStatus(currentStatus); - if (overlayEntries.isNotEmpty) overlayEntries.first.opaque = opaque; - - break; - case AnimationStatus.forward: - currentStatus = SnackbarStatus.OPENING; - _snackbarStatus(currentStatus); - break; - case AnimationStatus.reverse: - currentStatus = SnackbarStatus.CLOSING; - _snackbarStatus(currentStatus); - if (overlayEntries.isNotEmpty) overlayEntries.first.opaque = false; - break; - case AnimationStatus.dismissed: - assert(!overlayEntries.first.opaque); - // We might still be the current route if a subclass is controlling the - // the transition and hits the dismissed status. For example, the iOS - // back gesture drives this animation to the dismissed status before - // popping the navigator. - currentStatus = SnackbarStatus.CLOSED; - _snackbarStatus(currentStatus); - - if (!isCurrent) { - navigator.finalizeRoute(this); - assert(overlayEntries.isEmpty); - } - break; - } - changedInternalState(); - } - - @override - void install() { - assert(!_transitionCompleter.isCompleted, - 'Cannot install a $runtimeType after disposing it.'); - _controller = createAnimationController(); - assert(_controller != null, - '$runtimeType.createAnimationController() returned null.'); - _filterBlurAnimation = createBlurFilterAnimation(); - _filterColorAnimation = createColorFilterAnimation(); - _animation = createAnimation(); - assert(_animation != null, '$runtimeType.createAnimation() returned null.'); - super.install(); - } - - @override - TickerFuture didPush() { - super.didPush(); - assert( - _controller != null, - // ignore: lines_longer_than_80_chars - '$runtimeType.didPush called before calling install() or after calling dispose().', - ); - assert( - !_transitionCompleter.isCompleted, - 'Cannot reuse a $runtimeType after disposing it.', - ); - _animation.addStatusListener(_handleStatusChanged); - _configureTimer(); - return _controller.forward(); - } - - @override - void didReplace(Route oldRoute) { - assert( - _controller != null, - // ignore: lines_longer_than_80_chars - '$runtimeType.didReplace called before calling install() or after calling dispose().', - ); - assert( - !_transitionCompleter.isCompleted, - 'Cannot reuse a $runtimeType after disposing it.', - ); - - if (oldRoute is SnackRoute) { - _controller.value = oldRoute._controller.value; - } - _animation.addStatusListener(_handleStatusChanged); - super.didReplace(oldRoute); - } - - @override - bool didPop(T result) { - assert( - _controller != null, - // ignore: lines_longer_than_80_chars - '$runtimeType.didPop called before calling install() or after calling dispose().', - ); - assert( - !_transitionCompleter.isCompleted, - 'Cannot reuse a $runtimeType after disposing it.', - ); - - _result = result; - _cancelTimer(); - - if (_wasDismissedBySwipe) { - Timer(Duration(milliseconds: 200), () { - _controller.reset(); - }); - - _wasDismissedBySwipe = false; - } else { - _controller.reverse(); - } - - return super.didPop(result); - } - - void _configureTimer() { - if (snack.duration != null) { - if (_timer != null && _timer.isActive) { - _timer.cancel(); - } - _timer = Timer(snack.duration, () { - if (isCurrent) { - navigator.pop(); - } else if (isActive) { - navigator.removeRoute(this); - } - }); - } else { - if (_timer != null) { - _timer.cancel(); - } - } - } - - void _cancelTimer() { - if (_timer != null && _timer.isActive) { - _timer.cancel(); - } - } - - /// Whether this route can perform a transition to the given route. - /// Subclasses can override this method to restrict the set of routes they - /// need to coordinate transitions with. - bool canTransitionTo(SnackRoute nextRoute) => true; - - /// Whether this route can perform a transition from the given route. - /// - /// Subclasses can override this method to restrict the set of routes they - /// need to coordinate transitions with. - bool canTransitionFrom(SnackRoute previousRoute) => true; - - @override - void dispose() { - assert(!_transitionCompleter.isCompleted, - 'Cannot dispose a $runtimeType twice.'); - _controller?.dispose(); - _transitionCompleter.complete(_result); - super.dispose(); - } - - /// A short description of this route useful for debugging. - String get debugLabel => '$runtimeType'; -} diff --git a/packages/get_navigation/pubspec.yaml b/packages/get_navigation/pubspec.yaml deleted file mode 100644 index 2a309cdac..000000000 --- a/packages/get_navigation/pubspec.yaml +++ /dev/null @@ -1,56 +0,0 @@ -name: get_navigation -description: Open Screens, bottomsheets, dialogs, e snackbars with no context using GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - flutter: ">=1.17.0 <2.0.0" - -dependencies: - flutter: - sdk: flutter - get_state_manager: ">=3.13.0 <4.0.0" - get_core: ">=3.13.0 <4.0.0" - get_utils: ">=3.13.0 <4.0.0" - -dev_dependencies: - flutter_test: - sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_navigation/test/bottomsheet_test.dart b/packages/get_navigation/test/bottomsheet_test.dart deleted file mode 100644 index f97f63a29..000000000 --- a/packages/get_navigation/test/bottomsheet_test.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_navigation/get_navigation.dart'; -import 'utils/wrapper.dart'; - -void main() { - testWidgets("Get.bottomSheet smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.bottomSheet(Container( - child: Wrap( - children: [ - ListTile( - leading: Icon(Icons.music_note), - title: Text('Music'), - onTap: () => {}), - ], - ), - )); - - await tester.pumpAndSettle(); - - expect(find.byIcon(Icons.music_note), findsOneWidget); - }); - - testWidgets("Get.bottomSheet close test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.bottomSheet(Container( - child: Wrap( - children: [ - ListTile( - leading: Icon(Icons.music_note), - title: Text('Music'), - onTap: () => {}), - ], - ), - )); - - expect(Get.isBottomSheetOpen, true); - - Get.back(); - expect(Get.isBottomSheetOpen, false); - - expect(() => Get.bottomSheet(Container(), isScrollControlled: null), - throwsAssertionError); - - expect(() => Get.bottomSheet(Container(), isDismissible: null), - throwsAssertionError); - - expect(() => Get.bottomSheet(Container(), enableDrag: null), - throwsAssertionError); - - await tester.pumpAndSettle(); - }); - - testWidgets( - "GetMaterialApp with debugShowMaterialGrid null", - (tester) async { - expect( - () => GetMaterialApp( - debugShowMaterialGrid: null, - ), - throwsAssertionError, - ); - }, - ); -} diff --git a/packages/get_navigation/test/dialog_test.dart b/packages/get_navigation/test/dialog_test.dart deleted file mode 100644 index e9b39703f..000000000 --- a/packages/get_navigation/test/dialog_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_navigation/get_navigation.dart'; -import 'utils/wrapper.dart'; - -void main() { - testWidgets("Get.defaultDialog smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.defaultDialog( - onConfirm: () => print("Ok"), - middleText: "Dialog made in 3 lines of code"); - - await tester.pumpAndSettle(); - - expect(find.text("Ok"), findsOneWidget); - }); - - testWidgets("Get.dialog smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.dialog(YourDialogWidget()); - - await tester.pumpAndSettle(); - - expect(find.byType(YourDialogWidget), findsOneWidget); - }); - - testWidgets("Get.dialog close test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.dialog(YourDialogWidget()); - expect(Get.isDialogOpen, true); - Get.back(); - expect(Get.isDialogOpen, false); - await tester.pumpAndSettle(); - }); -} - -class YourDialogWidget extends StatelessWidget { - const YourDialogWidget({Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(); - } -} diff --git a/packages/get_navigation/test/get_main_test.dart b/packages/get_navigation/test/get_main_test.dart deleted file mode 100644 index 1f1e60535..000000000 --- a/packages/get_navigation/test/get_main_test.dart +++ /dev/null @@ -1,471 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_navigation/get_navigation.dart'; - -import 'utils/wrapper.dart'; - -class SizeTransitions extends CustomTransition { - @override - Widget buildTransition( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { - return Align( - alignment: Alignment.center, - child: SizeTransition( - sizeFactor: CurvedAnimation( - parent: animation, - curve: curve, - ), - child: child, - ), - ); - } -} - -void main() { - testWidgets("Get.to smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.to(SecondScreen()); - - await tester.pump(Duration.zero); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - testWidgets("Get.toNamed smoke test", (tester) async { - await tester.pumpWidget( - GetMaterialApp( - initialRoute: '/', - getPages: [ - GetPage( - page: () => FirstScreen(), - name: '/', - customTransition: SizeTransitions()), - GetPage(page: () => SecondScreen(), name: '/second'), - GetPage(page: () => ThirdScreen(), name: '/third'), - ], - ), - ); - - Get.toNamed('/second'); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - - testWidgets("Get.off smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.off(SecondScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - - testWidgets("Get.offNamed smoke test", (tester) async { - await tester.pumpWidget( - GetMaterialApp( - initialRoute: '/', - getPages: [ - GetPage(name: '/', page: () => Container()), - GetPage(name: '/first', page: () => FirstScreen()), - GetPage(name: '/second', page: () => SecondScreen()), - GetPage(name: '/third', page: () => ThirdScreen()), - ], - ), - ); - - Get.toNamed('/first'); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.offNamed('/second'); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - - testWidgets("Get.offAll smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.to(SecondScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - - Get.offAll(ThirdScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(ThirdScreen), findsOneWidget); - }); - - testWidgets("Get.offAllNamed smoke test", (tester) async { - await tester.pumpWidget( - WrapperNamed( - initialRoute: '/', - namedRoutes: [ - GetPage(page: () => Container(), name: '/'), - GetPage(page: () => FirstScreen(), name: '/first'), - GetPage(page: () => SecondScreen(), name: '/second'), - GetPage(page: () => ThirdScreen(), name: '/third'), - ], - ), - ); - - Get.toNamed('/first'); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.toNamed('/second'); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - - Get.offAllNamed('/third'); - - await tester.pumpAndSettle(); - - expect(find.byType(ThirdScreen), findsOneWidget); - }); - - testWidgets("Get.offAndToNamed smoke test", (tester) async { - await tester.pumpWidget( - WrapperNamed( - initialRoute: '/', - namedRoutes: [ - GetPage(page: () => Container(), name: '/'), - GetPage(page: () => FirstScreen(), name: '/first'), - GetPage(page: () => SecondScreen(), name: '/second'), - GetPage(page: () => ThirdScreen(), name: '/third'), - ], - ), - ); - - Get.toNamed('/first'); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.offAndToNamed('/second'); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - - testWidgets("Get.offUntil smoke test", (tester) async { - await tester.pumpWidget( - Wrapper( - child: Container(), - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.offUntil( - MaterialPageRoute(builder: (context) => SecondScreen()), - ModalRoute.withName('/'), - ); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - }); - - testWidgets("Get.offNamedUntil smoke test", (tester) async { - await tester.pumpWidget( - WrapperNamed( - initialRoute: '/', - namedRoutes: [ - GetPage( - page: () => Container(), - name: '/', - popGesture: true, - transition: Transition.cupertino), - GetPage( - page: () => FirstScreen(), - name: '/first', - transition: Transition.size), - GetPage( - page: () => SecondScreen(), name: '/second', transition: null), - GetPage(page: () => ThirdScreen(), name: '/third'), - ], - ), - ); - - Get.toNamed('/first'); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.offNamedUntil('/first', ModalRoute.withName('/')); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - }); - - testWidgets("Get.back smoke test", (tester) async { - await tester.pumpWidget( - Wrapper(child: Container()), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - Get.to(SecondScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(SecondScreen), findsOneWidget); - - Get.back(); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - }); - - testWidgets("Get.defaultTransition smoke test", (tester) async { - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.fadeIn, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.downToUp, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.fade, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.leftToRight, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.leftToRightWithFade, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.rightToLeft, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.rightToLeftWithFade, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.cupertino, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - - await tester.pumpWidget( - Wrapper( - child: Container(), - defaultTransition: Transition.size, - ), - ); - - Get.to(FirstScreen()); - - await tester.pumpAndSettle(); - - expect(find.byType(FirstScreen), findsOneWidget); - }); - - testWidgets("Get.snackbar test", (tester) async { - await tester.pumpWidget( - GetMaterialApp( - popGesture: true, - home: RaisedButton( - child: Text('Open Snackbar'), - onPressed: () { - Get.snackbar('title', "message", duration: Duration(seconds: 1)); - }, - ), - ), - ); - - expect(Get.isSnackbarOpen, false); - await tester.tap(find.text('Open Snackbar')); - - expect(Get.isSnackbarOpen, true); - await tester.pump(const Duration(seconds: 1)); - }); - - testWidgets("Get.rawSnackbar test", (tester) async { - await tester.pumpWidget( - Wrapper( - child: RaisedButton( - child: Text('Open Snackbar'), - onPressed: () { - Get.rawSnackbar( - title: 'title', - message: "message", - onTap: (_) { - print('snackbar tapped'); - }, - duration: Duration(seconds: 1), - shouldIconPulse: true, - icon: Icon(Icons.alarm), - showProgressIndicator: true, - barBlur: null, - isDismissible: true, - leftBarIndicatorColor: Colors.amber, - overlayBlur: 1.0, - ); - }, - ), - ), - ); - - expect(Get.isSnackbarOpen, false); - await tester.tap(find.text('Open Snackbar')); - - expect(Get.isSnackbarOpen, true); - await tester.pump(const Duration(seconds: 1)); - }); -} - -class FirstScreen extends StatelessWidget { - const FirstScreen({Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(child: Text('FirstScreen')); - } -} - -class SecondScreen extends StatelessWidget { - const SecondScreen({Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(); - } -} - -class ThirdScreen extends StatelessWidget { - const ThirdScreen({Key key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Container(); - } -} diff --git a/packages/get_navigation/test/root_widget_test.dart b/packages/get_navigation/test/root_widget_test.dart deleted file mode 100644 index 841453ea2..000000000 --- a/packages/get_navigation/test/root_widget_test.dart +++ /dev/null @@ -1,102 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_navigation/get_navigation.dart'; - -void main() { - testWidgets( - "GetMaterialApp with routes null", - (tester) async { - expect( - () => GetMaterialApp( - routes: null, - ), - throwsAssertionError); - }, - ); - - testWidgets( - "GetMaterialApp with navigatorObservers null", - (tester) async { - expect( - () => GetMaterialApp( - navigatorObservers: null, - ), - throwsAssertionError); - }, - ); - testWidgets( - "GetMaterialApp with title null", - (tester) async { - expect( - () => GetMaterialApp( - title: null, - ), - throwsAssertionError); - }, - ); - testWidgets( - "GetMaterialApp with debugShowMaterialGrid null", - (test) async { - expect( - () => GetMaterialApp( - debugShowMaterialGrid: null, - ), - throwsAssertionError, - ); - }, - ); - testWidgets( - "GetMaterialApp with showPerformanceOverlay null", - (test) async { - expect( - () => GetMaterialApp( - showPerformanceOverlay: null, - ), - throwsAssertionError, - ); - }, - ); - testWidgets( - "GetMaterialApp with showSemanticsDebugger null", - (test) async { - expect( - () => GetMaterialApp( - showSemanticsDebugger: null, - ), - throwsAssertionError, - ); - }, - ); - testWidgets( - "GetMaterialApp with debugShowCheckedModeBanner null", - (tester) async { - expect( - () => GetMaterialApp( - debugShowCheckedModeBanner: null, - ), - throwsAssertionError); - }, - ); - - testWidgets( - "GetMaterialApp with checkerboardRasterCacheImages null", - (tester) async { - expect( - () => GetMaterialApp( - checkerboardRasterCacheImages: null, - ), - throwsAssertionError); - }, - ); - - testWidgets( - "GetMaterialApp with checkerboardOffscreenLayers null", - (tester) async { - expect( - () => GetMaterialApp( - checkerboardOffscreenLayers: null, - ), - throwsAssertionError, - ); - }, - ); -} diff --git a/packages/get_navigation/test/routes_test.dart b/packages/get_navigation/test/routes_test.dart deleted file mode 100644 index 7f1d390e2..000000000 --- a/packages/get_navigation/test/routes_test.dart +++ /dev/null @@ -1,43 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_navigation/get_navigation.dart'; - -void main() { - testWidgets( - 'GetPage page null', - (tester) async { - expect(() => GetPage(page: null, name: null), throwsAssertionError); - }, - ); - - testWidgets( - "GetPage maintainState null", - (tester) async { - expect( - () => GetPage(page: () => Scaffold(), maintainState: null, name: '/'), - throwsAssertionError, - ); - }, - ); - - testWidgets( - "GetPage name null", - (tester) async { - expect( - () => GetPage(page: () => Scaffold(), maintainState: null, name: null), - throwsAssertionError, - ); - }, - ); - - testWidgets( - "GetPage fullscreenDialog null", - (tester) async { - expect( - () => - GetPage(page: () => Scaffold(), fullscreenDialog: null, name: '/'), - throwsAssertionError, - ); - }, - ); -} diff --git a/packages/get_navigation/test/utils/wrapper.dart b/packages/get_navigation/test/utils/wrapper.dart deleted file mode 100644 index 814669ce7..000000000 --- a/packages/get_navigation/test/utils/wrapper.dart +++ /dev/null @@ -1,53 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:get_navigation/get_navigation.dart'; - -class Wrapper extends StatelessWidget { - final Widget child; - final List namedRoutes; - final String initialRoute; - final Transition defaultTransition; - - const Wrapper({ - Key key, - this.child, - this.namedRoutes, - this.initialRoute, - this.defaultTransition, - }) : super(key: key); - - @override - Widget build(BuildContext context) { - return GetMaterialApp( - defaultTransition: defaultTransition, - initialRoute: initialRoute, - getPages: namedRoutes, - home: Scaffold( - body: child, - ), - ); - } -} - -class WrapperNamed extends StatelessWidget { - final Widget child; - final List namedRoutes; - final String initialRoute; - final Transition defaultTransition; - - const WrapperNamed({ - Key key, - this.child, - this.namedRoutes, - this.initialRoute, - this.defaultTransition, - }) : super(key: key); - - @override - Widget build(BuildContext context) { - return GetMaterialApp( - defaultTransition: defaultTransition, - initialRoute: initialRoute, - getPages: namedRoutes, - ); - } -} diff --git a/packages/get_rx/.gitignore b/packages/get_rx/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_rx/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_rx/.metadata b/packages/get_rx/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_rx/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_rx/CHANGELOG.md b/packages/get_rx/CHANGELOG.md deleted file mode 100644 index 412e3893d..000000000 --- a/packages/get_rx/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 - -## [3.10.2] -- Initial release diff --git a/packages/get_rx/LICENSE b/packages/get_rx/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_rx/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_rx/README.md b/packages/get_rx/README.md deleted file mode 100644 index 8946892a3..000000000 --- a/packages/get_rx/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_rx - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_rx/analysis_options.yaml b/packages/get_rx/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_rx/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_rx/coverage/lcov.info b/packages/get_rx/coverage/lcov.info deleted file mode 100644 index 878415a93..000000000 --- a/packages/get_rx/coverage/lcov.info +++ /dev/null @@ -1,677 +0,0 @@ -SF:lib/src/rx_core/rx_num.dart -DA:8,0 -DA:23,0 -DA:26,0 -DA:35,0 -DA:38,0 -DA:46,0 -DA:49,0 -DA:52,0 -DA:55,0 -DA:58,0 -DA:61,0 -DA:66,0 -DA:70,0 -DA:76,0 -DA:79,0 -DA:97,0 -DA:105,0 -DA:110,0 -DA:115,0 -DA:121,0 -DA:139,0 -DA:152,0 -DA:165,0 -DA:180,0 -DA:190,0 -DA:191,0 -DA:194,0 -DA:201,0 -DA:225,0 -DA:226,0 -DA:246,0 -DA:247,0 -DA:265,0 -DA:266,0 -DA:270,0 -DA:271,0 -DA:272,0 -DA:276,0 -DA:277,0 -DA:278,0 -DA:283,0 -DA:284,0 -DA:288,0 -DA:289,0 -DA:294,0 -DA:295,0 -DA:300,0 -DA:302,0 -DA:305,0 -DA:311,0 -DA:314,0 -DA:317,0 -DA:324,0 -DA:332,0 -DA:337,0 -DA:342,0 -DA:348,0 -DA:362,0 -DA:371,0 -DA:380,0 -DA:391,0 -DA:395,1 -DA:396,1 -DA:400,0 -DA:401,0 -DA:406,0 -DA:407,0 -DA:419,0 -DA:429,0 -DA:439,0 -DA:447,0 -DA:459,0 -DA:468,0 -DA:474,0 -DA:482,0 -DA:495,0 -DA:498,0 -DA:501,0 -DA:523,0 -DA:545,0 -DA:575,0 -DA:581,0 -DA:586,0 -DA:592,0 -DA:595,0 -DA:598,0 -DA:601,0 -DA:604,0 -DA:607,0 -DA:610,0 -DA:613,0 -DA:616,0 -LF:92 -LH:2 -end_of_record -SF:lib/src/rx_core/rx_impl.dart -DA:18,0 -DA:36,0 -DA:38,0 -DA:40,0 -DA:61,0 -DA:62,0 -DA:85,0 -DA:86,0 -DA:87,0 -DA:100,0 -DA:101,0 -DA:105,0 -DA:107,0 -DA:108,0 -DA:111,0 -DA:115,0 -DA:119,0 -DA:120,0 -DA:124,0 -DA:126,0 -DA:129,0 -DA:130,0 -DA:131,0 -DA:132,0 -DA:137,0 -DA:138,0 -DA:141,0 -DA:142,0 -DA:150,1 -DA:151,2 -DA:152,1 -DA:153,1 -DA:154,3 -DA:158,1 -DA:160,0 -DA:162,1 -DA:165,0 -DA:167,0 -DA:169,0 -DA:175,0 -DA:176,0 -DA:179,0 -DA:184,0 -DA:185,0 -DA:188,0 -DA:190,0 -DA:192,0 -DA:199,0 -DA:200,0 -DA:204,0 -DA:205,0 -DA:211,0 -DA:212,0 -DA:215,0 -DA:223,0 -DA:224,0 -DA:229,0 -DA:230,0 -DA:235,0 -DA:240,2 -DA:245,0 -DA:250,0 -DA:255,0 -LF:63 -LH:8 -end_of_record -SF:lib/src/rx_core/rx_interface.dart -DA:9,0 -DA:24,0 -LF:2 -LH:0 -end_of_record -SF:lib/src/rx_iterables/rx_list.dart -DA:12,0 -DA:13,0 -DA:18,0 -DA:19,0 -DA:21,0 -DA:22,0 -DA:24,0 -DA:25,0 -DA:28,0 -DA:29,0 -DA:36,0 -DA:37,0 -DA:38,0 -DA:41,0 -DA:42,0 -DA:47,0 -DA:48,0 -DA:49,0 -DA:53,0 -DA:54,0 -DA:57,0 -DA:58,0 -DA:59,0 -DA:62,0 -DA:64,0 -DA:65,0 -DA:69,0 -DA:70,0 -DA:74,0 -DA:75,0 -DA:79,0 -DA:80,0 -DA:81,0 -DA:85,0 -DA:86,0 -DA:87,0 -DA:90,0 -DA:92,0 -DA:93,0 -DA:96,0 -DA:98,0 -DA:99,0 -DA:102,0 -DA:103,0 -DA:110,0 -DA:112,0 -DA:114,0 -DA:119,0 -DA:121,0 -DA:122,0 -DA:126,0 -DA:128,0 -DA:129,0 -DA:133,0 -DA:135,0 -DA:136,0 -DA:139,0 -DA:141,0 -DA:142,0 -DA:145,0 -DA:147,0 -DA:148,0 -DA:151,0 -DA:153,0 -DA:154,0 -DA:157,0 -DA:159,0 -DA:160,0 -DA:162,0 -DA:163,0 -DA:167,0 -DA:168,0 -DA:169,0 -DA:172,0 -DA:173,0 -DA:174,0 -DA:178,0 -DA:179,0 -DA:180,0 -DA:183,0 -DA:186,0 -DA:188,0 -DA:191,0 -DA:193,0 -DA:194,0 -DA:197,0 -DA:200,0 -DA:201,0 -DA:202,0 -DA:203,0 -DA:206,0 -DA:208,0 -DA:214,0 -DA:220,0 -DA:221,0 -DA:224,0 -DA:225,0 -DA:227,0 -DA:228,0 -DA:230,0 -DA:232,0 -DA:235,0 -DA:237,0 -DA:240,0 -DA:242,0 -DA:245,0 -DA:247,0 -DA:250,0 -DA:252,0 -DA:255,0 -DA:257,0 -DA:260,0 -DA:262,0 -DA:265,0 -DA:267,0 -DA:268,0 -DA:271,0 -DA:273,0 -DA:276,0 -DA:278,0 -DA:281,0 -DA:283,0 -DA:286,0 -DA:288,0 -DA:291,0 -DA:293,0 -DA:296,0 -DA:298,0 -DA:301,0 -DA:303,0 -DA:306,0 -DA:308,0 -DA:311,0 -DA:313,0 -DA:316,0 -DA:318,0 -DA:321,0 -DA:323,0 -DA:326,0 -DA:328,0 -DA:329,0 -DA:332,0 -DA:334,0 -DA:337,0 -DA:339,0 -DA:342,0 -DA:344,0 -DA:345,0 -DA:348,0 -DA:350,0 -DA:351,0 -DA:354,0 -DA:355,0 -DA:357,0 -DA:359,0 -DA:360,0 -DA:363,0 -DA:365,0 -DA:366,0 -DA:369,0 -DA:371,0 -DA:372,0 -DA:375,0 -DA:376,0 -DA:378,0 -DA:380,0 -DA:383,0 -DA:385,0 -DA:388,0 -DA:390,0 -DA:393,0 -DA:395,0 -DA:398,0 -DA:400,0 -DA:403,0 -DA:405,0 -DA:408,0 -DA:410,0 -DA:413,0 -DA:415,0 -DA:418,0 -DA:420,0 -DA:423,0 -DA:425,0 -DA:428,0 -DA:430,0 -DA:431,0 -DA:434,0 -DA:436,0 -DA:437,0 -DA:442,0 -DA:444,0 -DA:446,0 -LF:193 -LH:0 -end_of_record -SF:lib/src/rx_iterables/rx_map.dart -DA:10,0 -DA:11,0 -DA:20,0 -DA:23,0 -DA:25,0 -DA:28,0 -DA:29,0 -DA:32,0 -DA:34,0 -DA:35,0 -DA:38,0 -DA:40,0 -DA:41,0 -DA:43,0 -DA:44,0 -DA:47,0 -DA:49,0 -DA:52,0 -DA:53,0 -DA:57,0 -DA:58,0 -DA:59,0 -DA:60,0 -DA:63,0 -DA:65,0 -DA:67,0 -DA:73,0 -DA:74,0 -DA:77,0 -DA:78,0 -DA:79,0 -DA:82,0 -DA:83,0 -DA:84,0 -DA:85,0 -DA:86,0 -DA:90,0 -DA:91,0 -DA:92,0 -DA:95,0 -DA:97,0 -DA:100,0 -DA:102,0 -DA:103,0 -DA:106,0 -DA:108,0 -DA:109,0 -DA:112,0 -DA:114,0 -DA:115,0 -DA:118,0 -DA:120,0 -DA:121,0 -DA:124,0 -DA:125,0 -DA:127,0 -DA:128,0 -DA:130,0 -DA:131,0 -DA:133,0 -DA:134,0 -DA:136,0 -DA:138,0 -DA:141,0 -DA:142,0 -DA:144,0 -DA:145,0 -DA:147,0 -DA:148,0 -DA:150,0 -DA:151,0 -DA:153,0 -DA:155,0 -DA:157,0 -DA:159,0 -DA:160,0 -DA:164,0 -DA:166,0 -DA:167,0 -DA:171,0 -DA:173,0 -DA:174,0 -DA:177,0 -DA:178,0 -DA:180,0 -DA:181,0 -DA:183,0 -DA:185,0 -DA:186,0 -DA:190,0 -DA:192,0 -DA:193,0 -DA:198,0 -DA:200,0 -DA:202,0 -LF:95 -LH:0 -end_of_record -SF:lib/src/rx_iterables/rx_set.dart -DA:10,0 -DA:11,0 -DA:16,0 -DA:17,0 -DA:19,0 -DA:20,0 -DA:22,0 -DA:23,0 -DA:26,0 -DA:27,0 -DA:33,0 -DA:34,0 -DA:35,0 -DA:39,0 -DA:40,0 -DA:41,0 -DA:44,0 -DA:45,0 -DA:50,0 -DA:51,0 -DA:52,0 -DA:56,0 -DA:58,0 -DA:59,0 -DA:63,0 -DA:65,0 -DA:66,0 -DA:70,0 -DA:71,0 -DA:75,0 -DA:76,0 -DA:79,0 -DA:86,0 -DA:87,0 -DA:89,0 -DA:94,0 -DA:95,0 -DA:96,0 -DA:99,0 -DA:100,0 -DA:101,0 -DA:104,0 -DA:105,0 -DA:106,0 -DA:108,0 -DA:109,0 -DA:113,0 -DA:114,0 -DA:115,0 -DA:118,0 -DA:119,0 -DA:120,0 -DA:124,0 -DA:125,0 -DA:126,0 -DA:129,0 -DA:132,0 -DA:134,0 -DA:137,0 -DA:139,0 -DA:140,0 -DA:143,0 -DA:144,0 -DA:148,0 -DA:149,0 -DA:150,0 -DA:151,0 -DA:154,0 -DA:156,0 -DA:158,0 -DA:164,0 -DA:165,0 -DA:168,0 -DA:169,0 -DA:171,0 -DA:172,0 -DA:174,0 -DA:176,0 -DA:179,0 -DA:181,0 -DA:184,0 -DA:186,0 -DA:189,0 -DA:191,0 -DA:194,0 -DA:196,0 -DA:199,0 -DA:201,0 -DA:204,0 -DA:206,0 -DA:209,0 -DA:211,0 -DA:214,0 -DA:216,0 -DA:219,0 -DA:221,0 -DA:224,0 -DA:226,0 -DA:229,0 -DA:231,0 -DA:234,0 -DA:236,0 -DA:239,0 -DA:241,0 -DA:244,0 -DA:245,0 -DA:247,0 -DA:249,0 -DA:252,0 -DA:254,0 -DA:257,0 -DA:259,0 -DA:262,0 -DA:264,0 -DA:267,0 -DA:269,0 -DA:272,0 -DA:274,0 -DA:277,0 -DA:279,0 -DA:282,0 -DA:284,0 -DA:287,0 -DA:289,0 -DA:292,0 -DA:294,0 -DA:297,0 -DA:299,0 -DA:302,0 -DA:304,0 -DA:307,0 -DA:309,0 -DA:312,0 -DA:314,0 -DA:315,0 -DA:318,0 -DA:320,0 -DA:321,0 -DA:324,0 -DA:326,0 -DA:327,0 -DA:330,0 -DA:332,0 -DA:337,0 -DA:339,0 -DA:341,0 -LF:146 -LH:0 -end_of_record -SF:lib/src/rx_workers/rx_workers.dart -DA:7,1 -DA:9,1 -DA:10,0 -DA:44,1 -DA:46,4 -DA:47,2 -DA:49,2 -DA:56,0 -DA:58,0 -DA:59,0 -DA:60,0 -DA:61,0 -DA:63,0 -DA:66,0 -DA:67,0 -DA:68,0 -DA:70,0 -DA:73,0 -DA:97,1 -DA:101,4 -DA:102,1 -DA:103,1 -DA:104,1 -DA:105,1 -DA:106,1 -DA:108,2 -DA:129,1 -DA:133,4 -DA:134,1 -DA:136,2 -DA:138,1 -DA:140,2 -DA:162,1 -DA:165,1 -DA:166,4 -DA:167,2 -DA:168,1 -DA:171,2 -DA:175,1 -DA:185,1 -DA:187,6 -DA:190,0 -DA:191,0 -DA:192,0 -DA:195,0 -DA:196,0 -DA:197,0 -DA:200,0 -LF:48 -LH:29 -end_of_record -SF:lib/src/rx_workers/utils/debouncer.dart -DA:15,1 -DA:17,1 -DA:18,2 -DA:19,3 -DA:23,0 -DA:26,0 -LF:6 -LH:4 -end_of_record diff --git a/packages/get_rx/example/main.dart b/packages/get_rx/example/main.dart deleted file mode 100644 index 76b49fa26..000000000 --- a/packages/get_rx/example/main.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:get_rx/get_rx.dart'; - -void main() { - var count = 0.obs; - ever(count, print); - count++; - count++; - count++; - count++; - count++; - count++; -} diff --git a/packages/get_rx/lib/get_rx.dart b/packages/get_rx/lib/get_rx.dart deleted file mode 100644 index 70fd95ae5..000000000 --- a/packages/get_rx/lib/get_rx.dart +++ /dev/null @@ -1,8 +0,0 @@ -library get_rx; - -export 'src/rx_core/rx_impl.dart'; -export 'src/rx_core/rx_interface.dart'; -export 'src/rx_iterables/rx_list.dart'; -export 'src/rx_iterables/rx_map.dart'; -export 'src/rx_iterables/rx_set.dart'; -export 'src/rx_workers/rx_workers.dart'; diff --git a/packages/get_rx/lib/src/rx_core/rx_impl.dart b/packages/get_rx/lib/src/rx_core/rx_impl.dart deleted file mode 100644 index 6c1e66e72..000000000 --- a/packages/get_rx/lib/src/rx_core/rx_impl.dart +++ /dev/null @@ -1,330 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'package:meta/meta.dart'; - -import '../rx_core/rx_interface.dart'; -part 'rx_num.dart'; - -/// global object that registers against `GetX` and `Obx`, and allows the -/// reactivity -/// of those `Widgets` and Rx values. -RxInterface getObs; - -/// Base Rx class that manages all the stream logic for any Type. -abstract class _RxImpl implements RxInterface { - _RxImpl(T initial) { - _value = initial; - } - StreamController subject = StreamController.broadcast(); - final _subscriptions = HashMap, StreamSubscription>(); - - T _value; - - bool get canUpdate => _subscriptions.isNotEmpty; - - /// Makes this Rx looks like a function so you can update a new - /// value using [rx(someOtherValue)]. Practical to assign the Rx directly - /// to some Widget that has a signature ::onChange( value ) - /// - /// Example: - /// ``` - /// final myText = 'GetX rocks!'.obs; - /// - /// // in your Constructor, just to check it works :P - /// ever( myText, print ) ; - /// - /// // in your build(BuildContext) { - /// TextField( - /// onChanged: myText, - /// ), - ///``` - T call([T v]) { - if (v != null) { - value = v; - } - return value; - } - - /// Makes a direct update of [value] adding it to the Stream - /// useful when you make use of Rx for custom Types to referesh your UI. - /// - /// Sample: - /// ``` - /// class Person { - /// String name, last; - /// int age; - /// Person({this.name, this.last, this.age}); - /// @override - /// String toString() => '$name $last, $age years old'; - /// } - /// - /// final person = Person(name: 'John', last: 'Doe', age: 18).obs; - /// person.value.name = 'Roi'; - /// person.refresh(); - /// print( person ); - /// ``` - void refresh() { - subject.add(value); - } - - /// Uses a callback to update [value] internally, similar to [refresh], - /// but provides the current value as the argument. - /// Makes sense for custom Rx types (like Models). - /// - /// Sample: - /// ``` - /// class Person { - /// String name, last; - /// int age; - /// Person({this.name, this.last, this.age}); - /// @override - /// String toString() => '$name $last, $age years old'; - /// } - /// - /// final person = Person(name: 'John', last: 'Doe', age: 18).obs; - /// person.update((person) { - /// person.name = 'Roi'; - /// }); - /// print( person ); - /// ``` - void update(void fn(T val)) { - fn(_value); - subject.add(_value); - } - - /// updates the value to [null] and adds it to the Stream. - /// Even with null-safety coming, is still an important feature to support, as - /// [call()] doesn't accept [null] values. For instance, - /// [InputDecoration.errorText] has to be null to not show the "error state". - /// - /// Sample: - /// ``` - /// final inputError = ''.obs..nil(); - /// print('${inputError.runtimeType}: $inputError'); // outputs > RxString: null - /// ``` - void nil() { - subject.add(_value = null); - } - - /// Same as `toString()` but using a getter. - String get string => value.toString(); - - @override - String toString() => value.toString(); - - /// Returns the json representation of `value`. - dynamic toJson() => value; - - /// This equality override works for _RxImpl instances and the internal - /// values. - @override - // ignore: avoid_equals_and_hash_code_on_mutable_classes - bool operator ==(dynamic o) { - // Todo, find a common implementation for the hashCode of different Types. - if (o is T) return value == o; - if (o is RxInterface) return value == o.value; - return false; - } - - @override - // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => _value.hashCode; - - /// Closes the subscriptions for this Rx, releasing the resources. - void close() { - _subscriptions.forEach((observable, subscription) => subscription.cancel()); - _subscriptions.clear(); - subject.close(); - } - - /// This is an internal method. - /// Subscribe to changes on the inner stream. - void addListener(Stream rxGetx) { - if (_subscriptions.containsKey(rxGetx)) { - return; - } - _subscriptions[rxGetx] = rxGetx.listen((data) { - subject.add(data); - }); - } - - bool firstRebuild = true; - - /// Updates the [value] and adds it to the stream, updating the observer - /// Widget, only if it's different from the previous value. - set value(T val) { - if (_value == val && !firstRebuild) return; - firstRebuild = false; - _value = val; - subject.add(_value); - } - - /// Returns the current [value] - T get value { - if (getObs != null) { - getObs.addListener(subject.stream); - } - return _value; - } - - Stream get stream => subject.stream; - - StreamSubscription listen(void Function(T) onData, - {Function onError, void Function() onDone, bool cancelOnError}) => - stream.listen(onData, onError: onError, onDone: onDone); - - /// Binds an existing [Stream] to this Rx to keep the values in sync. - /// You can bind multiple sources to update the value. - /// Closing the subscription will happen automatically when the observer - /// Widget ([GetX] or [Obx]) gets unmounted from the Widget tree. - void bindStream(Stream stream) { - _subscriptions[stream] = stream.listen((va) => value = va); - } - - Stream map(R mapper(T data)) => stream.map(mapper); -} - -/// Rx class for `bool` Type. -class RxBool extends _RxImpl { - RxBool([bool initial]) : super(initial); - - bool operator &(bool other) => other && value; - - bool operator |(bool other) => other || value; - - bool operator ^(bool other) => !other == value; - - /// Toggles the bool [value] between false and true. - /// A shortcut for `flag.value = !flag.value;` - /// FIXME: why return this? fluent interface is not - /// not really a dart thing since we have '..' operator - // ignore: avoid_returning_this - RxBool toggle() { - subject.add(_value = !_value); - return this; - } - - String toString() { - return value ? "true" : "false"; - } -} - -/// Rx class for `String` Type. -class RxString extends _RxImpl { - RxString([String initial]) : super(initial); - - String operator +(String val) => _value + val; -} - -/// Foundation class used for custom `Types` outside the common native Dart -/// types. -/// For example, any custom "Model" class, like User().obs will use `Rx` as -/// wrapper. -class Rx extends _RxImpl { - Rx([T initial]) : super(initial); - - // TODO: Look for a way to throw the Exception with proper details when the - // value [T] doesn't implement toJson(). - @override - dynamic toJson() => (value as dynamic)?.toJson(); -} - -enum RxStatus { loading, error, success } - -/// It's Experimental class, the Api can be change -abstract class RxState extends _RxImpl { - RxState(T initial) : super(initial) { - _fillEmptyStatus(); - } - - RxStatus _status; - - bool get isNullOrEmpty { - if (_value == null) return true; - dynamic val = _value; - var result = false; - if (val is Iterable) { - result = val.isEmpty; - } else if (val is String) { - result = val.isEmpty; - } else if (val is Map) { - result = val.isEmpty; - } - return result; - } - - void _fillEmptyStatus() { - _status = isNullOrEmpty ? RxStatus.loading : RxStatus.success; - } - - RxStatus get status { - return _status; - } - - bool get isLoading => _status == RxStatus.loading; - bool get hasError => _status == RxStatus.error; - bool get hasData => _status == RxStatus.success; - - @protected - void refresh() { - subject.add(_value); - } - - @protected - void update(void fn(T val)) { - fn(_value); - subject.add(_value); - } - - @protected - T call([T v]) { - if (v != null) value = v; - return value; - } - - @protected - set value(T val) { - if (_value == val && !firstRebuild) return; - firstRebuild = false; - _value = val; - subject.add(_value); - } - - @protected - void change(T newState, {RxStatus status}) { - if (status != null) { - _status = status; - } - if (newState != _value) { - value = newState; - } - } - - @override - dynamic toJson() => (value as dynamic)?.toJson(); -} - -extension StringExtension on String { - /// Returns a `RxString` with [this] `String` as initial value. - RxString get obs => RxString(this); -} - -extension IntExtension on int { - /// Returns a `RxInt` with [this] `int` as initial value. - RxInt get obs => RxInt(this); -} - -extension DoubleExtension on double { - /// Returns a `RxDouble` with [this] `double` as initial value. - RxDouble get obs => RxDouble(this); -} - -extension BoolExtension on bool { - /// Returns a `RxBool` with [this] `bool` as initial value. - RxBool get obs => RxBool(this); -} - -extension RxT on T { - /// Returns a `Rx` instace with [this] `T` as initial value. - Rx get obs => Rx(this); -} diff --git a/packages/get_rx/lib/src/rx_core/rx_interface.dart b/packages/get_rx/lib/src/rx_core/rx_interface.dart deleted file mode 100644 index 1625bc187..000000000 --- a/packages/get_rx/lib/src/rx_core/rx_interface.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'dart:async'; -import '../rx_typedefs/rx_typedefs.dart'; - -/// This class is the foundation for all reactive (Rx) classes that makes Get -/// so powerful. -/// This interface is the contract that [_RxImpl]<[T]> uses in all it's -/// subclass. -abstract class RxInterface { - RxInterface([T initial]); - - StreamController subject; - - /// Adds a listener to stream - void addListener(Stream rxGetx); - - bool get canUpdate; - - set value(T val); - - T get value; - - /// Closes the stream - // FIXME: shouldn't we expose the returned future? - void close() => subject?.close(); - - /// Calls [callback] with current value, when the value changes. - StreamSubscription listen(ValueCallback callback); -} diff --git a/packages/get_rx/lib/src/rx_core/rx_num.dart b/packages/get_rx/lib/src/rx_core/rx_num.dart deleted file mode 100644 index dd1855638..000000000 --- a/packages/get_rx/lib/src/rx_core/rx_num.dart +++ /dev/null @@ -1,617 +0,0 @@ -part of 'rx_impl.dart'; - -/// Base Rx class for all num Rx's. -abstract class _BaseRxNum extends _RxImpl { - _BaseRxNum(T initial) : super(initial); - - /// Addition operator. */ - - /// Multiplication operator. - num operator *(num other) => value * other; - - /// Euclidean modulo operator. - /// - /// Returns the remainder of the Euclidean division. The Euclidean division of - /// two integers `a` and `b` yields two integers `q` and `r` such that - /// `a == b * q + r` and `0 <= r < b.abs()`. - /// - /// The Euclidean division is only defined for integers, but can be easily - /// extended to work with doubles. In that case `r` may have a non-integer - /// value, but it still verifies `0 <= r < |b|`. - /// - /// The sign of the returned value `r` is always positive. - /// - /// See [remainder] for the remainder of the truncating division. - num operator %(num other) => value % other; - - /// Division operator. - double operator /(num other) => value / other; - - /// Truncating division operator. - /// - /// If either operand is a [double] then the result of the truncating division - /// `a ~/ b` is equivalent to `(a / b).truncate().toInt()`. - /// - /// If both operands are [int]s then `a ~/ b` performs the truncating - /// integer division. - int operator ~/(num other) => value ~/ other; - - /// Negate operator. - num operator -() => -value; - - /// Returns the remainder of the truncating division of `this` by [other]. - /// - /// The result `r` of this operation satisfies: - /// `this == (this ~/ other) * other + r`. - /// As a consequence the remainder `r` has the same sign as the divider - /// `this`. - num remainder(num other) => value.remainder(other); - - /// Relational less than operator. - bool operator <(num other) => value < other; - - /// Relational less than or equal operator. - bool operator <=(num other) => value <= other; - - /// Relational greater than operator. - bool operator >(num other) => value > other; - - /// Relational greater than or equal operator. - bool operator >=(num other) => value >= other; - - /// True if the number is the double Not-a-Number value; otherwise, false. - bool get isNaN => value.isNaN; - - /// True if the number is negative; otherwise, false. - /// - /// Negative numbers are those less than zero, and the double `-0.0`. - bool get isNegative => value.isNegative; - - /// True if the number is positive infinity or negative infinity; otherwise, - /// false. - bool get isInfinite => value.isInfinite; - - /// True if the number is finite; otherwise, false. - /// - /// The only non-finite numbers are NaN, positive infinity, and - /// negative infinity. - bool get isFinite => value.isFinite; - - /// Returns the absolute value of this [num]. - num abs() => value.abs(); - - /// Returns minus one, zero or plus one depending on the sign and - /// numerical value of the number. - /// - /// Returns minus one if the number is less than zero, - /// plus one if the number is greater than zero, - /// and zero if the number is equal to zero. - /// - /// Returns NaN if the number is the double NaN value. - /// - /// Returns a number of the same type as this number. - /// For doubles, `-0.0.sign == -0.0`. - /// The result satisfies: - /// - /// n == n.sign * n.abs() - /// - /// for all numbers `n` (except NaN, because NaN isn't `==` to itself). - num get sign => value.sign; - - /// Returns the integer closest to `this`. - /// - /// Rounds away from zero when there is no closest integer: - /// `(3.5).round() == 4` and `(-3.5).round() == -4`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int round() => value.round(); - - /// Returns the greatest integer no greater than `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int floor() => value.floor(); - - /// Returns the least integer no smaller than `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int ceil() => value.ceil(); - - /// Returns the integer obtained by discarding any fractional - /// digits from `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int truncate() => value.truncate(); - - /// Returns the double integer value closest to `this`. - /// - /// Rounds away from zero when there is no closest integer: - /// `(3.5).roundToDouble() == 4` and `(-3.5).roundToDouble() == -4`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is a - /// non-finite double value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`, - /// and `-0.0` is therefore considered closer to negative numbers than `0.0`. - /// This means that for a value, `d` in the range `-0.5 < d < 0.0`, - /// the result is `-0.0`. - /// - /// The result is always a double. - /// If this is a numerically large integer, the result may be an infinite - /// double. - double roundToDouble() => value.roundToDouble(); - - /// Returns the greatest double integer value no greater than `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is a - /// non-finite double value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `0.0 < d < 1.0` will return `0.0`. - /// - /// The result is always a double. - /// If this is a numerically large integer, the result may be an infinite - /// double. - double floorToDouble() => value.floorToDouble(); - - /// Returns the least double integer value no smaller than `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is a - /// non-finite double value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `-1.0 < d < 0.0` will return `-0.0`. - /// - /// The result is always a double. - /// If this is a numerically large integer, the result may be an infinite - /// double. - double ceilToDouble() => value.ceilToDouble(); - - /// Returns the double integer value obtained by discarding any fractional - /// digits from the double value of `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is a - /// non-finite double value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `-1.0 < d < 0.0` will return `-0.0`, and - /// in the range `0.0 < d < 1.0` it will return 0.0. - /// - /// The result is always a double. - /// If this is a numerically large integer, the result may be an infinite - /// double. - double truncateToDouble() => value.truncateToDouble(); - - /// Returns this [num] clamped to be in the range [lowerLimit]-[upperLimit]. - /// - /// The comparison is done using [compareTo] and therefore takes `-0.0` into - /// account. This also implies that [double.nan] is treated as the maximal - /// double value. - /// - /// The arguments [lowerLimit] and [upperLimit] must form a valid range where - /// `lowerLimit.compareTo(upperLimit) <= 0`. - num clamp(num lowerLimit, num upperLimit) => - value.clamp(lowerLimit, upperLimit); - - /// Truncates this [num] to an integer and returns the result as an [int]. */ - int toInt() => value.toInt(); - - /// Return this [num] as a [double]. - /// - /// If the number is not representable as a [double], an - /// approximation is returned. For numerically large integers, the - /// approximation may be infinite. - double toDouble() => value.toDouble(); - - /// Returns a decimal-point string-representation of `this`. - /// - /// Converts `this` to a [double] before computing the string representation. - /// - /// If the absolute value of `this` is greater or equal to `10^21` then this - /// methods returns an exponential representation computed by - /// `this.toStringAsExponential()`. Otherwise the result - /// is the closest string representation with exactly [fractionDigits] digits - /// after the decimal point. If [fractionDigits] equals 0 then the decimal - /// point is omitted. - /// - /// The parameter [fractionDigits] must be an integer satisfying: - /// `0 <= fractionDigits <= 20`. - /// - /// Examples: - /// - /// 1.toStringAsFixed(3); // 1.000 - /// (4321.12345678).toStringAsFixed(3); // 4321.123 - /// (4321.12345678).toStringAsFixed(5); // 4321.12346 - /// 123456789012345.toStringAsFixed(3); // 123456789012345.000 - /// 10000000000000000.toStringAsFixed(4); // 10000000000000000.0000 - /// 5.25.toStringAsFixed(0); // 5 - String toStringAsFixed(int fractionDigits) => - value.toStringAsFixed(fractionDigits); - - /// Returns an exponential string-representation of `this`. - /// - /// Converts `this` to a [double] before computing the string representation. - /// - /// If [fractionDigits] is given then it must be an integer satisfying: - /// `0 <= fractionDigits <= 20`. In this case the string contains exactly - /// [fractionDigits] after the decimal point. Otherwise, without the - /// parameter, the returned string uses the shortest number of digits that - /// accurately represent [this]. - /// - /// If [fractionDigits] equals 0 then the decimal point is omitted. - /// Examples: - /// - /// 1.toStringAsExponential(); // 1e+0 - /// 1.toStringAsExponential(3); // 1.000e+0 - /// 123456.toStringAsExponential(); // 1.23456e+5 - /// 123456.toStringAsExponential(3); // 1.235e+5 - /// 123.toStringAsExponential(0); // 1e+2 - String toStringAsExponential([int fractionDigits]) => - value.toStringAsExponential(fractionDigits); - - /// Converts `this` to a double and returns a string representation with - /// exactly [precision] significant digits. - /// - /// The parameter [precision] must be an integer satisfying: - /// `1 <= precision <= 21`. - /// - /// Examples: - /// - /// 1.toStringAsPrecision(2); // 1.0 - /// 1e15.toStringAsPrecision(3); // 1.00e+15 - /// 1234567.toStringAsPrecision(3); // 1.23e+6 - /// 1234567.toStringAsPrecision(9); // 1234567.00 - /// 12345678901234567890.toStringAsPrecision(20); // 12345678901234567168 - /// 12345678901234567890.toStringAsPrecision(14); // 1.2345678901235e+19 - /// 0.00000012345.toStringAsPrecision(15); // 1.23450000000000e-7 - /// 0.0000012345.toStringAsPrecision(15); // 0.00000123450000000000 - String toStringAsPrecision(int precision) => - value.toStringAsPrecision(precision); -} - -class RxNum extends _BaseRxNum { - RxNum(num initial) : super(initial); - - num operator +(num other) { - value += other; - return value; - } - - /// Subtraction operator. - num operator -(num other) { - value -= other; - return value; - } -} - -class RxDouble extends _BaseRxNum { - RxDouble([double initial]) : super(initial); - - /// Addition operator. - RxDouble operator +(num other) { - value += other; - return this; - } - - /// Subtraction operator. - RxDouble operator -(num other) { - value -= other; - return this; - } - - /// Multiplication operator. - double operator *(num other) => value * other; - - double operator %(num other) => value % other; - - /// Division operator. - double operator /(num other) => value / other; - - /// Truncating division operator. - /// - /// The result of the truncating division `a ~/ b` is equivalent to - /// `(a / b).truncate()`. - int operator ~/(num other) => value ~/ other; - - /// Negate operator. */ - double operator -() => -value; - - /// Returns the absolute value of this [double]. - double abs() => value.abs(); - - /// Returns the sign of the double's numerical value. - /// - /// Returns -1.0 if the value is less than zero, - /// +1.0 if the value is greater than zero, - /// and the value itself if it is -0.0, 0.0 or NaN. - double get sign => value.sign; - - /// Returns the integer closest to `this`. - /// - /// Rounds away from zero when there is no closest integer: - /// `(3.5).round() == 4` and `(-3.5).round() == -4`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int round() => value.round(); - - /// Returns the greatest integer no greater than `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int floor() => value.floor(); - - /// Returns the least integer no smaller than `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int ceil() => value.ceil(); - - /// Returns the integer obtained by discarding any fractional - /// digits from `this`. - /// - /// If `this` is not finite (`NaN` or infinity), throws an [UnsupportedError]. - int truncate() => value.truncate(); - - /// Returns the integer double value closest to `this`. - /// - /// Rounds away from zero when there is no closest integer: - /// `(3.5).roundToDouble() == 4` and `(-3.5).roundToDouble() == -4`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is - /// not a finite value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`, - /// and `-0.0` is therefore considered closer to negative numbers than `0.0`. - /// This means that for a value, `d` in the range `-0.5 < d < 0.0`, - /// the result is `-0.0`. - double roundToDouble() => value.roundToDouble(); - - /// Returns the greatest integer double value no greater than `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is - /// not a finite value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `0.0 < d < 1.0` will return `0.0`. - double floorToDouble() => value.floorToDouble(); - - /// Returns the least integer double value no smaller than `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is - /// not a finite value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `-1.0 < d < 0.0` will return `-0.0`. - double ceilToDouble() => value.ceilToDouble(); - - /// Returns the integer double value obtained by discarding any fractional - /// digits from `this`. - /// - /// If this is already an integer valued double, including `-0.0`, or it is - /// not a finite value, the value is returned unmodified. - /// - /// For the purpose of rounding, `-0.0` is considered to be below `0.0`. - /// A number `d` in the range `-1.0 < d < 0.0` will return `-0.0`, and - /// in the range `0.0 < d < 1.0` it will return 0.0. - double truncateToDouble() => value.truncateToDouble(); -} - -class RxInt extends _BaseRxNum { - RxInt([int initial]) : super(initial); - - /// Addition operator. - RxInt operator +(int other) { - value += other; - return this; - } - - /// Subtraction operator. - RxInt operator -(int other) { - value -= other; - return this; - } - - /// Bit-wise and operator. - /// - /// Treating both `this` and [other] as sufficiently large two's component - /// integers, the result is a number with only the bits set that are set in - /// both `this` and [other] - /// - /// If both operands are negative, the result is negative, otherwise - /// the result is non-negative. - int operator &(int other) => value & other; - - /// Bit-wise or operator. - /// - /// Treating both `this` and [other] as sufficiently large two's component - /// integers, the result is a number with the bits set that are set in either - /// of `this` and [other] - /// - /// If both operands are non-negative, the result is non-negative, - /// otherwise the result is negative. - int operator |(int other) => value | other; - - /// Bit-wise exclusive-or operator. - /// - /// Treating both `this` and [other] as sufficiently large two's component - /// integers, the result is a number with the bits set that are set in one, - /// but not both, of `this` and [other] - /// - /// If the operands have the same sign, the result is non-negative, - /// otherwise the result is negative. - int operator ^(int other) => value ^ other; - - /// The bit-wise negate operator. - /// - /// Treating `this` as a sufficiently large two's component integer, - /// the result is a number with the opposite bits set. - /// - /// This maps any integer `x` to `-x - 1`. - int operator ~() => ~value; - - /// Shift the bits of this integer to the left by [shiftAmount]. - /// - /// Shifting to the left makes the number larger, effectively multiplying - /// the number by `pow(2, shiftIndex)`. - /// - /// There is no limit on the size of the result. It may be relevant to - /// limit intermediate values by using the "and" operator with a suitable - /// mask. - /// - /// It is an error if [shiftAmount] is negative. - int operator <<(int shiftAmount) => value << shiftAmount; - - /// Shift the bits of this integer to the right by [shiftAmount]. - /// - /// Shifting to the right makes the number smaller and drops the least - /// significant bits, effectively doing an integer division by - ///`pow(2, shiftIndex)`. - /// - /// It is an error if [shiftAmount] is negative. - int operator >>(int shiftAmount) => value >> shiftAmount; - - /// Returns this integer to the power of [exponent] modulo [modulus]. - /// - /// The [exponent] must be non-negative and [modulus] must be - /// positive. - int modPow(int exponent, int modulus) => value.modPow(exponent, modulus); - - /// Returns the modular multiplicative inverse of this integer - /// modulo [modulus]. - /// - /// The [modulus] must be positive. - /// - /// It is an error if no modular inverse exists. - int modInverse(int modulus) => value.modInverse(modulus); - - /// Returns the greatest common divisor of this integer and [other]. - /// - /// If either number is non-zero, the result is the numerically greatest - /// integer dividing both `this` and `other`. - /// - /// The greatest common divisor is independent of the order, - /// so `x.gcd(y)` is always the same as `y.gcd(x)`. - /// - /// For any integer `x`, `x.gcd(x)` is `x.abs()`. - /// - /// If both `this` and `other` is zero, the result is also zero. - int gcd(int other) => value.gcd(other); - - /// Returns true if and only if this integer is even. - bool get isEven => value.isEven; - - /// Returns true if and only if this integer is odd. - bool get isOdd => value.isOdd; - - /// Returns the minimum number of bits required to store this integer. - /// - /// The number of bits excludes the sign bit, which gives the natural length - /// for non-negative (unsigned) values. Negative values are complemented to - /// return the bit position of the first bit that differs from the sign bit. - /// - /// To find the number of bits needed to store the value as a signed value, - /// add one, i.e. use `x.bitLength + 1`. - /// ``` - /// x.bitLength == (-x-1).bitLength - /// - /// 3.bitLength == 2; // 00000011 - /// 2.bitLength == 2; // 00000010 - /// 1.bitLength == 1; // 00000001 - /// 0.bitLength == 0; // 00000000 - /// (-1).bitLength == 0; // 11111111 - /// (-2).bitLength == 1; // 11111110 - /// (-3).bitLength == 2; // 11111101 - /// (-4).bitLength == 2; // 11111100 - /// ``` - int get bitLength => value.bitLength; - - /// Returns the least significant [width] bits of this integer as a - /// non-negative number (i.e. unsigned representation). The returned value - /// has zeros in all bit positions higher than [width]. - /// ``` - /// (-1).toUnsigned(5) == 31 // 11111111 -> 00011111 - /// ``` - /// This operation can be used to simulate arithmetic from low level - /// languages. - /// For example, to increment an 8 bit quantity: - /// ``` - /// q = (q + 1).toUnsigned(8); - /// ``` - /// `q` will count from `0` up to `255` and then wrap around to `0`. - /// - /// If the input fits in [width] bits without truncation, the result is the - /// same as the input. The minimum width needed to avoid truncation of `x` is - /// given by `x.bitLength`, i.e. - /// ``` - /// x == x.toUnsigned(x.bitLength); - /// ``` - int toUnsigned(int width) => value.toUnsigned(width); - - /// Returns the least significant [width] bits of this integer, extending the - /// highest retained bit to the sign. This is the same as truncating the - /// value to fit in [width] bits using an signed 2-s complement - /// representation. - /// The returned value has the same bit value in all positions higher than - /// [width]. - /// - /// ``` - /// V--sign bit-V - /// 16.toSigned(5) == -16 // 00010000 -> 11110000 - /// 239.toSigned(5) == 15 // 11101111 -> 00001111 - /// ^ ^ - /// ``` - /// This operation can be used to simulate arithmetic from low level - /// languages. - /// For example, to increment an 8 bit signed quantity: - /// ``` - /// q = (q + 1).toSigned(8); - /// ``` - /// `q` will count from `0` up to `127`, wrap to `-128` and count back up to - /// `127`. - /// - /// If the input value fits in [width] bits without truncation, the result is - /// the same as the input. The minimum width needed to avoid truncation - /// of `x` is `x.bitLength + 1`, i.e. - /// ``` - /// x == x.toSigned(x.bitLength + 1); - /// ``` - int toSigned(int width) => value.toSigned(width); - - /// Return the negative value of this integer. - /// - /// The result of negating an integer always has the opposite sign, except - /// for zero, which is its own negation. - int operator -() => -value; - - /// Returns the absolute value of this integer. - /// - /// For any integer `x`, the result is the same as `x < 0 ? -x : x`. - int abs() => value.abs(); - - /// Returns the sign of this integer. - /// - /// Returns 0 for zero, -1 for values less than zero and - /// +1 for values greater than zero. - int get sign => value.sign; - - /// Returns `this`. - int round() => value.round(); - - /// Returns `this`. - int floor() => value.floor(); - - /// Returns `this`. - int ceil() => value.ceil(); - - /// Returns `this`. - int truncate() => value.truncate(); - - /// Returns `this.toDouble()`. - double roundToDouble() => value.roundToDouble(); - - /// Returns `this.toDouble()`. - double floorToDouble() => value.floorToDouble(); - - /// Returns `this.toDouble()`. - double ceilToDouble() => value.ceilToDouble(); - - /// Returns `this.toDouble()`. - double truncateToDouble() => value.truncateToDouble(); -} diff --git a/packages/get_rx/lib/src/rx_iterables/rx_list.dart b/packages/get_rx/lib/src/rx_iterables/rx_list.dart deleted file mode 100644 index f9563cf94..000000000 --- a/packages/get_rx/lib/src/rx_iterables/rx_list.dart +++ /dev/null @@ -1,449 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'dart:math'; -import 'package:meta/meta.dart'; - -import '../rx_core/rx_impl.dart'; -import '../rx_core/rx_interface.dart'; -import '../rx_typedefs/rx_typedefs.dart'; - -/// Create a list similar to `List` -class RxList implements List, RxInterface> { - RxList([List initial]) { - if (initial != null) _list = initial; - } - - List _list = []; - - @override - Iterator get iterator => value.iterator; - - @override - bool get isEmpty => value.isEmpty; - - bool get canUpdate { - return _subscriptions.length > 0; - } - - @override - bool get isNotEmpty => value.isNotEmpty; - - @override - StreamController> subject = StreamController.broadcast(); - - final _subscriptions = HashMap>, StreamSubscription>(); - - void operator []=(int index, E val) { - _list[index] = val; - refresh(); - } - - void refresh() { - subject.add(_list); - } - - /// Special override to push() element(s) in a reactive way - /// inside the List, - RxList operator +(Iterable val) { - addAll(val); - refresh(); - return this; - } - - E operator [](int index) { - return value[index]; - } - - void add(E item) { - _list.add(item); - refresh(); - } - - @override - void addAll(Iterable item) { - _list.addAll(item); - refresh(); - } - - /// Add [item] to [List] only if [item] is not null. - void addNonNull(E item) { - if (item != null) add(item); - } - - /// Add [Iterable] to [List] only if [Iterable] is not null. - void addAllNonNull(Iterable item) { - if (item != null) addAll(item); - } - - /// Add [item] to [List] only if [condition] is true. - void addIf(dynamic condition, E item) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) add(item); - } - - /// Adds [Iterable] to [List] only if [condition] is true. - void addAllIf(dynamic condition, Iterable items) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) addAll(items); - } - - @override - void insert(int index, E item) { - _list.insert(index, item); - refresh(); - } - - @override - void insertAll(int index, Iterable iterable) { - _list.insertAll(index, iterable); - refresh(); - } - - @override - int get length => value.length; - - /// Removes an item from the list. - /// - /// This is O(N) in the number of items in the list. - /// - /// Returns whether the item was present in the list. - @override - bool remove(Object item) { - final hasRemoved = _list.remove(item); - if (hasRemoved) { - refresh(); - } - return hasRemoved; - } - - @override - E removeAt(int index) { - final item = _list.removeAt(index); - refresh(); - return item; - } - - @override - E removeLast() { - final item = _list.removeLast(); - refresh(); - return item; - } - - @override - void removeRange(int start, int end) { - _list.removeRange(start, end); - refresh(); - } - - @override - void removeWhere(bool Function(E) test) { - _list.removeWhere(test); - refresh(); - } - - @override - void clear() { - _list.clear(); - refresh(); - } - - @override - void sort([int compare(E a, E b)]) { - _list.sort(compare); - refresh(); - } - - @override - void close() { - _subscriptions.forEach((observable, subscription) { - subscription.cancel(); - }); - _subscriptions.clear(); - subject.close(); - } - - /// Replaces all existing items of this list with [item] - void assign(E item) { - clear(); - add(item); - } - - void update(void fn(Iterable value)) { - fn(value); - refresh(); - } - - /// Replaces all existing items of this list with [items] - void assignAll(Iterable items) { - clear(); - addAll(items); - } - - @protected - List get value { - if (getObs != null) { - getObs.addListener(subject.stream); - } - return _list; - } - - String get string => value.toString(); - - void addListener(Stream> rxGetX) { - if (_subscriptions.containsKey(rxGetX)) { - return; - } - _subscriptions[rxGetX] = rxGetX.listen(subject.add); - } - - set value(List val) { - if (_list == val) return; - _list = val; - refresh(); - } - - Stream> get stream => subject.stream; - - StreamSubscription> listen( - void Function(List) onData, { - Function onError, - void Function() onDone, - bool cancelOnError, - }) => - stream.listen(onData, onError: onError, onDone: onDone); - - /// Binds an existing [Stream] to this [RxList]. - /// You can bind multiple sources to update the value. - /// Closing the subscription will happen automatically when the observer - /// Widget ([GetX] or [Obx]) gets unmounted from the Widget tree. - void bindStream(Stream> stream) { - _subscriptions[stream] = stream.listen((va) => value = va); - } - - @override - E get first => value.first; - - @override - E get last => value.last; - - @override - bool any(bool Function(E) test) { - return value.any(test); - } - - @override - Map asMap() { - return value.asMap(); - } - - @override - List cast() { - return value.cast(); - } - - @override - bool contains(Object element) { - return value.contains(element); - } - - @override - E elementAt(int index) { - return value.elementAt(index); - } - - @override - bool every(bool Function(E) test) { - return value.every(test); - } - - @override - Iterable expand(Iterable Function(E) f) { - return value.expand(f); - } - - @override - void fillRange(int start, int end, [E fillValue]) { - _list.fillRange(start, end, fillValue); - refresh(); - } - - @override - E firstWhere(bool Function(E) test, {E Function() orElse}) { - return value.firstWhere(test, orElse: orElse); - } - - @override - T fold(T initialValue, T Function(T, E) combine) { - return value.fold(initialValue, combine); - } - - @override - Iterable followedBy(Iterable other) { - return value.followedBy(other); - } - - @override - void forEach(void Function(E) f) { - value.forEach(f); - } - - @override - Iterable getRange(int start, int end) { - return value.getRange(start, end); - } - - @override - int indexOf(E element, [int start = 0]) { - return value.indexOf(element, start); - } - - @override - int indexWhere(bool Function(E) test, [int start = 0]) { - return value.indexWhere(test, start); - } - - @override - String join([String separator = ""]) { - return value.join(separator); - } - - @override - int lastIndexOf(E element, [int start]) { - return value.lastIndexOf(element, start); - } - - @override - int lastIndexWhere(bool Function(E) test, [int start]) { - return value.lastIndexWhere(test, start); - } - - @override - E lastWhere(bool Function(E) test, {E Function() orElse}) { - return value.lastWhere(test, orElse: orElse); - } - - @override - set length(int newLength) { - _list.length = newLength; - refresh(); - } - - @override - Iterable map(T Function(E) f) { - return value.map(f); - } - - @override - E reduce(E Function(E, E) combine) { - return value.reduce(combine); - } - - @override - void replaceRange(int start, int end, Iterable replacement) { - _list.replaceRange(start, end, replacement); - refresh(); - } - - @override - void retainWhere(bool Function(E) test) { - _list.retainWhere(test); - refresh(); - } - - @override - Iterable get reversed => value.reversed; - - @override - void setAll(int index, Iterable iterable) { - _list.setAll(index, iterable); - refresh(); - } - - @override - void setRange(int start, int end, Iterable iterable, [int skipCount = 0]) { - _list.setRange(start, end, iterable, skipCount); - refresh(); - } - - @override - void shuffle([Random random]) { - _list.shuffle(random); - refresh(); - } - - @override - E get single => value.single; - - @override - E singleWhere(bool Function(E) test, {E Function() orElse}) { - return value.singleWhere(test, orElse: orElse); - } - - @override - Iterable skip(int count) { - return value.skip(count); - } - - @override - Iterable skipWhile(bool Function(E) test) { - return value.skipWhile(test); - } - - @override - List sublist(int start, [int end]) { - return value.sublist(start, end); - } - - @override - Iterable take(int count) { - return value.take(count); - } - - @override - Iterable takeWhile(bool Function(E) test) { - return value.takeWhile(test); - } - - @override - List toList({bool growable = true}) { - return value.toList(growable: growable); - } - - @override - Set toSet() { - return value.toSet(); - } - - @override - Iterable where(bool Function(E) test) { - return value.where(test); - } - - @override - Iterable whereType() { - return value.whereType(); - } - - @override - set first(E value) { - _list.first = value; - refresh(); - } - - @override - set last(E value) { - _list.last = value; - refresh(); - } -} - -extension ListExtension on List { - RxList get obs { - if (this != null) { - return RxList([])..addAllNonNull(this); - } else { - return RxList(null); - } - } -} diff --git a/packages/get_rx/lib/src/rx_iterables/rx_map.dart b/packages/get_rx/lib/src/rx_iterables/rx_map.dart deleted file mode 100644 index c9b9c26df..000000000 --- a/packages/get_rx/lib/src/rx_iterables/rx_map.dart +++ /dev/null @@ -1,205 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'package:meta/meta.dart'; - -import '../rx_core/rx_impl.dart'; -import '../rx_core/rx_interface.dart'; -import '../rx_typedefs/rx_typedefs.dart'; - -class RxMap implements RxInterface>, Map { - RxMap([Map initial]) { - if (initial != null) _value = initial; - } - - @override - StreamController> subject = StreamController>.broadcast(); - final _subscriptions = HashMap>, StreamSubscription>(); - - Map _value; - - @protected - Map get value { - if (getObs != null) { - getObs.addListener(subject.stream); - } - return _value; - } - - void refresh() { - subject.add(_value); - } - - String get string => value.toString(); - - bool get canUpdate { - return _subscriptions.length > 0; - } - - @override - void close() { - _subscriptions.forEach((observable, subscription) { - subscription.cancel(); - }); - _subscriptions.clear(); - subject.close(); - } - - @override - void addListener(Stream> rxGetX) { - if (_subscriptions.containsKey(rxGetX)) { - return; - } - _subscriptions[rxGetX] = rxGetX.listen((data) { - subject.add(data); - }); - } - - set value(Map val) { - if (_value == val) return; - _value = val; - refresh(); - } - - Stream> get stream => subject.stream; - - StreamSubscription> listen(void Function(Map) onData, - {Function onError, void Function() onDone, bool cancelOnError}) => - stream.listen(onData, onError: onError, onDone: onDone); - - /// Binds an existing [Stream] to this [RxMap]. - /// You can bind multiple sources to update the value. - /// Closing the subscription will happen automatically when the observer - /// Widget ([GetX] or [Obx]) gets unmounted from the Widget tree. - void bindStream(Stream> stream) { - _subscriptions[stream] = stream.listen((va) => value = va); - } - - void add(K key, V value) { - _value[key] = value; - refresh(); - } - - void addIf(dynamic condition, K key, V value) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) { - _value[key] = value; - refresh(); - } - } - - void addAllIf(dynamic condition, Map values) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) addAll(values); - } - - @override - V operator [](Object key) { - return value[key]; - } - - @override - void operator []=(K key, V value) { - _value[key] = value; - refresh(); - } - - @override - void addAll(Map other) { - _value.addAll(other); - refresh(); - } - - @override - void addEntries(Iterable> entries) { - _value.addEntries(entries); - refresh(); - } - - @override - void clear() { - _value.clear(); - refresh(); - } - - @override - Map cast() => value.cast(); - - @override - bool containsKey(Object key) => value.containsKey(key); - - @override - bool containsValue(Object value) => _value.containsValue(value); - - @override - Iterable> get entries => value.entries; - - @override - void forEach(void Function(K, V) f) { - value.forEach(f); - } - - @override - bool get isEmpty => value.isEmpty; - - @override - bool get isNotEmpty => value.isNotEmpty; - - @override - Iterable get keys => value.keys; - - @override - int get length => value.length; - - @override - Map map(MapEntry Function(K, V) transform) => - value.map(transform); - - @override - V putIfAbsent(K key, V Function() ifAbsent) { - final val = _value.putIfAbsent(key, ifAbsent); - refresh(); - return val; - } - - @override - V remove(Object key) { - final val = _value.remove(key); - refresh(); - return val; - } - - @override - void removeWhere(bool Function(K, V) test) { - _value.removeWhere(test); - refresh(); - } - - @override - Iterable get values => value.values; - - @override - String toString() => _value.toString(); - - @override - V update(K key, V Function(V) update, {V Function() ifAbsent}) { - final val = _value.update(key, update, ifAbsent: ifAbsent); - refresh(); - return val; - } - - @override - void updateAll(V Function(K, V) update) { - _value.updateAll(update); - refresh(); - } -} - -extension MapExtension on Map { - RxMap get obs { - if (this != null) { - return RxMap({})..addAll(this); - } else { - return RxMap(null); - } - } -} diff --git a/packages/get_rx/lib/src/rx_iterables/rx_set.dart b/packages/get_rx/lib/src/rx_iterables/rx_set.dart deleted file mode 100644 index d621d6686..000000000 --- a/packages/get_rx/lib/src/rx_iterables/rx_set.dart +++ /dev/null @@ -1,344 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'package:meta/meta.dart'; - -import '../rx_core/rx_impl.dart'; -import '../rx_core/rx_interface.dart'; -import '../rx_typedefs/rx_typedefs.dart'; - -class RxSet implements Set, RxInterface> { - RxSet([Set initial]) { - if (initial != null) _set = initial; - } - - Set _set = {}; - - @override - Iterator get iterator => value.iterator; - - @override - bool get isEmpty => value.isEmpty; - - bool get canUpdate { - return _subscriptions.length > 0; - } - - @override - bool get isNotEmpty => value.isNotEmpty; - - StreamController> subject = StreamController>.broadcast(); - final _subscriptions = HashMap>, StreamSubscription>(); - - /// Adds [item] only if [condition] resolves to true. - void addIf(dynamic condition, E item) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) add(item); - } - - /// Adds all [items] only if [condition] resolves to true. - void addAllIf(dynamic condition, Iterable items) { - if (condition is Condition) condition = condition(); - if (condition is bool && condition) addAll(items); - } - - void refresh() { - subject.add(_set); - } - - /// Special override to push() element(s) in a reactive way - /// inside the List, - RxSet operator +(Set val) { - addAll(val); - refresh(); - return this; - } - - @override - bool add(E value) { - final val = _set.add(value); - refresh(); - return val; - } - - @override - void addAll(Iterable item) { - _set.addAll(item); - refresh(); - } - - /// Adds only if [item] is not null. - void addNonNull(E item) { - if (item != null) add(item); - } - - /// Adds only if [item] is not null. - void addAllNonNull(Iterable item) { - if (item != null) addAll(item); - } - - int get length => value.length; - - /// Removes an item from the list. - /// - /// This is O(N) in the number of items in the list. - /// - /// Returns whether the item was present in the list. - bool remove(Object item) { - var hasRemoved = _set.remove(item); - if (hasRemoved) { - refresh(); - } - return hasRemoved; - } - - void removeWhere(bool Function(E) test) { - _set.removeWhere(test); - refresh(); - } - - void clear() { - _set.clear(); - refresh(); - } - - void close() { - _subscriptions.forEach((observable, subscription) { - subscription.cancel(); - }); - _subscriptions.clear(); - subject.close(); - } - - /// Replaces all existing items of this list with [item] - void assign(E item) { - clear(); - add(item); - } - - void update(void fn(Iterable value)) { - fn(value); - refresh(); - } - - /// Replaces all existing items of this list with [items] - void assignAll(Iterable items) { - clear(); - addAll(items); - } - - @protected - Set get value { - if (getObs != null) { - getObs.addListener(subject.stream); - } - return _set; - } - - String get string => value.toString(); - - void addListener(Stream> rxGetX) { - if (_subscriptions.containsKey(rxGetX)) { - return; - } - _subscriptions[rxGetX] = rxGetX.listen((data) { - subject.add(data); - }); - } - - set value(Set val) { - if (_set == val) return; - _set = val; - refresh(); - } - - Stream> get stream => subject.stream; - - StreamSubscription> listen(void Function(Set) onData, - {Function onError, void Function() onDone, bool cancelOnError}) => - stream.listen(onData, onError: onError, onDone: onDone); - - /// Binds an existing [Stream] to this [RxSet]. - /// You can bind multiple sources to update the value. - /// Closing the subscription will happen automatically when the observer - /// Widget ([GetX] or [Obx]) gets unmounted from the Widget tree. - void bindStream(Stream> stream) { - _subscriptions[stream] = stream.listen((va) => value = va); - } - - @override - E get first => value.first; - - @override - E get last => value.last; - - @override - bool any(bool Function(E) test) { - return value.any(test); - } - - @override - Set cast() { - return value.cast(); - } - - @override - bool contains(Object element) { - return value.contains(element); - } - - @override - E elementAt(int index) { - return value.elementAt(index); - } - - @override - bool every(bool Function(E) test) { - return value.every(test); - } - - @override - Iterable expand(Iterable Function(E) f) { - return value.expand(f); - } - - @override - E firstWhere(bool Function(E) test, {E Function() orElse}) { - return value.firstWhere(test, orElse: orElse); - } - - @override - T fold(T initialValue, T Function(T, E) combine) { - return value.fold(initialValue, combine); - } - - @override - Iterable followedBy(Iterable other) { - return value.followedBy(other); - } - - @override - void forEach(void Function(E) f) { - value.forEach(f); - } - - @override - String join([String separator = ""]) { - return value.join(separator); - } - - @override - E lastWhere(bool Function(E) test, {E Function() orElse}) { - return value.lastWhere(test, orElse: orElse); - } - - @override - Iterable map(T Function(E) f) { - return value.map(f); - } - - @override - E reduce(E Function(E, E) combine) { - return value.reduce(combine); - } - - @override - E get single => value.single; - - @override - E singleWhere(bool Function(E) test, {E Function() orElse}) { - return value.singleWhere(test, orElse: orElse); - } - - @override - Iterable skip(int count) { - return value.skip(count); - } - - @override - Iterable skipWhile(bool Function(E) test) { - return value.skipWhile(test); - } - - @override - Iterable take(int count) { - return value.take(count); - } - - @override - Iterable takeWhile(bool Function(E) test) { - return value.takeWhile(test); - } - - @override - List toList({bool growable = true}) { - return value.toList(growable: growable); - } - - @override - Set toSet() { - return value.toSet(); - } - - @override - Iterable where(bool Function(E) test) { - return value.where(test); - } - - @override - Iterable whereType() { - return value.whereType(); - } - - @override - bool containsAll(Iterable other) { - return value.containsAll(other); - } - - @override - Set difference(Set other) { - return value.difference(other); - } - - @override - Set intersection(Set other) { - return value.intersection(other); - } - - @override - E lookup(Object object) { - return value.lookup(object); - } - - @override - void removeAll(Iterable elements) { - _set.removeAll(elements); - refresh(); - } - - @override - void retainAll(Iterable elements) { - _set.retainAll(elements); - refresh(); - } - - @override - void retainWhere(bool Function(E) E) { - _set.retainWhere(E); - refresh(); - } - - @override - Set union(Set other) { - return value.union(other); - } -} - -extension SetExtension on Set { - RxSet get obs { - if (this != null) { - return RxSet({})..addAllNonNull(this); - } else { - return RxSet(null); - } - } -} diff --git a/packages/get_rx/lib/src/rx_typedefs/rx_typedefs.dart b/packages/get_rx/lib/src/rx_typedefs/rx_typedefs.dart deleted file mode 100644 index dd1bb714e..000000000 --- a/packages/get_rx/lib/src/rx_typedefs/rx_typedefs.dart +++ /dev/null @@ -1,2 +0,0 @@ -typedef Condition = bool Function(); -typedef ValueCallback = Function(T v); diff --git a/packages/get_rx/lib/src/rx_workers/rx_workers.dart b/packages/get_rx/lib/src/rx_workers/rx_workers.dart deleted file mode 100644 index f316a2505..000000000 --- a/packages/get_rx/lib/src/rx_workers/rx_workers.dart +++ /dev/null @@ -1,201 +0,0 @@ -import 'dart:async'; -import 'package:get_core/get_core.dart'; - -import '../rx_core/rx_interface.dart'; -import 'utils/debouncer.dart'; - -bool _conditional(dynamic condition) { - if (condition == null) return true; - if (condition is bool) return condition; - if (condition is bool Function()) return condition(); - return true; -} - -/// -/// Called every time [listener] changes. As long as the [condition] -/// returns true. -/// -/// Sample: -/// Every time increment() is called, ever() will process the [condition] -/// (can be a [bool] expression or a [bool Function()]), and only call -/// the callback when [condition] is true. -/// In our case, only when count is bigger to 5. In order to "dispose" -/// this Worker -/// that will run forever, we made a [worker] variable. So, when the count value -/// reaches 10, the worker gets disposed, and releases any memory resources. -/// -/// ``` -/// // imagine some counter widget... -/// -/// class _CountController extends GetxController { -/// final count = 0.obs; -/// Worker worker; -/// -/// void onInit() { -/// worker = ever(count, (value) { -/// print('counter changed to: $value'); -/// if (value == 10) worker.dispose(); -/// }, condition: () => count > 5); -/// } -/// -/// void increment() => count + 1; -/// } -/// ``` -Worker ever(RxInterface listener, Function(T) callback, - {dynamic condition = true}) { - StreamSubscription sub = listener.subject.stream.listen((event) { - if (_conditional(condition)) callback(event); - }); - return Worker(sub.cancel, '[ever]'); -} - -/// Similar to [ever], but takes a list of [listeners], the condition -/// for the [callback] is common to all [listeners], -/// and the [callback] is executed to each one of them. The [Worker] is -/// common to all, so [worker.dispose()] will cancel all streams. -Worker everAll(List listeners, Function(dynamic) callback, - {dynamic condition = true}) { - final evers = []; - for (var i in listeners) { - final sub = i.subject.stream.listen((event) { - if (_conditional(condition)) callback(event); - }); - evers.add(sub); - } - - Future cancel() { - for (var i in evers) { - i.cancel(); - } - return Future.value(() {}); - } - - return Worker(cancel, '[everAll]'); -} - -/// [once()] will execute only 1 time when [condition] is met and cancel -/// the subscription to the [listener] stream right after that. -/// [condition] defines when [callback] is called, and -/// can be a [bool] or a [bool Function()]. -/// -/// Sample: -/// ``` -/// class _CountController extends GetxController { -/// final count = 0.obs; -/// Worker worker; -/// -/// @override -/// Future onInit() async { -/// worker = once(count, (value) { -/// print("counter reached $value before 3 seconds."); -/// }, condition: () => count() > 2); -/// 3.delay(worker.dispose); -/// } -/// void increment() => count + 1; -/// } -///``` -Worker once(RxInterface listener, Function(T) callback, - {dynamic condition}) { - Worker ref; - StreamSubscription sub; - sub = listener.subject.stream.listen((event) { - if (!_conditional(condition)) return; - ref._disposed = true; - ref._log('called'); - sub?.cancel(); - callback(event); - }); - ref = Worker(sub.cancel, '[once]'); - return ref; -} - -/// Ignore all changes in [listener] during [time] (1 sec by default) or until -/// [condition] is met (can be a [bool] expression or a [bool Function()]), -/// It brings the 1st "value" since the period of time, so -/// if you click a counter button 3 times in 1 sec, it will show you "1" -/// (after 1 sec of the first press) -/// click counter 3 times in 1 sec, it will show you "4" (after 1 sec) -/// click counter 2 times in 1 sec, it will show you "7" (after 1 sec). -/// -/// Sample: -/// // wait 1 sec each time an event starts, only if counter is lower than 20. -/// worker = interval( -/// count, -/// (value) => print(value), -/// time: 1.seconds, -/// condition: () => count < 20, -/// ); -/// ``` -Worker interval(RxInterface listener, Function(T) callback, - {Duration time = const Duration(seconds: 1), dynamic condition = true}) { - var debounceActive = false; - time ??= const Duration(seconds: 1); - StreamSubscription sub = listener.subject.stream.listen((event) async { - if (debounceActive || !_conditional(condition)) return; - debounceActive = true; - await Future.delayed(time); - debounceActive = false; - callback(event); - }); - return Worker(sub.cancel, '[interval]'); -} - -/// [debounce] is similar to [interval], but sends the last value. -/// Useful for Anti DDos, every time the user stops typing for 1 second, -/// for instance. -/// When [listener] emits the last "value", when [time] hits, -/// it calls [callback] with the last "value" emitted. -/// -/// Sample: -/// -/// ``` -/// worker = debounce( -/// count, -/// (value) { -/// print(value); -/// if( value > 20 ) worker.dispose(); -/// }, -/// time: 1.seconds, -/// ); -/// } -/// ``` -Worker debounce(RxInterface listener, Function(T) callback, - {Duration time}) { - final _debouncer = - Debouncer(delay: time ?? const Duration(milliseconds: 800)); - StreamSubscription sub = listener.subject.stream.listen((event) { - _debouncer(() { - callback(event); - }); - }); - return Worker(sub.cancel, '[debounce]'); -} - -class Worker { - Worker(this.worker, this.type); - - /// subscription.cancel() callback - final Future Function() worker; - - /// type of worker (debounce, interval, ever).. - final String type; - bool _disposed = false; - - //final bool _verbose = true; - void _log(String msg) { - // if (!_verbose) return; - Get.log('$runtimeType $type $msg'); - } - - void dispose() { - if (_disposed) { - _log('already disposed'); - return; - } - _disposed = true; - worker(); - _log('disposed'); - } - - void call() => dispose(); -} diff --git a/packages/get_rx/lib/src/rx_workers/utils/debouncer.dart b/packages/get_rx/lib/src/rx_workers/utils/debouncer.dart deleted file mode 100644 index a304fe092..000000000 --- a/packages/get_rx/lib/src/rx_workers/utils/debouncer.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:async'; - -/// This "function" class is the implementation of [debouncer()] Worker. -/// It calls the function passed after specified [delay] parameter. -/// Example: -/// ``` -/// final delayed = Debouncer( delay: Duration( seconds: 1 )) ; -/// print( 'the next function will be called after 1 sec' ); -/// delayed( () => print( 'called after 1 sec' )); -/// ``` -class Debouncer { - final Duration delay; - Timer _timer; - - Debouncer({this.delay}); - - void call(void Function() action) { - _timer?.cancel(); - _timer = Timer(delay, action); - } - - /// Notifies if the delayed call is active. - bool get isRunning => _timer?.isActive ?? false; - - /// Cancel the current delayed call. - void cancel() => _timer?.cancel(); -} diff --git a/packages/get_rx/pubspec.yaml b/packages/get_rx/pubspec.yaml deleted file mode 100644 index bd6fdae92..000000000 --- a/packages/get_rx/pubspec.yaml +++ /dev/null @@ -1,19 +0,0 @@ -name: get_rx -description: A set of powerful tools to provide reactive programming for the GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - - -dependencies: - get_core: ">=3.13.0 <4.0.0" - get_instance: ">=3.13.0 <4.0.0" - meta: ">=1.1.0 <2.0.0" - - -dev_dependencies: - test: ">=1.0.0 <2.0.0" - test_coverage: ">=0.4.3 <1.0.0" - diff --git a/packages/get_rx/test/rx_workers_test.dart b/packages/get_rx/test/rx_workers_test.dart deleted file mode 100644 index ab5d1e25d..000000000 --- a/packages/get_rx/test/rx_workers_test.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'package:get_rx/get_rx.dart'; -import 'package:test/test.dart'; - -void main() { - test('once', () async { - final count = 0.obs; - var result = -1; - once(count, (_) { - result = _ as int; - }); - count.value++; - await Future.delayed(Duration.zero); - expect(1, result); - count.value++; - await Future.delayed(Duration.zero); - expect(1, result); - count.value++; - await Future.delayed(Duration.zero); - expect(1, result); - }); - - test('ever', () async { - final count = 0.obs; - var result = -1; - ever(count, (_) { - result = _ as int; - }); - count.value++; - await Future.delayed(Duration.zero); - expect(1, result); - count.value++; - await Future.delayed(Duration.zero); - expect(2, result); - count.value++; - await Future.delayed(Duration.zero); - expect(3, result); - }); - - test('debounce', () async { - final count = 0.obs; - var result = -1; - debounce(count, (_) { - // print(_); - result = _ as int; - }, time: Duration(milliseconds: 100)); - - count.value++; - count.value++; - count.value++; - count.value++; - await Future.delayed(Duration.zero); - expect(-1, result); - await Future.delayed(Duration(milliseconds: 100)); - expect(4, result); - }); - - test('interval', () async { - final count = 0.obs; - var result = -1; - interval(count, (_) { - // print(_); - result = _ as int; - }, time: Duration(milliseconds: 100)); - - count.value++; - await Future.delayed(Duration.zero); - await Future.delayed(Duration(milliseconds: 100)); - expect(1, result); - count.value++; - count.value++; - count.value++; - await Future.delayed(Duration.zero); - await Future.delayed(Duration(milliseconds: 100)); - expect(2, result); - count.value++; - await Future.delayed(Duration.zero); - await Future.delayed(Duration(milliseconds: 100)); - expect(5, result); - }); -} diff --git a/packages/get_state_manager/.gitignore b/packages/get_state_manager/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_state_manager/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_state_manager/.metadata b/packages/get_state_manager/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_state_manager/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_state_manager/CHANGELOG.md b/packages/get_state_manager/CHANGELOG.md deleted file mode 100644 index c895ba06f..000000000 --- a/packages/get_state_manager/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 - -## [3.10.2] - -- initial release diff --git a/packages/get_state_manager/LICENSE b/packages/get_state_manager/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_state_manager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_state_manager/README.md b/packages/get_state_manager/README.md deleted file mode 100644 index 6c6cf562a..000000000 --- a/packages/get_state_manager/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_state_manager - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_state_manager/analysis_options.yaml b/packages/get_state_manager/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_state_manager/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_state_manager/lib/get_state_manager.dart b/packages/get_state_manager/lib/get_state_manager.dart deleted file mode 100644 index 24df24f23..000000000 --- a/packages/get_state_manager/lib/get_state_manager.dart +++ /dev/null @@ -1,13 +0,0 @@ -library get_state_manager; - -export 'package:get_instance/get_instance.dart'; -export 'package:get_rx/get_rx.dart'; -export 'src/rx_flutter/rx_disposable.dart'; -export 'src/rx_flutter/rx_getx_widget.dart'; -export 'src/rx_flutter/rx_obx_widget.dart'; -export 'src/rx_flutter/rx_ticket_provider_mixin.dart'; -export 'src/simple/get_state.dart'; -export 'src/simple/get_view.dart'; -export 'src/simple/immutable_state.dart'; -export 'src/simple/mixin_state.dart'; -export 'src/simple/simple_builder.dart'; diff --git a/packages/get_state_manager/lib/src/rx_flutter/rx_disposable.dart b/packages/get_state_manager/lib/src/rx_flutter/rx_disposable.dart deleted file mode 100644 index fc833b6df..000000000 --- a/packages/get_state_manager/lib/src/rx_flutter/rx_disposable.dart +++ /dev/null @@ -1,48 +0,0 @@ -import 'package:flutter/scheduler.dart'; -import 'package:get_instance/get_instance.dart'; - -/// Unlike GetxController, which serves to control events on each of its pages, -/// GetxService is not automatically disposed (nor can be removed with -/// Get.delete()). -/// It is ideal for situations where, once started, that service will -/// remain in memory, such as Auth control for example. Only way to remove -/// it is Get.reset(). -abstract class GetxService extends DisposableInterface with GetxServiceMixin {} - -abstract class DisposableInterface extends GetLifeCycle { - bool _initialized = false; - - /// Checks whether the controller has already been initialized. - bool get initialized => _initialized; - - DisposableInterface() { - onStart.callback = _onStart; - } - - // Internal callback that starts the cycle of this controller. - void _onStart() { - onInit(); - _initialized = true; - SchedulerBinding.instance?.addPostFrameCallback((_) => onReady()); - } - - /// Called immediately after the widget is allocated in memory. - /// You might use this to initialize something for the controller. - @override - void onInit() {} - - /// Called 1 frame after onInit(). It is the perfect place to enter - /// navigation events, like snackbar, dialogs, or a new route, or - /// async request. - @override - void onReady() {} - - /// Called before [onDelete] method. [onClose] might be used to - /// dispose resources used by the controller. Like closing events, - /// or streams before the controller is destroyed. - /// Or dispose objects that can potentially create some memory leaks, - /// like TextEditingControllers, AnimationControllers. - /// Might be useful as well to persist some data on disk. - @override - void onClose() {} -} diff --git a/packages/get_state_manager/lib/src/rx_flutter/rx_getx_widget.dart b/packages/get_state_manager/lib/src/rx_flutter/rx_getx_widget.dart deleted file mode 100644 index a9cf97159..000000000 --- a/packages/get_state_manager/lib/src/rx_flutter/rx_getx_widget.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/widgets.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import 'package:get_rx/get_rx.dart'; -import '../../get_state_manager.dart'; - -typedef GetXControllerBuilder = Widget Function( - T controller); - -class GetX extends StatefulWidget { - final GetXControllerBuilder builder; - final bool global; - - // final Stream Function(T) stream; - // final StreamController Function(T) streamController; - final bool autoRemove; - final bool assignId; - final void Function(State state) initState, dispose, didChangeDependencies; - final void Function(GetX oldWidget, State state) didUpdateWidget; - final T init; - final String tag; - - const GetX({ - this.tag, - this.builder, - this.global = true, - this.autoRemove = true, - this.initState, - this.assignId = false, - // this.stream, - this.dispose, - this.didChangeDependencies, - this.didUpdateWidget, - this.init, - // this.streamController - }); - - GetImplXState createState() => GetImplXState(); -} - -class GetImplXState extends State> { - RxInterface _observer; - T controller; - bool isCreator = false; - StreamSubscription subs; - - @override - void initState() { - _observer = Rx(); - var isPrepared = GetInstance().isPrepared(tag: widget.tag); - var isRegistered = GetInstance().isRegistered(tag: widget.tag); - - if (widget.global) { - if (isPrepared) { - if (Get.smartManagement != SmartManagement.keepFactory) { - isCreator = true; - } - controller = GetInstance().find(tag: widget.tag); - } else if (isRegistered) { - controller = GetInstance().find(tag: widget.tag); - isCreator = false; - } else { - controller = widget.init; - isCreator = true; - GetInstance().put(controller, tag: widget.tag); - } - } else { - controller = widget.init; - isCreator = true; - controller?.onStart(); - } - if (widget.initState != null) widget.initState(this); - if (widget.global && Get.smartManagement == SmartManagement.onlyBuilder) { - controller?.onStart(); - } - subs = _observer.subject.stream.listen((data) => setState(() {})); - super.initState(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (widget.didChangeDependencies != null) { - widget.didChangeDependencies(this); - } - } - - @override - void didUpdateWidget(GetX oldWidget) { - super.didUpdateWidget(oldWidget as GetX); - if (widget.didUpdateWidget != null) widget.didUpdateWidget(oldWidget, this); - } - - @override - void dispose() { - if (widget.dispose != null) widget.dispose(this); - if (isCreator || widget.assignId) { - if (widget.autoRemove && GetInstance().isRegistered(tag: widget.tag)) { - GetInstance().delete(tag: widget.tag); - } - } - subs.cancel(); - _observer.close(); - controller = null; - isCreator = null; - super.dispose(); - } - - Widget get notifyChildren { - final observer = getObs; - getObs = _observer; - final result = widget.builder(controller); - if (!_observer.canUpdate) { - throw """ - [Get] the improper use of a GetX has been detected. - You should only use GetX or Obx for the specific widget that will be updated. - If you are seeing this error, you probably did not insert any observable variables into GetX/Obx - or insert them outside the scope that GetX considers suitable for an update - (example: GetX => HeavyWidget => variableObservable). - If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. - """; - } - getObs = observer; - return result; - } - - @override - Widget build(BuildContext context) => notifyChildren; -} diff --git a/packages/get_state_manager/lib/src/rx_flutter/rx_obx_widget.dart b/packages/get_state_manager/lib/src/rx_flutter/rx_obx_widget.dart deleted file mode 100644 index 62d29db12..000000000 --- a/packages/get_state_manager/lib/src/rx_flutter/rx_obx_widget.dart +++ /dev/null @@ -1,120 +0,0 @@ -import 'dart:async'; -import 'package:flutter/widgets.dart'; -import 'package:get_rx/get_rx.dart'; - -typedef WidgetCallback = Widget Function(); - -/// The simplest reactive widget in GetX. -/// -/// Just pass your Rx variable in the root scope of the callback to have it -/// automatically registered for changes. -/// -/// final _name = "GetX".obs; -/// Obx(() => Text( _name.value )),... ; -class Obx extends StatefulWidget { - final WidgetCallback builder; - - const Obx(this.builder); - - _ObxState createState() => _ObxState(); -} - -class _ObxState extends State { - RxInterface _observer; - StreamSubscription subs; - - _ObxState() { - _observer = Rx(); - } - - @override - void initState() { - subs = _observer.subject.stream.listen((data) => setState(() {})); - super.initState(); - } - - @override - void dispose() { - subs.cancel(); - _observer.close(); - super.dispose(); - } - - Widget get notifyChilds { - final observer = getObs; - getObs = _observer; - final result = widget.builder(); - if (!_observer.canUpdate) { - throw """ - [Get] the improper use of a GetX has been detected. - You should only use GetX or Obx for the specific widget that will be updated. - If you are seeing this error, you probably did not insert any observable variables into GetX/Obx - or insert them outside the scope that GetX considers suitable for an update - (example: GetX => HeavyWidget => variableObservable). - If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. - """; - } - getObs = observer; - return result; - } - - @override - Widget build(BuildContext context) => notifyChilds; -} - -/// Similar to Obx, but manages a local state. -/// Pass the initial data in constructor. -/// Useful for simple local states, like toggles, visibility, themes, -/// button states, etc. -/// Sample: -/// ObxValue((data) => Switch( -/// value: data.value, -/// onChanged: (flag) => data.value = flag, -/// ), -/// false.obs, -/// ), - -// TODO: change T to a proper Rx interface, that includes the accessor -// for ::value -class ObxValue extends StatefulWidget { - final Widget Function(T) builder; - final T data; - - const ObxValue(this.builder, this.data, {Key key}) : super(key: key); - - _ObxValueState createState() => _ObxValueState(); -} - -class _ObxValueState extends State { - RxInterface _observer; - StreamSubscription subs; - - _ObxValueState() { - _observer = Rx(); - } - - @override - void initState() { - subs = _observer.subject.stream.listen((data) => setState(() {})); - super.initState(); - } - - @override - void dispose() { - subs.cancel(); - _observer.close(); - super.dispose(); - } - - Widget get notifyChilds { - final observer = getObs; - getObs = _observer; - // observable is implicity taken from the constructor. - final result = widget.builder(widget.data); - getObs = observer; - return result; - } - - @override - Widget build(BuildContext context) => notifyChilds; -} diff --git a/packages/get_state_manager/lib/src/rx_flutter/rx_ticket_provider_mixin.dart b/packages/get_state_manager/lib/src/rx_flutter/rx_ticket_provider_mixin.dart deleted file mode 100644 index 4795afff9..000000000 --- a/packages/get_state_manager/lib/src/rx_flutter/rx_ticket_provider_mixin.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:flutter/scheduler.dart'; -import '../../get_state_manager.dart'; - -/// Used like [SingleTickerProviderMixin] but only with Get Controllers. -/// Simplifies AnimationController creation inside GetxController. -/// -/// Example: -///``` -///class SplashController extends GetxController with -/// SingleGetTickerProviderMixin { -/// AnimationController _ac; -/// -/// @override -/// void onInit() { -/// final dur = const Duration(seconds: 2); -/// _ac = AnimationController.unbounded(duration: dur, vsync: this); -/// _ac.repeat(); -/// _ac.addListener(() => print("Animation Controller value: ${_ac.value}")); -/// } -/// ... -/// ``` -mixin SingleGetTickerProviderMixin on DisposableInterface - implements TickerProvider { - Ticker createTicker(TickerCallback onTick) => Ticker(onTick); -} diff --git a/packages/get_state_manager/lib/src/simple/get_state.dart b/packages/get_state_manager/lib/src/simple/get_state.dart deleted file mode 100644 index 208baa98c..000000000 --- a/packages/get_state_manager/lib/src/simple/get_state.dart +++ /dev/null @@ -1,305 +0,0 @@ -import 'dart:collection'; -import 'package:flutter/material.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import '../../get_state_manager.dart'; - -import 'simple_builder.dart'; - -// Changed to VoidCallback. -//typedef Disposer = void Function(); - -// replacing StateSetter, return if the Widget is mounted for extra validation. -// if it brings overhead the extra call, -typedef GetStateUpdate = void Function(); -//typedef GetStateUpdate = void Function(VoidCallback fn); - -/// Complies with [GetStateUpdater] -/// -/// This mixin's function represents a [GetStateUpdater], and might be used -/// by [GetBuilder()], [SimpleBuilder()] (or similar) to comply -/// with [GetStateUpdate] signature. REPLACING the [StateSetter]. -/// Avoids the potential (but extremely unlikely) issue of having -/// the Widget in a dispose() state, and abstracts the -/// API from the ugly fn((){}). -mixin GetStateUpdaterMixin on State { - // To avoid the creation of an anonym function to be GC later. - // ignore: prefer_function_declarations_over_variables - - /// Experimental method to replace setState((){}); - /// Used with GetStateUpdate. - void getUpdate() { - if (mounted) setState(() {}); - } -} - -class GetxController extends DisposableInterface { - final _updaters = HashSet(); - -// final _updatersIds = HashMap(); // - final _updatersIds = HashMap(); - - final _updatersGroupIds = HashMap>(); - - /// Rebuilds [GetBuilder] each time you call [update()]; - /// Can take a List of [ids], that will only update the matching - /// `GetBuilder( id: )`, - /// [ids] can be reused among `GetBuilders` like group tags. - /// The update will only notify the Widgets, if [condition] is true. - void update([List ids, bool condition = true]) { - if (!condition) { - return; - } - if (ids == null) { -// _updaters?.forEach((rs) => rs(() {})); // - for (final updater in _updaters) { - updater(); - } - } else { - // @jonny, remove this commented code if it's not more optimized. -// for (final id in ids) { -// if (_updatersIds[id] != null) _updatersIds[id](); -// if (_updatersGroupIds[id] != null) -// for (final rs in _updatersGroupIds[id]) rs(); -// } - - for (final id in ids) { - _updatersIds[id]?.call(); - // ignore: avoid_function_literals_in_foreach_calls - _updatersGroupIds[id]?.forEach((rs) => rs()); - } - } - } - -// VoidCallback addListener(StateSetter listener) {// - VoidCallback addListener(GetStateUpdate listener) { - _updaters.add(listener); - return () => _updaters.remove(listener); - } - -// VoidCallback addListenerId(String key, StateSetter listener) {// - VoidCallback addListenerId(String key, GetStateUpdate listener) { -// _printCurrentIds(); - if (_updatersIds.containsKey(key)) { - _updatersGroupIds[key] ??= HashSet.identity(); - _updatersGroupIds[key].add(listener); - return () { - _updatersGroupIds[key].remove(listener); - }; - } else { - _updatersIds[key] = listener; - return () => _updatersIds.remove(key); - } - } - - /// To dispose an [id] from future updates(), this ids are registered - /// by [GetBuilder()] or similar, so is a way to unlink the state change with - /// the Widget from the Controller. - void disposeId(String id) { - _updatersIds.remove(id); - _updatersGroupIds.remove(id); - } - - /// Remove this after checking the new implementation makes sense. - /// Uncomment this if you wanna control the removal of ids.. - /// bool _debugging = false; - /// Future _printCurrentIds() async { - /// if (_debugging) return; - /// _debugging = true; - /// print('about to debug...'); - /// await Future.delayed(Duration(milliseconds: 10)); - /// int totalGroups = 0; - /// _updatersGroupIds.forEach((key, value) { - /// totalGroups += value.length; - /// }); - /// int totalIds = _updatersIds.length; - /// print( - /// 'Total: ${totalIds + totalGroups},'+ - /// 'in groups:$totalGroups, solo ids:$totalIds',); - /// _debugging = false; - /// } -} - -typedef GetControllerBuilder = Widget Function( - T controller); - -class GetBuilder extends StatefulWidget { - final GetControllerBuilder builder; - final bool global; - final String id; - final String tag; - final bool autoRemove; - final bool assignId; - final void Function(State state) initState, dispose, didChangeDependencies; - final void Function(GetBuilder oldWidget, State state) didUpdateWidget; - final T init; - - const GetBuilder({ - Key key, - this.init, - this.global = true, - @required this.builder, - this.autoRemove = true, - this.assignId = false, - this.initState, - this.tag, - this.dispose, - this.id, - this.didChangeDependencies, - this.didUpdateWidget, - }) : assert(builder != null), - super(key: key); - - @override - _GetBuilderState createState() => _GetBuilderState(); -} - -class _GetBuilderState extends State> - with GetStateUpdaterMixin { - T controller; - - bool isCreator = false; - VoidCallback remove; - - @override - void initState() { - super.initState(); - - if (widget.initState != null) widget.initState(this); - if (widget.global) { - final isPrepared = GetInstance().isPrepared(tag: widget.tag); - final isRegistered = GetInstance().isRegistered(tag: widget.tag); - - if (isPrepared) { - if (Get.smartManagement != SmartManagement.keepFactory) { - isCreator = true; - } - controller = GetInstance().find(tag: widget.tag); - } else if (isRegistered) { - controller = GetInstance().find(tag: widget.tag); - isCreator = false; - } else { - controller = widget.init; - isCreator = true; - GetInstance().put(controller, tag: widget.tag); - } - } else { - controller = widget.init; - isCreator = true; - controller?.onStart(); - } - - // if (widget.global && Get.smartManagement == - //SmartManagement.onlyBuilder) { - // controller?.onStart(); - // } - _subscribeToController(); - } - - /// Register to listen Controller's events. - /// It gets a reference to the remove() callback, to delete the - /// setState "link" from the Controller. - void _subscribeToController() { - remove?.call(); - remove = (widget.id == null) -// ? controller?.addListener(setState) // -// : controller?.addListenerId(widget.id, setState); // - ? controller?.addListener(getUpdate) - : controller?.addListenerId(widget.id, getUpdate); - } - - /// Sample for [GetStateUpdate] when you don't wanna - /// use [GetStateHelper mixin]. - /// bool _getUpdater() { - /// final _mounted = mounted; - /// if (_mounted) setState(() {}); - /// return _mounted; - /// } - - @override - void dispose() { - super.dispose(); - if (widget.dispose != null) widget.dispose(this); - if (isCreator || widget.assignId) { - if (widget.autoRemove && GetInstance().isRegistered(tag: widget.tag)) { - GetInstance().delete(tag: widget.tag); - } - } - - remove?.call(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (widget.didChangeDependencies != null) { - widget.didChangeDependencies(this); - } - } - - @override - void didUpdateWidget(GetBuilder oldWidget) { - super.didUpdateWidget(oldWidget as GetBuilder); - // to avoid conflicts when modifying a "grouped" id list. - if (oldWidget.id != widget.id) { - _subscribeToController(); - } - if (widget.didUpdateWidget != null) widget.didUpdateWidget(oldWidget, this); - } - - @override - Widget build(BuildContext context) => widget.builder(controller); -} - -/// This is a experimental feature. -/// Meant to be used with SimpleBuilder, it auto-registers the variable -/// like Rx() does with Obx(). -class Value extends GetxController { - Value([this._value]); - - T _value; - - T get value { - TaskManager.instance.notify(_updaters); - return _value; - } - - set value(T newValue) { - if (_value == newValue) return; - _value = newValue; - update(); - } -} - -/// It's Experimental class, the Api can be change -abstract class GetState extends GetxController { - GetState(T initialValue) { - _state = initialValue; - } - - // StreamController _subject; - - // @override - // void onClose() { - // _subject?.close(); - // } - - // Stream get stream { - // if (_subject == null) { - // _subject = StreamController.broadcast(); - // } - // return _subject.stream; - // } - - T _state; - - T get state => _state; - - @protected - void change(T newState) { - if (newState != _state) { - _state = newState; - update(); - } - } -} diff --git a/packages/get_state_manager/lib/src/simple/get_view.dart b/packages/get_state_manager/lib/src/simple/get_view.dart deleted file mode 100644 index 8c452f03f..000000000 --- a/packages/get_state_manager/lib/src/simple/get_view.dart +++ /dev/null @@ -1,120 +0,0 @@ -import 'package:flutter/widgets.dart'; -import 'package:get_instance/get_instance.dart'; -import '../rx_flutter/rx_disposable.dart'; - -/// GetView is a great way of quickly access your Controller -/// without having to call Get.find() yourself. -/// -/// Sample: -/// ``` -/// class AwesomeController extends GetxController { -/// final String title = 'My Awesome View'; -/// } -/// -/// class AwesomeView extends GetView { -/// /// if you need you can pass the tag for -/// /// Get.find(tag:"myTag"); -/// @override -/// final String tag = "myTag"; -/// -/// AwesomeView({Key key}):super(key:key); -/// -/// @override -/// Widget build(BuildContext context) { -/// return Container( -/// padding: EdgeInsets.all(20), -/// child: Text( controller.title ), -/// ); -/// } -/// } -///`` -abstract class GetView extends StatelessWidget { - const GetView({Key key}) : super(key: key); - - final String tag = null; - - T get controller => GetInstance().find(tag: tag); - - @override - Widget build(BuildContext context); -} - -abstract class GetWidget - extends GetStatelessWidget { - GetWidget({Key key}) : super(key: key); - - final Set _value = {}; - - final String tag = null; - - T get controller { - if (_value.isEmpty) _value.add(GetInstance().find(tag: tag)); - return _value.first; - } - - @override - Widget build(BuildContext context); -} - -// abstract class GetView extends StatelessWidget { -// const GetView({Key key}) : super(key: key); -// A get controller => GetInstance().find(); -// B get controller2 => GetInstance().find(); - -// @override -// Widget build(BuildContext context); -// } - -// abstract class GetView2 extends StatelessWidget { -// const GetView2({Key key}) : super(key: key); -// A get controller => GetInstance().find(); -// B get controller2 => GetInstance().find(); -// C get controller3 => GetInstance().find(); - -// @override -// Widget build(BuildContext context); -// } - -class GetStatelessElement extends ComponentElement { - GetStatelessElement(GetStatelessWidget widget) : super(widget); - - @override - GetStatelessWidget get widget => super.widget as GetStatelessWidget; - - @override - Widget build() => widget.build(this); - - @override - void update(GetStatelessWidget newWidget) { - super.update(newWidget); - markNeedsBuild(); - rebuild(); - } - - @override - void mount(Element parent, dynamic newSlot) { - if (widget?.controller?.initialized != null && - !widget.controller.initialized) { - widget?.controller?.onStart(); - } - - super.mount(parent, newSlot); - } - - @override - void unmount() { - widget?.controller?.onClose(); - super.unmount(); - } -} - -abstract class GetStatelessWidget - extends Widget { - const GetStatelessWidget({Key key}) : super(key: key); - @override - GetStatelessElement createElement() => GetStatelessElement(this); - @protected - Widget build(BuildContext context); - - T get controller; -} diff --git a/packages/get_state_manager/lib/src/simple/immutable_state.dart b/packages/get_state_manager/lib/src/simple/immutable_state.dart deleted file mode 100644 index 73f58709b..000000000 --- a/packages/get_state_manager/lib/src/simple/immutable_state.dart +++ /dev/null @@ -1,148 +0,0 @@ -//import 'package:flutter/foundation.dart'; -//import 'package:flutter/material.dart'; -//import 'package:get/state_manager.dart'; -// -//import '../../instance/get_instance.dart'; -// -//abstract class GetState extends DisposableInterface { -// GetState(this.initialValue) { -// _state = initialValue; -// } -// -// final Set _updaters = {}; -// -// @protected -// void update(T value, [bool condition = true]) { -// if (!condition) return; -// _state = value; -// _updaters.forEach((rs) => rs(() {})); -// } -// -// T _state; -// -// final T initialValue; -// -// void addListener(StateSetter value) { -// _updaters.add(value); -// } -// -// void removeListener(StateSetter value) { -// _updaters.add(value); -// } -// -// // @protected -// T get state => _state; -// -// @protected -// void updater(void fn(T value)) { -// fn(_state); -// update(_state); -// } -//} -// -//class StateBuilder extends StatefulWidget { -// final Widget Function(dynamic) builder; -// final bool global; -// final String tag; -// final bool autoRemove; -// final bool assignId; -// final void Function(State state) initState, dispose, didChangeDependencies; -// final void Function(StateBuilder oldWidget, State state) didUpdateWidget; -// final T Function() state; -// -// const StateBuilder({ -// Key key, -// this.state, -// this.global = true, -// @required this.builder, -// this.autoRemove = true, -// this.assignId = false, -// this.initState, -// this.tag, -// this.dispose, -// this.didChangeDependencies, -// this.didUpdateWidget, -// }) : assert(builder != null), -// super(key: key); -// -// @override -// _StateBuilderState createState() => _StateBuilderState(); -//} -// -//class _StateBuilderState extends State> { -// T controller; -// -// bool isCreator = false; -// -// @override -// void initState() { -// super.initState(); -// if (widget.initState != null) widget.initState(this); -// if (widget.global) { -// final isPrepared = GetInstance().isPrepared(tag: widget.tag); -// final isRegistred = GetInstance().isRegistred(tag: widget.tag); -// -// if (isPrepared) { -// isCreator = true; -// } else if (isRegistred) { -// isCreator = false; -// } else { -// isCreator = true; -// } -// -// if (isCreator) { -// controller?.onStart(); -// } -// -// final instance = GetInstance().putOrFind( -// widget.state, -// tag: widget.tag, -// ); -// controller = instance; -// controller._updaters.add(setState); -// } else { -// controller = widget.state(); -// isCreator = true; -// controller._updaters.add(setState); -// controller?.onStart(); -// } -// } -// -// @override -// void dispose() { -// super.dispose(); -// if (widget.dispose != null) widget.dispose(this); -// if (isCreator || widget.assignId) { -// if (widget.autoRemove && -// GetInstance().isRegistred( -// tag: widget.tag, -// )) { -// controller._updaters.remove(setState); -// GetInstance().delete(tag: widget.tag); -// } -// } else { -// controller._updaters.remove(setState); -// } -// } -// -// @override -// void didChangeDependencies() { -// super.didChangeDependencies(); -// if (widget.didChangeDependencies != null) { -// widget.didChangeDependencies(this); -// } -// } -// -// @override -// void didUpdateWidget(StateBuilder oldWidget) { -// super.didUpdateWidget(oldWidget as StateBuilder); -// if (widget.didUpdateWidget != null) { -// widget.didUpdateWidget(oldWidget, this); -// } -// } -// -// @override -// Widget build(BuildContext context) { -// return widget.builder(controller.state); -// } -//} diff --git a/packages/get_state_manager/lib/src/simple/mixin_state.dart b/packages/get_state_manager/lib/src/simple/mixin_state.dart deleted file mode 100644 index f886468da..000000000 --- a/packages/get_state_manager/lib/src/simple/mixin_state.dart +++ /dev/null @@ -1,42 +0,0 @@ -import 'package:flutter/material.dart'; -import '../../get_state_manager.dart'; -import 'get_state.dart'; - -class MixinBuilder extends StatelessWidget { - @required - final Widget Function(T) builder; - final bool global; - final String id; - final bool autoRemove; - final void Function(State state) initState, dispose, didChangeDependencies; - final void Function(GetBuilder oldWidget, State state) didUpdateWidget; - final T init; - - const MixinBuilder({ - Key key, - this.init, - this.global = true, - this.builder, - this.autoRemove = true, - this.initState, - this.dispose, - this.id, - this.didChangeDependencies, - this.didUpdateWidget, - }) : assert(builder != null), - super(key: key); - - @override - Widget build(BuildContext context) { - return GetBuilder( - init: init, - global: global, - autoRemove: autoRemove, - initState: initState, - dispose: dispose, - id: id, - didChangeDependencies: didChangeDependencies, - didUpdateWidget: didUpdateWidget, - builder: (controller) => Obx(() => builder.call(controller))); - } -} diff --git a/packages/get_state_manager/lib/src/simple/simple_builder.dart b/packages/get_state_manager/lib/src/simple/simple_builder.dart deleted file mode 100644 index 1a375df14..000000000 --- a/packages/get_state_manager/lib/src/simple/simple_builder.dart +++ /dev/null @@ -1,148 +0,0 @@ -import 'dart:async'; -import 'dart:collection'; -import 'package:flutter/widgets.dart'; -import 'get_state.dart'; - -typedef ValueBuilderUpdateCallback = void Function(T snapshot); -typedef ValueBuilderBuilder = Widget Function( - T snapshot, ValueBuilderUpdateCallback updater); - -/// Manages a local state like ObxValue, but uses a callback instead of -/// a Rx value. -/// -/// Example: -/// ``` -/// ValueBuilder( -/// initialValue: false, -/// builder: (value, update) => Switch( -/// value: value, -/// onChanged: (flag) { -/// update( flag ); -/// },), -/// onUpdate: (value) => print("Value updated: $value"), -/// ), -/// ``` -class ValueBuilder extends StatefulWidget { - final T initialValue; - final ValueBuilderBuilder builder; - final void Function() onDispose; - final void Function(T) onUpdate; - - const ValueBuilder({ - Key key, - this.initialValue, - this.onDispose, - this.onUpdate, - @required this.builder, - }) : super(key: key); - - @override - _ValueBuilderState createState() => _ValueBuilderState(); -} - -class _ValueBuilderState extends State> { - T value; - - @override - void initState() { - super.initState(); - value = widget.initialValue; - } - - @override - Widget build(BuildContext context) => widget.builder(value, updater); - - void updater(T newValue) { - if (widget.onUpdate != null) { - widget.onUpdate(newValue); - } - setState(() { - value = newValue; - }); - } - - @override - void dispose() { - super.dispose(); - widget?.onDispose?.call(); - if (value is ChangeNotifier) { - (value as ChangeNotifier)?.dispose(); - } else if (value is StreamController) { - (value as StreamController)?.close(); - } - value = null; - } -} - -// It's a experimental feature -class SimpleBuilder extends StatefulWidget { - final Widget Function(BuildContext) builder; - - const SimpleBuilder({Key key, @required this.builder}) - : assert(builder != null), - super(key: key); - - @override - _SimpleBuilderState createState() => _SimpleBuilderState(); -} - -class _SimpleBuilderState extends State - with GetStateUpdaterMixin { - final HashSet disposers = HashSet(); - - @override - void dispose() { - super.dispose(); - for (final disposer in disposers) { - disposer(); - } - } - - @override - Widget build(BuildContext context) { - return TaskManager.instance.exchange( - disposers, - getUpdate, - widget.builder, - context, - ); - } -} - -class TaskManager { - TaskManager._(); - - static TaskManager _instance; - - static TaskManager get instance => _instance ??= TaskManager._(); - -// StateSetter _setter;// - GetStateUpdate _setter; - - HashSet _remove; - -// void notify(HashSet _updaters) { // - void notify(HashSet _updaters) { - if (_setter != null) { - if (!_updaters.contains(_setter)) { - _updaters.add(_setter); - _remove.add(() => _updaters.remove(_setter)); - } - } - } - - Widget exchange( - HashSet disposers, -// StateSetter setState, // - GetStateUpdate setState, - Widget Function(BuildContext) builder, - BuildContext context, - ) { - _remove = disposers; - _setter = setState; - final result = builder(context); - _remove = null; - _setter = null; - return result; - } -} diff --git a/packages/get_state_manager/pubspec.yaml b/packages/get_state_manager/pubspec.yaml deleted file mode 100644 index 3b1a5fe5d..000000000 --- a/packages/get_state_manager/pubspec.yaml +++ /dev/null @@ -1,56 +0,0 @@ -name: get_state_manager -description: The most powerful, easier and flexible StateManager to Flutter and GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - flutter: ">=1.17.0 <2.0.0" - -dependencies: - flutter: - sdk: flutter - get_rx: ">=3.13.0 <4.0.0" - get_instance: ">=3.13.0 <4.0.0" - get_core: ">=3.13.0 <4.0.0" - -dev_dependencies: - flutter_test: - sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_state_manager/test/get_mixin_state_test.dart b/packages/get_state_manager/test/get_mixin_state_test.dart deleted file mode 100644 index 017e140ce..000000000 --- a/packages/get_state_manager/test/get_mixin_state_test.dart +++ /dev/null @@ -1,101 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import 'package:get_state_manager/get_state_manager.dart'; - -void main() { - testWidgets("MixinBuilder smoke test", (tester) async { - await tester.pumpWidget( - MaterialApp( - home: MixinBuilder( - init: Controller(), - builder: (controller) { - return Column( - children: [ - Text( - 'Count: ${controller.counter.value}', - ), - Text( - 'Count2: ${controller.count}', - ), - Text( - 'Double: ${controller.doubleNum.value}', - ), - Text( - 'String: ${controller.string.value}', - ), - Text( - 'List: ${controller.list.length}', - ), - Text( - 'Bool: ${controller.boolean.value}', - ), - Text( - 'Map: ${controller.map.length}', - ), - FlatButton( - child: Text("increment"), - onPressed: () => controller.increment(), - ) - ], - ); - }, - ), - ), - ); - - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Count2: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); - - Controller.to.increment(); - - await tester.pump(); - - expect(find.text("Count: 1"), findsOneWidget); - - await tester.tap(find.text('increment')); - - await tester.pump(); - - expect(find.text("Count: 2"), findsOneWidget); - }); - - testWidgets( - "MixinBuilder with build null", - (tester) async { - expect( - () => MixinBuilder( - init: Controller(), - builder: null, - ), - throwsAssertionError, - ); - }, - ); -} - -class Controller extends GetxController { - static Controller get to => Get.find(); - int count = 0; - RxInt counter = 0.obs; - RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; - RxList list = [].obs; - RxMap map = {}.obs; - RxBool boolean = true.obs; - - void increment() { - counter.value++; - } - - void increment2() { - count++; - update(); - } -} diff --git a/packages/get_state_manager/test/get_obx_test.dart b/packages/get_state_manager/test/get_obx_test.dart deleted file mode 100644 index 8826835d1..000000000 --- a/packages/get_state_manager/test/get_obx_test.dart +++ /dev/null @@ -1,69 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import 'package:get_state_manager/get_state_manager.dart'; - -void main() { - final controller = Get.put(Controller()); - testWidgets("GetxController smoke test", (tester) async { - await tester.pumpWidget( - MaterialApp( - home: Column( - children: [ - Obx( - () => Column(children: [ - Text('Count: ${controller.counter.value}'), - Text('Double: ${controller.doubleNum.value}'), - Text('String: ${controller.string.value}'), - Text('List: ${controller.list.length}'), - Text('Bool: ${controller.boolean.value}'), - Text('Map: ${controller.map.length}'), - FlatButton( - child: Text("increment"), - onPressed: controller.increment, - ), - Obx(() => Text('Obx: ${controller.map.length}')) - ]), - ), - ], - ), - ), - ); - - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); - expect(find.text("Obx: 0"), findsOneWidget); - - Controller.to.increment(); - - await tester.pump(); - - expect(find.text("Count: 1"), findsOneWidget); - - await tester.tap(find.text('increment')); - - await tester.pump(); - - expect(find.text("Count: 2"), findsOneWidget); - }); -} - -class Controller extends GetxController { - static Controller get to => Get.find(); - - RxInt counter = 0.obs; - RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; - RxList list = [].obs; - RxMap map = {}.obs; - RxBool boolean = true.obs; - - void increment() { - counter.value++; - } -} diff --git a/packages/get_state_manager/test/get_rxstate_test.dart b/packages/get_state_manager/test/get_rxstate_test.dart deleted file mode 100644 index 96c695e91..000000000 --- a/packages/get_state_manager/test/get_rxstate_test.dart +++ /dev/null @@ -1,99 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import 'package:get_state_manager/get_state_manager.dart'; - -void main() { - Get.lazyPut(() => Controller2()); - testWidgets("GetxController smoke test", (tester) async { - await tester.pumpWidget( - MaterialApp( - home: GetX( - init: Controller(), - builder: (controller) { - return Column( - children: [ - Text( - 'Count: ${controller.counter.value}', - ), - Text( - 'Double: ${controller.doubleNum.value}', - ), - Text( - 'String: ${controller.string.value}', - ), - Text( - 'List: ${controller.list.length}', - ), - Text( - 'Bool: ${controller.boolean.value}', - ), - Text( - 'Map: ${controller.map.length}', - ), - FlatButton( - child: Text("increment"), - onPressed: () => controller.increment(), - ), - GetX(builder: (controller) { - return Text('lazy ${controller.lazy.value}'); - }), - GetX( - init: ControllerNonGlobal(), - global: false, - builder: (controller) { - return Text('single ${controller.nonGlobal.value}'); - }) - ], - ); - }, - ), - ), - ); - - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); - - Controller.to.increment(); - - await tester.pump(); - - expect(find.text("Count: 1"), findsOneWidget); - - await tester.tap(find.text('increment')); - - await tester.pump(); - - expect(find.text("Count: 2"), findsOneWidget); - expect(find.text("lazy 0"), findsOneWidget); - expect(find.text("single 0"), findsOneWidget); - }); -} - -class Controller2 extends GetxController { - RxInt lazy = 0.obs; -} - -class ControllerNonGlobal extends GetxController { - RxInt nonGlobal = 0.obs; -} - -class Controller extends GetxController { - static Controller get to => Get.find(); - - RxInt counter = 0.obs; - RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; - RxList list = [].obs; - RxMap map = {}.obs; - RxBool boolean = true.obs; - - void increment() { - counter.value++; - } -} diff --git a/packages/get_state_manager/test/get_state_test.dart b/packages/get_state_manager/test/get_state_test.dart deleted file mode 100644 index c144187d2..000000000 --- a/packages/get_state_manager/test/get_state_test.dart +++ /dev/null @@ -1,109 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_core/get_core.dart'; -import 'package:get_instance/get_instance.dart'; -import 'package:get_state_manager/get_state_manager.dart'; - -void main() { - Get.lazyPut(() => Controller2()); - testWidgets("GetxController smoke test", (test) async { - await test.pumpWidget( - MaterialApp( - home: GetBuilder( - init: Controller(), - builder: (controller) => Column( - children: [ - Text( - '${controller.counter}', - ), - FlatButton( - child: Text("increment"), - onPressed: () => controller.increment(), - ), - FlatButton( - child: Text("incrementWithId"), - onPressed: () => controller.incrementWithId(), - ), - GetBuilder( - id: '1', - didChangeDependencies: (_) { - // print("didChangeDependencies called"); - }, - builder: (controller) { - return Text('id ${controller.counter}'); - }), - GetBuilder(builder: (controller) { - return Text('lazy ${controller.test}'); - }), - GetBuilder( - init: ControllerNonGlobal(), - global: false, - builder: (controller) { - return Text('single ${controller.nonGlobal}'); - }) - ], - ), - ), - ), - ); - - expect(find.text("0"), findsOneWidget); - - Controller.to.increment(); - - await test.pump(); - - expect(find.text("1"), findsOneWidget); - - await test.tap(find.text('increment')); - - await test.pump(); - - expect(find.text("2"), findsOneWidget); - - await test.tap(find.text('incrementWithId')); - - await test.pump(); - - expect(find.text("id 3"), findsOneWidget); - expect(find.text("lazy 0"), findsOneWidget); - expect(find.text("single 0"), findsOneWidget); - }); - - testWidgets( - "MixinBuilder with build null", - (test) async { - expect( - () => GetBuilder( - init: Controller(), - builder: null, - ), - throwsAssertionError, - ); - }, - ); -} - -class Controller extends GetxController { - static Controller get to => Get.find(); - - int counter = 0; - - void increment() { - counter++; - update(); - } - - void incrementWithId() { - counter++; - update(['1']); - } -} - -class Controller2 extends GetxController { - int test = 0; -} - -class ControllerNonGlobal extends GetxController { - int nonGlobal = 0; -} diff --git a/packages/get_test/.gitignore b/packages/get_test/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_test/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_test/.metadata b/packages/get_test/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_test/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_test/CHANGELOG.md b/packages/get_test/CHANGELOG.md deleted file mode 100644 index d66abd29c..000000000 --- a/packages/get_test/CHANGELOG.md +++ /dev/null @@ -1,14 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.3] -* Added compatibility with last GetX - -## [3.12.0] -* Bump to Get 3.12.0 - -## [3.11.0] -- Compatibility with get 3.11.0 - -## [3.10.2] -- Initial release diff --git a/packages/get_test/LICENSE b/packages/get_test/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_test/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_test/README.md b/packages/get_test/README.md deleted file mode 100644 index a40c4d8de..000000000 --- a/packages/get_test/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_test - -A new Flutter package. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_test/analysis_options.yaml b/packages/get_test/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_test/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_test/example/.gitignore b/packages/get_test/example/.gitignore deleted file mode 100644 index 9d532b18a..000000000 --- a/packages/get_test/example/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -**/ios/Flutter/.last_build_id -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -/build/ - -# Web related -lib/generated_plugin_registrant.dart - -# Symbolication related -app.*.symbols - -# Obfuscation related -app.*.map.json diff --git a/packages/get_test/example/.metadata b/packages/get_test/example/.metadata deleted file mode 100644 index 37ddd46ac..000000000 --- a/packages/get_test/example/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: app diff --git a/packages/get_test/example/README.md b/packages/get_test/example/README.md deleted file mode 100644 index a13562602..000000000 --- a/packages/get_test/example/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# example - -A new Flutter project. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_test/example/lib/main.dart b/packages/get_test/example/lib/main.dart deleted file mode 100644 index 9a7952a5e..000000000 --- a/packages/get_test/example/lib/main.dart +++ /dev/null @@ -1,102 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get/get.dart'; -import 'package:get_test/get_test.dart'; - -void main() { - getTest( - "test description", - widgetTest: (tester) async { - expect('/', Get.currentRoute); - - Get.to(Container()); - expect('/Container', Get.currentRoute); - - Get.to(Scaffold()); - expect('/Scaffold', Get.currentRoute); - - Get.back(); - - expect('/Container', Get.currentRoute); - }, - ); - - testGetX( - 'GetX test', - widget: GetX( - init: Controller(), - builder: (controller) { - return Text("ban:${controller.count}"); - }, - ), - test: (e) { - expect(find.text("ban:0"), findsOneWidget); - expect(e.count.value, 0); - }, - ); - - testGetBuilder( - 'GetBuilder test', - widget: GetBuilder( - init: Controller(), - builder: (controller) { - return Text("ban:${controller.count}"); - }, - ), - test: (e) { - expect(find.text("ban:0"), findsOneWidget); - expect(e.count.value, 0); - }, - ); - - testObx( - 'Obx test', - widget: (controller) => Obx( - () => Text("ban:${controller.count}"), - ), - controller: Controller(), - test: (e) { - expect(find.text("ban:0"), findsOneWidget); - expect(e.count.value, 0); - }, - ); - - testController( - 'Controller test', - (controller) {}, - controller: Controller(), - onInit: (c) { - c.increment(); - print('onInit'); - }, - onReady: (c) { - print('onReady'); - c.increment(); - }, - onClose: (c) { - print('onClose'); - }, - ); -} - -class Controller extends GetxController { - final count = 0.obs; - void increment() => count.value++; - - @override - void onInit() { - print('inittt'); - super.onInit(); - } - - @override - void onReady() { - print('onReady'); - super.onReady(); - } - - void onClose() { - print('onClose'); - } -} diff --git a/packages/get_test/example/pubspec.yaml b/packages/get_test/example/pubspec.yaml deleted file mode 100644 index 61c5c6b76..000000000 --- a/packages/get_test/example/pubspec.yaml +++ /dev/null @@ -1,81 +0,0 @@ -name: example -description: A new Flutter project. - -# The following line prevents the package from being accidentally published to -# pub.dev using `pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -# The following defines the version and build number for your application. -# A version number is three numbers separated by dots, like 1.2.43 -# followed by an optional build number separated by a +. -# Both the version and the builder number may be overridden in flutter -# build by specifying --build-name and --build-number, respectively. -# In Android, build-name is used as versionName while build-number used as versionCode. -# Read more about Android versioning at https://developer.android.com/studio/publish/versioning -# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 1.0.0+1 - -environment: - sdk: ">=2.7.0 <3.0.0" - -dependencies: - flutter: - sdk: flutter - get: - git: - url: git://github.com/jonataslaw/getx.git - path: getx - ref: master - - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.0 - -dev_dependencies: - flutter_test: - sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_test/lib/get_test.dart b/packages/get_test/lib/get_test.dart deleted file mode 100644 index 3015029c7..000000000 --- a/packages/get_test/lib/get_test.dart +++ /dev/null @@ -1,142 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_navigation/get_navigation.dart'; -import 'package:get_state_manager/get_state_manager.dart'; -import 'package:meta/meta.dart'; -import 'utils/image_test.dart' - if (dart.library.io) 'utils/image_test_utils.dart'; - -class _Wrapper extends StatelessWidget { - final Widget child; - final List getPages; - final String initialRoute; - - const _Wrapper({ - Key key, - this.child = const Scaffold(), - this.getPages, - this.initialRoute, - }) : super(key: key); - - @override - Widget build(BuildContext context) { - return GetMaterialApp( - initialRoute: initialRoute, - getPages: getPages ?? [GetPage(name: '/', page: () => child)], - ); - } -} - -@isTest -void testController( - String description, - void Function(T) callback, { - @required T controller, - void Function(T) onInit, - void Function(T) onReady, - void Function(T) onClose, -}) { - test(description, () { - onInit(controller); - SchedulerBinding.instance.addPostFrameCallback((f) { - onReady(controller); - }); - callback(controller); - onClose(controller); - }); -} - -@isTest -Future testGetX( - String description, { - @required GetX widget, - @required void Function(T controller) test, -}) async { - T controller; - testWidgets(description, (tester) async { - provideMockedNetworkImages(() async { - await tester.pumpWidget(GetMaterialApp(home: widget)); - final controller = Get.find(); - test(controller); - }); - }); - return controller; -} - -@isTest -Future testGetBuilder( - String description, { - @required GetBuilder widget, - @required void Function(T controller) test, -}) async { - T controller; - testWidgets(description, (tester) async { - provideMockedNetworkImages(() async { - await tester.pumpWidget(GetMaterialApp(home: widget)); - final controller = Get.find(); - test(controller); - }); - }); - return controller; -} - -@isTest -Future testObx( - String description, { - @required T controller, - @required Obx Function(T controller) widget, - @required void Function(T controller) test, -}) async { - testWidgets(description, (tester) async { - provideMockedNetworkImages(() async { - await tester.pumpWidget(GetMaterialApp(home: widget(controller))); - test(controller); - }); - }); - return controller; -} - -@isTest -void getTest( - String description, { - @required WidgetTesterCallback widgetTest, - Widget wrapper, - List getPages, - String initialRoute = '/', - bool skip = false, - Timeout timeout, - Duration initialTimeout, - bool semanticsEnabled = true, - TestVariant variant = const DefaultTestVariant(), - dynamic tags, -}) { - assert(variant != null); - assert(variant.values.isNotEmpty); - - if (wrapper == null) { - if (getPages != null) { - wrapper = _Wrapper(getPages: getPages, initialRoute: initialRoute); - } else if (initialRoute != null && getPages != null) { - wrapper = _Wrapper(initialRoute: initialRoute, getPages: getPages); - } else { - wrapper = _Wrapper(); - } - } - - testWidgets( - description, - (tester) async { - provideMockedNetworkImages(() async { - await tester.pumpWidget(wrapper); - widgetTest(tester); - }); - }, - skip: skip, - timeout: timeout, - initialTimeout: initialTimeout, - semanticsEnabled: semanticsEnabled, - variant: variant, - tags: tags, - ); -} diff --git a/packages/get_test/lib/utils/image_test.dart b/packages/get_test/lib/utils/image_test.dart deleted file mode 100644 index d954b405f..000000000 --- a/packages/get_test/lib/utils/image_test.dart +++ /dev/null @@ -1,3 +0,0 @@ -R provideMockedNetworkImages(R body()) { - return body(); -} diff --git a/packages/get_test/lib/utils/image_test_utils.dart b/packages/get_test/lib/utils/image_test_utils.dart deleted file mode 100644 index 339f52c54..000000000 --- a/packages/get_test/lib/utils/image_test_utils.dart +++ /dev/null @@ -1,181 +0,0 @@ -import 'dart:async'; -import 'dart:io'; -import 'package:mockito/mockito.dart'; - -/// Copyright 2018 Iiro Krankka -/// Redistribution and use in source and binary forms, with or without -/// modification, are permitted provided that the following conditions are met: -/// 1. Redistributions of source code must retain the above copyright notice, -/// this list of conditions and the following disclaimer. -/// 2. Redistributions in binary form must reproduce the above copyright -/// notice, this list of conditions and the following disclaimer in the -/// documentation and/or other materials provided with the distribution. -/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -/// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -/// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -/// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -/// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -/// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, -/// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -/// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -/// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/// Runs [body] in a fresh [Zone] that provides mocked responses for -/// [Image.network] widgets. -/// -/// Behind the scenes, this creates a mocked HTTP client that responds -/// with mocked -/// image data to all HTTP GET requests. -/// -/// This is a workaround needed for widget tests that use network images. -/// Without -/// the mocked HTTP client, any widget tests that pump a widget tree containing -/// [Image.network] widgets will crash. -/// -/// By default, the mocked HTTP client will respond with [_transparentImage]. If -/// provided, it will use [imageBytes] instead. -/// -/// Example usage in a test case: -/// -/// ``` -/// void main() { -/// testWidgets('should not crash', (WidgetTester tester) async { -/// provideMockedNetworkImages(() async { -/// await tester.pumpWidget( -/// MaterialApp( -/// home: Image.network('https://example.com/image.png'), -/// ), -/// ); -/// }); -/// }); -/// } -/// ``` -/// -/// Note that you'll want to add this package to the dev_dependencies instead of -/// the regular dependencies block on your pubspec.yaml. -/// -/// For more context about [Image.network] widgets failing in widget tests, see -/// these issues: -/// -/// * https://github.com/flutter/flutter/issues/13433 -/// * https://github.com/flutter/flutter_markdown/pull/17 -/// -/// The underlying code is taken from the Flutter repo: -/// https://github.com/flutter/flutter/blob/master/dev/manual_tests/test/mock_image_http.dart -R provideMockedNetworkImages(R body(), - {List imageBytes = _transparentImage}) { - return HttpOverrides.runZoned( - body, - createHttpClient: (_) => _createMockImageHttpClient(_, imageBytes), - ); -} - -class MockHttpClient extends Mock implements HttpClient {} - -class MockHttpClientRequest extends Mock implements HttpClientRequest {} - -class MockHttpClientResponse extends Mock implements HttpClientResponse {} - -class MockHttpHeaders extends Mock implements HttpHeaders {} - -// Returns a mock HTTP client that responds with an image to all requests. -MockHttpClient _createMockImageHttpClient( - SecurityContext _, List imageBytes) { - final client = MockHttpClient(); - final request = MockHttpClientRequest(); - final response = MockHttpClientResponse(); - final headers = MockHttpHeaders(); - - when(client.getUrl(any)) - .thenAnswer((_) => Future.value(request)); - when(request.headers).thenReturn(headers); - when(request.close()) - .thenAnswer((_) => Future.value(response)); - when(response.contentLength).thenReturn(_transparentImage.length); - when(response.statusCode).thenReturn(HttpStatus.ok); - when(response.listen(any)).thenAnswer((invocation) { - final onData = - invocation.positionalArguments[0] as void Function(List); - final onDone = invocation.namedArguments[#onDone] as void Function(); - final onError = invocation.namedArguments[#onError] as void Function(Object, - [StackTrace]); - final cancelOnError = invocation.namedArguments[#cancelOnError] as bool; - - return Stream>.fromIterable(>[imageBytes]).listen( - onData, - onDone: onDone, - onError: onError, - cancelOnError: cancelOnError); - }); - - return client; -} - -const List _transparentImage = [ - 0x89, - 0x50, - 0x4E, - 0x47, - 0x0D, - 0x0A, - 0x1A, - 0x0A, - 0x00, - 0x00, - 0x00, - 0x0D, - 0x49, - 0x48, - 0x44, - 0x52, - 0x00, - 0x00, - 0x00, - 0x01, - 0x00, - 0x00, - 0x00, - 0x01, - 0x08, - 0x06, - 0x00, - 0x00, - 0x00, - 0x1F, - 0x15, - 0xC4, - 0x89, - 0x00, - 0x00, - 0x00, - 0x0A, - 0x49, - 0x44, - 0x41, - 0x54, - 0x78, - 0x9C, - 0x63, - 0x00, - 0x01, - 0x00, - 0x00, - 0x05, - 0x00, - 0x01, - 0x0D, - 0x0A, - 0x2D, - 0xB4, - 0x00, - 0x00, - 0x00, - 0x00, - 0x49, - 0x45, - 0x4E, - 0x44, - 0xAE, -]; diff --git a/packages/get_test/pubspec.yaml b/packages/get_test/pubspec.yaml deleted file mode 100644 index d8c74b696..000000000 --- a/packages/get_test/pubspec.yaml +++ /dev/null @@ -1,57 +0,0 @@ -name: get_test -description: A package that facilitates the creation of tests for applications built with GetX -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - flutter: ">=1.17.0 <2.0.0" - -dependencies: - flutter: - sdk: flutter - mockito: ">=3.0.0 <5.0.0" - get_navigation: ">=3.13.0 <4.0.0" - get_state_manager: ">=3.13.0 <4.0.0" - meta: ">=1.1.0 <2.0.0" - flutter_test: - sdk: flutter - - - - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - - - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_utils/.gitignore b/packages/get_utils/.gitignore deleted file mode 100644 index 1985397a2..000000000 --- a/packages/get_utils/.gitignore +++ /dev/null @@ -1,74 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -build/ - -# Android related -**/android/**/gradle-wrapper.jar -**/android/.gradle -**/android/captures/ -**/android/gradlew -**/android/gradlew.bat -**/android/local.properties -**/android/**/GeneratedPluginRegistrant.java - -# iOS/XCode related -**/ios/**/*.mode1v3 -**/ios/**/*.mode2v3 -**/ios/**/*.moved-aside -**/ios/**/*.pbxuser -**/ios/**/*.perspectivev3 -**/ios/**/*sync/ -**/ios/**/.sconsign.dblite -**/ios/**/.tags* -**/ios/**/.vagrant/ -**/ios/**/DerivedData/ -**/ios/**/Icon? -**/ios/**/Pods/ -**/ios/**/.symlinks/ -**/ios/**/profile -**/ios/**/xcuserdata -**/ios/.generated/ -**/ios/Flutter/App.framework -**/ios/Flutter/Flutter.framework -**/ios/Flutter/Flutter.podspec -**/ios/Flutter/Generated.xcconfig -**/ios/Flutter/app.flx -**/ios/Flutter/app.zip -**/ios/Flutter/flutter_assets/ -**/ios/Flutter/flutter_export_environment.sh -**/ios/ServiceDefinitions.json -**/ios/Runner/GeneratedPluginRegistrant.* - -# Exceptions to above rules. -!**/ios/**/default.mode1v3 -!**/ios/**/default.mode2v3 -!**/ios/**/default.pbxuser -!**/ios/**/default.perspectivev3 diff --git a/packages/get_utils/.metadata b/packages/get_utils/.metadata deleted file mode 100644 index 3207f67d3..000000000 --- a/packages/get_utils/.metadata +++ /dev/null @@ -1,10 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled and should not be manually edited. - -version: - revision: a27c242b0eea731317cfec5bbdd9d35452ab3ecb - channel: dev - -project_type: package diff --git a/packages/get_utils/CHANGELOG.md b/packages/get_utils/CHANGELOG.md deleted file mode 100644 index 344af7595..000000000 --- a/packages/get_utils/CHANGELOG.md +++ /dev/null @@ -1,11 +0,0 @@ -## [3.13.0] -* Bump to Get 3.13.0 - -## [3.12.0] -* Bump to Get 3.12.0 -* Improve capitalizeFirst method - - -## [3.10.2] - -- Initial release diff --git a/packages/get_utils/LICENSE b/packages/get_utils/LICENSE deleted file mode 100644 index 2fb920baf..000000000 --- a/packages/get_utils/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Jonny Borges - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/packages/get_utils/README.md b/packages/get_utils/README.md deleted file mode 100644 index 3bfa62407..000000000 --- a/packages/get_utils/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# get_utils - -A new Flutter package project. - -## Getting Started - -This project is a starting point for a Dart -[package](https://flutter.dev/developing-packages/), -a library module containing code that can be shared easily across -multiple Flutter or Dart projects. - -For help getting started with Flutter, view our -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/get_utils/analysis_options.yaml b/packages/get_utils/analysis_options.yaml deleted file mode 100644 index 38018b421..000000000 --- a/packages/get_utils/analysis_options.yaml +++ /dev/null @@ -1,85 +0,0 @@ -# Include option is buggy: -# https://github.com/flutter/flutter/issues/62591 -# In case the include issue gets fixed, lines below INCLUDE_FIX -# can be removed - -# include: package:effective_dart/analysis_options.1.2.0.yaml -analyzer: - strong-mode: - implicit-casts: false -linter: - rules: - await_only_futures: true - # This one is desirable, but that's a lot of work for now - public_member_api_docs: false - # Desirable, but would be breaking changes: - avoid_positional_boolean_parameters: false - constant_identifier_names: false - include_file_not_found: false - - # INCLUDE_FIX (copy of effective dart 1.2.0) - # STYLE - camel_case_types: true - camel_case_extensions: true - library_names: true - file_names: true - library_prefixes: true - non_constant_identifier_names: true - directives_ordering: true - lines_longer_than_80_chars: true # avoid - curly_braces_in_flow_control_structures: true - - # DOCUMENTATION - slash_for_doc_comments: true - package_api_docs: true # prefer - #- comment_references # Unused because https://github.com/dart-lang/sdk/issues/36974 - - # USAGE - implementation_imports: true - avoid_relative_lib_imports: true # prefer - prefer_relative_imports: true # prefer - prefer_adjacent_string_concatenation: true - prefer_interpolation_to_compose_strings: true # prefer - unnecessary_brace_in_string_interps: true # avoid - prefer_collection_literals: true - avoid_function_literals_in_foreach_calls: true # avoid - prefer_iterable_whereType: true - prefer_function_declarations_over_variables: true - unnecessary_lambdas: true - prefer_equal_for_default_values: true - avoid_init_to_null: true - unnecessary_getters_setters: true - #- unnecessary_getters # prefer # Disabled pending fix: https://github.com/dart-lang/linter/issues/23 - #- prefer_expression_function_bodies # consider - unnecessary_this: true - prefer_initializing_formals: true - type_init_formals: true - empty_constructor_bodies: true - unnecessary_new: true - unnecessary_const: true - avoid_catches_without_on_clauses: true # avoid - avoid_catching_errors: true - use_rethrow_when_possible: true - - # DESIGN - use_to_and_as_if_applicable: true # prefer - one_member_abstracts: true # avoid - avoid_classes_with_only_static_members: true # avoid - prefer_mixin: true - prefer_final_fields: true # prefer - use_setters_to_change_properties: true - avoid_setters_without_getters: true - avoid_returning_null: true # avoid - avoid_returning_this: true # avoid - type_annotate_public_apis: true # prefer - #- prefer_typing_uninitialized_variables # consider - omit_local_variable_types: true # avoid - avoid_types_on_closure_parameters: true # avoid - avoid_return_types_on_setters: true # avoid - prefer_generic_function_type_aliases: true - avoid_private_typedef_functions: true # prefer - #- use_function_type_syntax_for_parameters # consider - hash_and_equals: true - avoid_equals_and_hash_code_on_mutable_classes: true # avoid - avoid_null_checks_in_equality_operators: true - diff --git a/packages/get_utils/lib/get_utils.dart b/packages/get_utils/lib/get_utils.dart deleted file mode 100644 index 15bc8f876..000000000 --- a/packages/get_utils/lib/get_utils.dart +++ /dev/null @@ -1,4 +0,0 @@ -export 'src/extensions/export.dart'; -export 'src/get_utils/get_utils.dart'; -export 'src/platform/platform.dart'; -export 'src/queue/get_queue.dart'; diff --git a/packages/get_utils/lib/src/extensions/context_extensions.dart b/packages/get_utils/lib/src/extensions/context_extensions.dart deleted file mode 100644 index 3762d22eb..000000000 --- a/packages/get_utils/lib/src/extensions/context_extensions.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; - -import '../platform/platform.dart'; - -extension ContextExtensionss on BuildContext { - /// The same of [MediaQuery.of(context).size] - Size get mediaQuerySize => MediaQuery.of(this).size; - - /// The same of [MediaQuery.of(context).size.height] - /// Note: updates when you rezise your screen (like on a browser or - /// desktop window) - double get height => mediaQuerySize.height; - - /// The same of [MediaQuery.of(context).size.width] - /// Note: updates when you rezise your screen (like on a browser or - /// desktop window) - double get width => mediaQuerySize.width; - - /// Gives you the power to get a portion of the height. - /// Useful for responsive applications. - /// - /// [dividedBy] is for when you want to have a portion of the value you - /// would get like for example: if you want a value that represents a third - /// of the screen you can set it to 3, and you will get a third of the height - /// - /// [reducedBy] is a percentage value of how much of the height you want - /// if you for example want 46% of the height, then you reduce it by 56%. - double heightTransformer({double dividedBy = 1, double reducedBy = 0.0}) { - return (mediaQuerySize.height - - ((mediaQuerySize.height / 100) * reducedBy)) / - dividedBy; - } - - /// Gives you the power to get a portion of the width. - /// Useful for responsive applications. - /// - /// [dividedBy] is for when you want to have a portion of the value you - /// would get like for example: if you want a value that represents a third - /// of the screen you can set it to 3, and you will get a third of the width - /// - /// [reducedBy] is a percentage value of how much of the width you want - /// if you for example want 46% of the width, then you reduce it by 56%. - double widthTransformer({double dividedBy = 1, double reducedBy = 0.0}) { - return (mediaQuerySize.width - ((mediaQuerySize.width / 100) * reducedBy)) / - dividedBy; - } - - /// Divide the height proportionally by the given value - double ratio({ - double dividedBy = 1, - double reducedByW = 0.0, - double reducedByH = 0.0, - }) { - return heightTransformer(dividedBy: dividedBy, reducedBy: reducedByH) / - widthTransformer(dividedBy: dividedBy, reducedBy: reducedByW); - } - - /// similar to [MediaQuery.of(context).padding] - ThemeData get theme => Theme.of(this); - - /// similar to [MediaQuery.of(context).padding] - TextTheme get textTheme => Theme.of(this).textTheme; - - /// similar to [MediaQuery.of(context).padding] - EdgeInsets get mediaQueryPadding => MediaQuery.of(this).padding; - - /// similar to [MediaQuery.of(context).padding] - MediaQueryData get mediaQuery => MediaQuery.of(this); - - /// similar to [MediaQuery.of(context).viewPadding] - EdgeInsets get mediaQueryViewPadding => MediaQuery.of(this).viewPadding; - - /// similar to [MediaQuery.of(context).viewInsets] - EdgeInsets get mediaQueryViewInsets => MediaQuery.of(this).viewInsets; - - /// similar to [MediaQuery.of(context).orientation] - Orientation get orientation => MediaQuery.of(this).orientation; - - /// check if device is on landscape mode - bool get isLandscape => orientation == Orientation.landscape; - - /// check if device is on portrait mode - bool get isPortrait => orientation == Orientation.portrait; - - /// similar to [MediaQuery.of(this).devicePixelRatio] - double get devicePixelRatio => MediaQuery.of(this).devicePixelRatio; - - /// similar to [MediaQuery.of(this).textScaleFactor] - double get textScaleFactor => MediaQuery.of(this).textScaleFactor; - - /// get the shortestSide from screen - double get mediaQueryShortestSide => mediaQuerySize.shortestSide; - - /// True if width be larger than 800 - bool get showNavbar => (width > 800); - - /// True if the shortestSide is smaller than 600p - bool get isPhone => (mediaQueryShortestSide < 600); - - /// True if the shortestSide is largest than 600p - bool get isSmallTablet => (mediaQueryShortestSide >= 600); - - /// True if the shortestSide is largest than 720p - bool get isLargeTablet => (mediaQueryShortestSide >= 720); - - /// True if the current device is Tablet - bool get isTablet => isSmallTablet || isLargeTablet; - - /// Returns a specific value according to the screen size - /// if the device width is higher than or equal to 1200 return - /// [desktop] value. if the device width is higher than or equal to 600 - /// and less than 1200 return [tablet] value. - /// if the device width is less than 300 return [watch] value. - /// in other cases return [mobile] value. - T responsiveValue({ - T mobile, - T tablet, - T desktop, - T watch, - }) { - var deviceWidth = mediaQuerySize.shortestSide; - if (GetPlatform.isDesktop) { - deviceWidth = mediaQuerySize.width; - } - if (deviceWidth >= 1200 && desktop != null) return desktop; - if (deviceWidth >= 600 && tablet != null) return tablet; - if (deviceWidth < 300 && watch != null) return watch; - return mobile; - } -} diff --git a/packages/get_utils/lib/src/extensions/double_extensions.dart b/packages/get_utils/lib/src/extensions/double_extensions.dart deleted file mode 100644 index 03ffa36dd..000000000 --- a/packages/get_utils/lib/src/extensions/double_extensions.dart +++ /dev/null @@ -1,8 +0,0 @@ -import 'dart:math'; - -extension Precision on double { - double toPrecision(int fractionDigits) { - var mod = pow(10, fractionDigits.toDouble()).toDouble(); - return ((this * mod).round().toDouble() / mod); - } -} diff --git a/packages/get_utils/lib/src/extensions/duration_extensions.dart b/packages/get_utils/lib/src/extensions/duration_extensions.dart deleted file mode 100644 index 6af77d305..000000000 --- a/packages/get_utils/lib/src/extensions/duration_extensions.dart +++ /dev/null @@ -1,19 +0,0 @@ -import 'dart:async'; - -/// Duration utilities. -extension GetDurationUtils on Duration { - /// Utility to delay some callback (or code execution). - /// - /// Sample: - /// ``` - /// void main() async { - /// final _delay = 3.seconds; - /// print('+ wait $_delay'); - /// await _delay.delay(); - /// print('- finish wait $_delay'); - /// print('+ callback in 700ms'); - /// await 0.7.seconds.delay(() { - /// } - ///``` - Future delay([FutureOr callback()]) async => Future.delayed(this, callback); -} diff --git a/packages/get_utils/lib/src/extensions/dynamic_extensions.dart b/packages/get_utils/lib/src/extensions/dynamic_extensions.dart deleted file mode 100644 index 7cb9c36d4..000000000 --- a/packages/get_utils/lib/src/extensions/dynamic_extensions.dart +++ /dev/null @@ -1,18 +0,0 @@ -import '../get_utils/get_utils.dart'; - -extension GetDynamicUtils on dynamic { - bool get isNull => GetUtils.isNull(this); - - bool get isNullOrBlank => GetUtils.isNullOrBlank(this); - - void printError( - {String info = '', Function logFunction = GetUtils.printFunction}) => - // ignore: unnecessary_this - logFunction('Error: ${this.runtimeType}', this, info, isError: true); - - void printInfo( - {String info = '', - Function printFunction = GetUtils.printFunction}) => - // ignore: unnecessary_this - printFunction('Info: ${this.runtimeType}', this, info); -} diff --git a/packages/get_utils/lib/src/extensions/export.dart b/packages/get_utils/lib/src/extensions/export.dart deleted file mode 100644 index 536f4ba10..000000000 --- a/packages/get_utils/lib/src/extensions/export.dart +++ /dev/null @@ -1,8 +0,0 @@ -export 'context_extensions.dart'; -export 'double_extensions.dart'; -export 'duration_extensions.dart'; -export 'dynamic_extensions.dart'; -export 'internacionalization.dart'; -export 'num_extensions.dart'; -export 'string_extensions.dart'; -export 'widget_extensions.dart'; diff --git a/packages/get_utils/lib/src/extensions/internacionalization.dart b/packages/get_utils/lib/src/extensions/internacionalization.dart deleted file mode 100644 index 4ee9dc55e..000000000 --- a/packages/get_utils/lib/src/extensions/internacionalization.dart +++ /dev/null @@ -1,88 +0,0 @@ -import 'dart:ui'; -import 'package:get_core/get_core.dart'; - -extension Trans on String { - String get tr { - // Returns the key if locale is null. - if (Get.locale?.languageCode == null) return this; - - // Checks whether the language code and country code are present, and - // whether the key is also present. - if (Get.translations.containsKey( - "${Get.locale.languageCode}_${Get.locale.countryCode}") && - Get.translations["${Get.locale.languageCode}_${Get.locale.countryCode}"] - .containsKey(this)) { - return Get.translations[ - "${Get.locale.languageCode}_${Get.locale.countryCode}"][this]; - - // Checks if there is a callback language in the absence of the specific - // country, and if it contains that key. - } else if (Get.translations.containsKey(Get.locale.languageCode) && - Get.translations[Get.locale.languageCode].containsKey(this)) { - return Get.translations[Get.locale.languageCode][this]; - // If there is no corresponding language or corresponding key, return - // the key. - } else if (Get.fallbackLocale != null) { - final fallback = Get.fallbackLocale; - final key = "${fallback.languageCode}_${fallback.countryCode}"; - - if (Get.translations.containsKey(key) && - Get.translations[key].containsKey(this)) { - return Get.translations[key][this]; - } - if (Get.translations.containsKey(fallback.languageCode) && - Get.translations[fallback.languageCode].containsKey(this)) { - return Get.translations[fallback.languageCode][this]; - } - return this; - } else { - return this; - } - } - - String trArgs([List args]) { - var key = tr; - if (args != null) { - for (final arg in args) { - key = key.replaceFirst(RegExp(r'%s'), arg.toString()); - } - } - return key; - } -} - -class _IntlHost { - Locale locale; - - Locale fallbackLocale; - - Map> translations = {}; -} - -extension LocalesIntl on GetInterface { - static final _intlHost = _IntlHost(); - - Locale get locale => _intlHost.locale; - - Locale get fallbackLocale => _intlHost.fallbackLocale; - - set locale(Locale newLocale) => _intlHost.locale = newLocale; - - set fallbackLocale(Locale newLocale) => _intlHost.fallbackLocale = newLocale; - - Map> get translations => _intlHost.translations; - - void addTranslations(Map> tr) { - translations.addAll(tr); - } - - void appendTranslations(Map> tr) { - tr.forEach((key, map) { - if (translations.containsKey(key)) { - translations[key].addAll(map); - } else { - translations[key] = map; - } - }); - } -} diff --git a/packages/get_utils/lib/src/extensions/num_extensions.dart b/packages/get_utils/lib/src/extensions/num_extensions.dart deleted file mode 100644 index b319a60f4..000000000 --- a/packages/get_utils/lib/src/extensions/num_extensions.dart +++ /dev/null @@ -1,67 +0,0 @@ -import 'dart:async'; -import '../get_utils/get_utils.dart'; - -extension GetNumUtils on num { - bool isLowerThan(num b) => GetUtils.isLowerThan(this, b); - - bool isGreaterThan(num b) => GetUtils.isGreaterThan(this, b); - - bool isEqual(num b) => GetUtils.isEqual(this, b); - - /// Utility to delay some callback (or code execution). - /// TODO: Add a separated implementation of delay() with the ability - /// to stop it. - /// - /// Sample: - /// ``` - /// void main() async { - /// print('+ wait for 2 seconds'); - /// await 2.delay(); - /// print('- 2 seconds completed'); - /// print('+ callback in 1.2sec'); - /// 1.delay(() => print('- 1.2sec callback called')); - /// print('currently running callback 1.2sec'); - /// } - ///``` - Future delay([FutureOr callback()]) async => Future.delayed( - Duration(milliseconds: (this * 1000).round()), - callback, - ); - - /// Easy way to make Durations from numbers. - /// - /// Sample: - /// ``` - /// print(1.seconds + 200.milliseconds); - /// print(1.hours + 30.minutes); - /// print(1.5.hours); - ///``` - Duration get milliseconds => Duration(microseconds: (this * 1000).round()); - - Duration get seconds => Duration(milliseconds: (this * 1000).round()); - - Duration get minutes => - Duration(seconds: (this * Duration.secondsPerMinute).round()); - - Duration get hours => - Duration(minutes: (this * Duration.minutesPerHour).round()); - - Duration get days => Duration(hours: (this * Duration.hoursPerDay).round()); - -//final _delayMaps = {}; -// TODO: create a proper Future and control the Timer. -// Future delay([double seconds = 0, VoidCallback callback]) async { -// final ms = (seconds * 1000).round(); -// return Future.delayed(Duration(milliseconds: ms), callback); -// return _delayMaps[callback]; -// } -//killDelay(VoidCallback callback) { -// if (_delayMaps.containsKey(callback)) { -// _delayMaps[callback]?.timeout(Duration.zero, onTimeout: () { -// print('callbacl eliminado!'); -// }); -// _delayMaps.remove(callback); -// } -//} - -} diff --git a/packages/get_utils/lib/src/extensions/string_extensions.dart b/packages/get_utils/lib/src/extensions/string_extensions.dart deleted file mode 100644 index a9db6f771..000000000 --- a/packages/get_utils/lib/src/extensions/string_extensions.dart +++ /dev/null @@ -1,82 +0,0 @@ -import '../get_utils/get_utils.dart'; - -extension GetStringUtils on String { - bool get isNum => GetUtils.isNum(this); - - bool get isNumericOnly => GetUtils.isNumericOnly(this); - - bool get isAlphabetOnly => GetUtils.isAlphabetOnly(this); - - bool get isBool => GetUtils.isBool(this); - - bool get isVectorFileName => GetUtils.isVector(this); - - bool get isImageFileName => GetUtils.isImage(this); - - bool get isAudioFileName => GetUtils.isAudio(this); - - bool get isVideoFileName => GetUtils.isVideo(this); - - bool get isTxtFileName => GetUtils.isTxt(this); - - bool get isDocumentFileName => GetUtils.isWord(this); - - bool get isExcelFileName => GetUtils.isExcel(this); - - bool get isPPTFileName => GetUtils.isPPT(this); - - bool get isAPKFileName => GetUtils.isAPK(this); - - bool get isPDFFileName => GetUtils.isPDF(this); - - bool get isHTMLFileName => GetUtils.isHTML(this); - - bool get isURL => GetUtils.isURL(this); - - bool get isEmail => GetUtils.isEmail(this); - - bool get isPhoneNumber => GetUtils.isPhoneNumber(this); - - bool get isDateTime => GetUtils.isDateTime(this); - - bool get isMD5 => GetUtils.isMD5(this); - - bool get isSHA1 => GetUtils.isSHA1(this); - - bool get isSHA256 => GetUtils.isSHA256(this); - - bool get isBinary => GetUtils.isBinary(this); - - bool get isIPv4 => GetUtils.isIPv4(this); - - bool get isIPv6 => GetUtils.isIPv6(this); - - bool get isHexadecimal => GetUtils.isHexadecimal(this); - - bool get isPalindrom => GetUtils.isPalindrom(this); - - bool get isPassport => GetUtils.isPassport(this); - - bool get isCurrency => GetUtils.isCurrency(this); - - bool get isCpf => GetUtils.isCpf(this); - - bool get isCnpj => GetUtils.isCnpj(this); - - bool isCaseInsensitiveContains(String b) => - GetUtils.isCaseInsensitiveContains(this, b); - - bool isCaseInsensitiveContainsAny(String b) => - GetUtils.isCaseInsensitiveContainsAny(this, b); - - String get capitalize => GetUtils.capitalize(this); - - String get capitalizeFirst => GetUtils.capitalizeFirst(this); - - String get removeAllWhitespace => GetUtils.removeAllWhitespace(this); - - String get camelCase => GetUtils.camelCase(this); - - String numericOnly({bool firstWordOnly = false}) => - GetUtils.numericOnly(this, firstWordOnly: firstWordOnly); -} diff --git a/packages/get_utils/lib/src/extensions/widget_extensions.dart b/packages/get_utils/lib/src/extensions/widget_extensions.dart deleted file mode 100644 index 3e4b6d3d8..000000000 --- a/packages/get_utils/lib/src/extensions/widget_extensions.dart +++ /dev/null @@ -1,56 +0,0 @@ -import 'package:flutter/widgets.dart'; - -/// add Padding Property to widget -extension WidgetPaddingX on Widget { - Widget paddingAll(double padding) => - Padding(padding: EdgeInsets.all(padding), child: this); - - Widget paddingSymmetric({double horizontal = 0.0, double vertical = 0.0}) => - Padding( - padding: - EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), - child: this); - - Widget paddingOnly({ - double left = 0.0, - double top = 0.0, - double right = 0.0, - double bottom = 0.0, - }) => - Padding( - padding: EdgeInsets.only( - top: top, left: left, right: right, bottom: bottom), - child: this); - - Widget get paddingZero => Padding(padding: EdgeInsets.zero, child: this); -} - -/// Add margin property to widget -extension WidgetMarginX on Widget { - Widget marginAll(double margin) => - Container(margin: EdgeInsets.all(margin), child: this); - - Widget marginSymmetric({double horizontal = 0.0, double vertical = 0.0}) => - Container( - margin: - EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), - child: this); - - Widget marginOnly({ - double left = 0.0, - double top = 0.0, - double right = 0.0, - double bottom = 0.0, - }) => - Container( - margin: EdgeInsets.only( - top: top, left: left, right: right, bottom: bottom), - child: this); - - Widget get marginZero => Container(margin: EdgeInsets.zero, child: this); -} - -/// Allows you to insert widgets inside a CustomScrollView -extension WidgetSliverBoxX on Widget { - Widget get sliverBox => SliverToBoxAdapter(child: this); -} diff --git a/packages/get_utils/lib/src/get_utils/get_utils.dart b/packages/get_utils/lib/src/get_utils/get_utils.dart deleted file mode 100644 index 96561cc73..000000000 --- a/packages/get_utils/lib/src/get_utils/get_utils.dart +++ /dev/null @@ -1,581 +0,0 @@ -import 'package:get_core/get_core.dart'; - -/// Returns whether a dynamic value PROBABLY -/// has the isEmpty getter/method by checking -/// standard dart types that contains it. -/// -/// This is here to for the 'DRY' -bool _hasIsEmpty(dynamic value) { - return value is Iterable || value is String || value is Map; -} - -/// Returns whether a dynamic value PROBABLY -/// has the length getter/method by checking -/// standard dart types that contains it. -/// -/// This is here to for the 'DRY' -bool _hasLength(dynamic value) { - return value is Iterable || value is String || value is Map; -} - -/// Obtains a length of a dynamic value -/// by previously validating it's type -/// -/// Note: if [value] is double/int -/// it will be taking the .toString -/// length of the given value. -/// -/// Note 2: **this may return null!** -/// -/// Note 3: null [value] returns null. -int _obtainDynamicLength(dynamic value) { - if (value == null) { - // ignore: avoid_returning_null - return null; - } - - if (_hasLength(value)) { - return value.length as int; - } - - if (value is int) { - return value.toString().length; - } - - if (value is double) { - return value.toString().replaceAll('.', '').length; - } - - // ignore: avoid_returning_null - return null; -} - -class GetUtils { - GetUtils._(); - - /// Checks if data is null. - static bool isNull(dynamic value) => value == null; - - /// In dart2js (in flutter v1.17) a var by default is undefined. - /// *Use this only if you are in version <- 1.17*. - /// So we assure the null type in json convertions to avoid the - /// "value":value==null?null:value; someVar.nil will force the null type - /// if the var is null or undefined. - /// `nil` taken from ObjC just to have a shorter sintax. - static dynamic nil(dynamic s) => s == null ? null : s; - - /// Checks if data is null or blank (empty or only contains whitespace). - static bool isNullOrBlank(dynamic value) { - if (isNull(value)) { - return true; - } - - if (value is String) { - return value.toString().trim().isEmpty; - } - - // Pretty sure that isNullOrBlank should't be validating - // iterables... but I'm going to keep this for compatibility. - return _hasIsEmpty(value) ? value.isEmpty as bool : false; - } - - /// Checks if string is int or double. - static bool isNum(String value) { - if (isNull(value)) { - return false; - } - - return num.tryParse(value) is num; - } - - /// Checks if string consist only numeric. - /// Numeric only doesn't accepting "." which double data type have - static bool isNumericOnly(String s) => hasMatch(s, r'^\d+$'); - - /// Checks if string consist only Alphabet. (No Whitespace) - static bool isAlphabetOnly(String s) => hasMatch(s, r'^[a-zA-Z]+$'); - - /// Checks if string is boolean. - static bool isBool(String value) { - if (isNull(value)) { - return false; - } - - return (value == 'true' || value == 'false'); - } - - /// Checks if string is an video file. - static bool isVideo(String filePath) { - var ext = filePath.toLowerCase(); - - return ext.endsWith(".mp4") || - ext.endsWith(".avi") || - ext.endsWith(".wmv") || - ext.endsWith(".rmvb") || - ext.endsWith(".mpg") || - ext.endsWith(".mpeg") || - ext.endsWith(".3gp"); - } - - /// Checks if string is an image file. - static bool isImage(String filePath) { - final ext = filePath.toLowerCase(); - - return ext.endsWith(".jpg") || - ext.endsWith(".jpeg") || - ext.endsWith(".png") || - ext.endsWith(".gif") || - ext.endsWith(".bmp"); - } - - /// Checks if string is an audio file. - static bool isAudio(String filePath) { - final ext = filePath.toLowerCase(); - - return ext.endsWith(".mp3") || - ext.endsWith(".wav") || - ext.endsWith(".wma") || - ext.endsWith(".amr") || - ext.endsWith(".ogg"); - } - - /// Checks if string is an powerpoint file. - static bool isPPT(String filePath) { - final ext = filePath.toLowerCase(); - - return ext.endsWith(".ppt") || ext.endsWith(".pptx"); - } - - /// Checks if string is an word file. - static bool isWord(String filePath) { - final ext = filePath.toLowerCase(); - - return ext.endsWith(".doc") || ext.endsWith(".docx"); - } - - /// Checks if string is an excel file. - static bool isExcel(String filePath) { - final ext = filePath.toLowerCase(); - - return ext.endsWith(".xls") || ext.endsWith(".xlsx"); - } - - /// Checks if string is an apk file. - static bool isAPK(String filePath) { - return filePath.toLowerCase().endsWith(".apk"); - } - - /// Checks if string is an pdf file. - static bool isPDF(String filePath) { - return filePath.toLowerCase().endsWith(".pdf"); - } - - /// Checks if string is an txt file. - static bool isTxt(String filePath) { - return filePath.toLowerCase().endsWith(".txt"); - } - - /// Checks if string is an chm file. - static bool isChm(String filePath) { - return filePath.toLowerCase().endsWith(".chm"); - } - - /// Checks if string is a vector file. - static bool isVector(String filePath) { - return filePath.toLowerCase().endsWith(".svg"); - } - - /// Checks if string is an html file. - static bool isHTML(String filePath) { - return filePath.toLowerCase().endsWith(".html"); - } - - /// Checks if string is a valid username. - static bool isUsername(String s) => - hasMatch(s, r'^[a-zA-Z0-9][a-zA-Z0-9_.]+[a-zA-Z0-9]$'); - - /// Checks if string is URL. - static bool isURL(String s) => hasMatch(s, - r"^((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\:[0-9]{1,5})*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$"); - - /// Checks if string is email. - static bool isEmail(String s) => hasMatch(s, - r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'); - - /// Checks if string is phone number. - static bool isPhoneNumber(String s) => hasMatch(s, - r'^(0|\+|(\+[0-9]{2,4}|\(\+?[0-9]{2,4}\)) ?)([0-9]*|\d{2,4}-\d{2,4}(-\d{2,4})?)$'); - - /// Checks if string is DateTime (UTC or Iso8601). - static bool isDateTime(String s) => - hasMatch(s, r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}.\d{3}Z?$'); - - /// Checks if string is MD5 hash. - static bool isMD5(String s) => hasMatch(s, r'^[a-f0-9]{32}$'); - - /// Checks if string is SHA1 hash. - static bool isSHA1(String s) => - hasMatch(s, r'(([A-Fa-f0-9]{2}\:){19}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{40})'); - - /// Checks if string is SHA256 hash. - static bool isSHA256(String s) => - hasMatch(s, r'([A-Fa-f0-9]{2}\:){31}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{64}'); - - /// Checks if string is SSN (Social Security Number). - static bool isSSN(String s) => hasMatch(s, - r'^(?!0{3}|6{3}|9[0-9]{2})[0-9]{3}-?(?!0{2})[0-9]{2}-?(?!0{4})[0-9]{4}$'); - - /// Checks if string is binary. - static bool isBinary(String s) => hasMatch(s, r'^[0-1]+$'); - - /// Checks if string is IPv4. - static bool isIPv4(String s) => - hasMatch(s, r'^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$'); - - /// Checks if string is IPv6. - static bool isIPv6(String s) => hasMatch(s, - r'^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$'); - - /// Checks if string is hexadecimal. - /// Example: HexColor => #12F - static bool isHexadecimal(String s) => - hasMatch(s, r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'); - - /// Checks if string is Palindrom. - static bool isPalindrom(String string) { - final cleanString = string - .toLowerCase() - .replaceAll(RegExp(r"\s+"), '') - .replaceAll(RegExp(r"[^0-9a-zA-Z]+"), ""); - - for (var i = 0; i < cleanString.length; i++) { - if (cleanString[i] != cleanString[cleanString.length - i - 1]) { - return false; - } - } - - return true; - } - - /// Checks if all data have same value. - /// Example: 111111 -> true, wwwww -> true, [1,1,1,1] -> true - static bool isOneAKind(dynamic value) { - if ((value is String || value is List) && !isNullOrBlank(value)) { - final first = value[0]; - final len = value.length as num; - - for (var i = 0; i < len; i++) { - if (value[i] != first) { - return false; - } - } - - return true; - } - - if (value is int) { - final stringValue = value.toString(); - final first = stringValue[0]; - - for (var i = 0; i < stringValue.length; i++) { - if (stringValue[i] != first) { - return false; - } - } - - return true; - } - - return false; - } - - /// Checks if string is Passport No. - static bool isPassport(String s) => - hasMatch(s, r'^(?!^0+$)[a-zA-Z0-9]{6,9}$'); - - /// Checks if string is Currency. - static bool isCurrency(String s) => hasMatch(s, - r'^(S?\$|\₩|Rp|\¥|\€|\₹|\₽|fr|R\$|R)?[ ]?[-]?([0-9]{1,3}[,.]([0-9]{3}[,.])*[0-9]{3}|[0-9]+)([,.][0-9]{1,2})?( ?(USD?|AUD|NZD|CAD|CHF|GBP|CNY|EUR|JPY|IDR|MXN|NOK|KRW|TRY|INR|RUB|BRL|ZAR|SGD|MYR))?$'); - - /// Checks if length of data is GREATER than maxLength. - static bool isLengthGreaterThan(dynamic value, int maxLength) { - final length = _obtainDynamicLength(value); - - if (length == null) { - return false; - } - - return length > maxLength; - } - - /// Checks if length of data is GREATER OR EQUAL to maxLength. - static bool isLengthGreaterOrEqual(dynamic value, int maxLength) { - final length = _obtainDynamicLength(value); - - if (length == null) { - return false; - } - - return length >= maxLength; - } - - /// Checks if length of data is LOWER than maxLength. - /// - /// This method is deprecated, use [isLengthLessThan] instead - @deprecated - static bool isLengthLowerThan(dynamic value, int maxLength) => - isLengthLessThan(value, maxLength); - - /// Checks if length of data is LESS than maxLength. - static bool isLengthLessThan(dynamic value, int maxLength) { - final length = _obtainDynamicLength(value); - if (length == null) { - return false; - } - - return length < maxLength; - } - - /// Checks if length of data is LOWER OR EQUAL to maxLength. - /// - /// This method is deprecated, use [isLengthLessOrEqual] instead - @deprecated - static bool isLengthLowerOrEqual(dynamic value, int maxLength) => - isLengthLessOrEqual(value, maxLength); - - /// Checks if length of data is LESS OR EQUAL to maxLength. - static bool isLengthLessOrEqual(dynamic value, int maxLength) { - final length = _obtainDynamicLength(value); - - if (length == null) { - return false; - } - - return length <= maxLength; - } - - /// Checks if length of data is EQUAL to maxLength. - static bool isLengthEqualTo(dynamic value, int otherLength) { - final length = _obtainDynamicLength(value); - - if (length == null) { - return false; - } - - return length == otherLength; - } - - /// Checks if length of data is BETWEEN minLength to maxLength. - static bool isLengthBetween(dynamic value, int minLength, int maxLength) { - if (isNull(value)) { - return false; - } - - return isLengthGreaterOrEqual(value, minLength) && - isLengthLessOrEqual(value, maxLength); - } - - /// Checks if a contains b (Treating or interpreting upper- and lowercase - /// letters as being the same). - static bool isCaseInsensitiveContains(String a, String b) { - return a.toLowerCase().contains(b.toLowerCase()); - } - - /// Checks if a contains b or b contains a (Treating or - /// interpreting upper- and lowercase letters as being the same). - static bool isCaseInsensitiveContainsAny(String a, String b) { - final lowA = a.toLowerCase(); - final lowB = b.toLowerCase(); - - return lowA.contains(lowB) || lowB.contains(lowA); - } - - /// Checks if num a LOWER than num b. - static bool isLowerThan(num a, num b) => a < b; - - /// Checks if num a GREATER than num b. - static bool isGreaterThan(num a, num b) => a > b; - - /// Checks if num a EQUAL than num b. - static bool isEqual(num a, num b) => a == b; - - //Check if num is a cnpj - static bool isCnpj(String cnpj) { - if (cnpj == null) { - return false; - } - - // Obter somente os números do CNPJ - final numbers = cnpj.replaceAll(RegExp(r'[^0-9]'), ''); - - // Testar se o CNPJ possui 14 dígitos - if (numbers.length != 14) { - return false; - } - - // Testar se todos os dígitos do CNPJ são iguais - if (RegExp(r'^(\d)\1*$').hasMatch(numbers)) { - return false; - } - - // Dividir dígitos - final digits = numbers.split('').map(int.parse).toList(); - - // Calcular o primeiro dígito verificador - var calcDv1 = 0; - var j = 0; - for (var i in Iterable.generate(12, (i) => i < 4 ? 5 - i : 13 - i)) { - calcDv1 += digits[j++] * i; - } - calcDv1 %= 11; - final dv1 = calcDv1 < 2 ? 0 : 11 - calcDv1; - - // Testar o primeiro dígito verificado - if (digits[12] != dv1) { - return false; - } - - // Calcular o segundo dígito verificador - var calcDv2 = 0; - j = 0; - for (var i in Iterable.generate(13, (i) => i < 5 ? 6 - i : 14 - i)) { - calcDv2 += digits[j++] * i; - } - calcDv2 %= 11; - final dv2 = calcDv2 < 2 ? 0 : 11 - calcDv2; - - // Testar o segundo dígito verificador - if (digits[13] != dv2) { - return false; - } - - return true; - } - - /// Checks if the cpf is valid. - static bool isCpf(String cpf) { - if (cpf == null) { - return false; - } - - // get only the numbers - final numbers = cpf.replaceAll(RegExp(r'[^0-9]'), ''); - // Test if the CPF has 11 digits - if (numbers.length != 11) { - return false; - } - // Test if all CPF digits are the same - if (RegExp(r'^(\d)\1*$').hasMatch(numbers)) { - return false; - } - - // split the digits - final digits = numbers.split('').map(int.parse).toList(); - - // Calculate the first verifier digit - var calcDv1 = 0; - for (var i in Iterable.generate(9, (i) => 10 - i)) { - calcDv1 += digits[10 - i] * i; - } - calcDv1 %= 11; - - final dv1 = calcDv1 < 2 ? 0 : 11 - calcDv1; - - // Tests the first verifier digit - if (digits[9] != dv1) { - return false; - } - - // Calculate the second verifier digit - var calcDv2 = 0; - for (var i in Iterable.generate(10, (i) => 11 - i)) { - calcDv2 += digits[11 - i] * i; - } - calcDv2 %= 11; - - final dv2 = calcDv2 < 2 ? 0 : 11 - calcDv2; - - // Test the second verifier digit - if (digits[10] != dv2) { - return false; - } - - return true; - } - - /// Capitalize each word inside string - /// Example: your name => Your Name, your name => Your name - static String capitalize(String value) { - if (isNullOrBlank(value)) return null; - return value.split(' ').map(capitalizeFirst).join(' '); - } - - /// Uppercase first letter inside string and let the others lowercase - /// Example: your name => Your name - static String capitalizeFirst(String s) { - if (isNullOrBlank(s)) { - return null; - } - - return s[0].toUpperCase() + s.substring(1).toLowerCase(); - } - - /// Remove all whitespace inside string - /// Example: your name => yourname - static String removeAllWhitespace(String value) { - if (isNullOrBlank(value)) { - return null; - } - - return value.replaceAll(' ', ''); - } - - /// Camelcase string - /// Example: your name => yourName - static String camelCase(String value) { - if (isNullOrBlank(value)) { - return null; - } - - final separatedWords = value.split(' '); - var newString = ''; - - for (final word in separatedWords) { - newString += word[0].toUpperCase() + word.substring(1).toLowerCase(); - } - - return newString[0].toLowerCase() + newString.substring(1); - } - - /// Extract numeric value of string - /// Example: OTP 12312 27/04/2020 => 1231227042020ß - /// If firstword only is true, then the example return is "12312" - /// (first found numeric word) - static String numericOnly(String s, {bool firstWordOnly = false}) { - var numericOnlyStr = ''; - - for (var i = 0; i < s.length; i++) { - if (isNumericOnly(s[i])) { - numericOnlyStr += s[i]; - } - if (firstWordOnly && numericOnlyStr.isNotEmpty && s[i] == " ") { - break; - } - } - - return numericOnlyStr; - } - - static bool hasMatch(String value, String pattern) { - return (value == null) ? false : RegExp(pattern).hasMatch(value); - } - - static void printFunction( - String prefix, - dynamic value, - String info, { - bool isError = false, - }) { - Get.log('$prefix $value $info'.trim(), isError: isError); - } -} diff --git a/packages/get_utils/lib/src/platform/platform.dart b/packages/get_utils/lib/src/platform/platform.dart deleted file mode 100644 index 63dc201cb..000000000 --- a/packages/get_utils/lib/src/platform/platform.dart +++ /dev/null @@ -1,23 +0,0 @@ -import 'platform_web.dart' if (dart.library.io) 'platform_io.dart'; - -// ignore: avoid_classes_with_only_static_members -class GetPlatform { - static bool get isWeb => GeneralPlatform.isWeb; - - static bool get isMacOS => GeneralPlatform.isMacOS; - - static bool get isWindows => GeneralPlatform.isWindows; - - static bool get isLinux => GeneralPlatform.isLinux; - - static bool get isAndroid => GeneralPlatform.isAndroid; - - static bool get isIOS => GeneralPlatform.isIOS; - - static bool get isFuchsia => GeneralPlatform.isFuchsia; - - static bool get isMobile => GetPlatform.isIOS || GetPlatform.isAndroid; - - static bool get isDesktop => - GetPlatform.isMacOS || GetPlatform.isWindows || GetPlatform.isLinux; -} diff --git a/packages/get_utils/lib/src/platform/platform_io.dart b/packages/get_utils/lib/src/platform/platform_io.dart deleted file mode 100644 index 1808275b3..000000000 --- a/packages/get_utils/lib/src/platform/platform_io.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'dart:io'; - -// ignore: avoid_classes_with_only_static_members -class GeneralPlatform { - static bool get isWeb => false; - - static bool get isMacOS => Platform.isMacOS; - - static bool get isWindows => Platform.isWindows; - - static bool get isLinux => Platform.isLinux; - - static bool get isAndroid => Platform.isAndroid; - - static bool get isIOS => Platform.isIOS; - - static bool get isFuchsia => Platform.isFuchsia; - - static bool get isDesktop => - Platform.isMacOS || Platform.isWindows || Platform.isLinux; -} diff --git a/packages/get_utils/lib/src/platform/platform_web.dart b/packages/get_utils/lib/src/platform/platform_web.dart deleted file mode 100644 index 9387e11b0..000000000 --- a/packages/get_utils/lib/src/platform/platform_web.dart +++ /dev/null @@ -1,35 +0,0 @@ -// TODO: resolve platform/desktop by JS browser agent. -// ignore: avoid_web_libraries_in_flutter -import 'dart:html' as html; - -import '../../get_utils.dart'; - -html.Navigator _navigator = html.window.navigator; - -// ignore: avoid_classes_with_only_static_members -class GeneralPlatform { - static bool get isWeb => true; - - static bool get isMacOS => - _navigator.appVersion.contains('Mac OS') && !GeneralPlatform.isIOS; - - static bool get isWindows => _navigator.appVersion.contains('Win'); - - static bool get isLinux => - (_navigator.appVersion.contains('Linux') || - _navigator.appVersion.contains('x11')) && - !isAndroid; - - // @check https://developer.chrome.com/multidevice/user-agent - static bool get isAndroid => _navigator.appVersion.contains('Android '); - - static bool get isIOS { - // maxTouchPoints is needed to separate iPad iOS13 vs new MacOS - return GetUtils.hasMatch(_navigator.platform, r'/iPad|iPhone|iPod/') || - (_navigator.platform == 'MacIntel' && _navigator.maxTouchPoints > 1); - } - - static bool get isFuchsia => false; - - static bool get isDesktop => isMacOS || isWindows || isLinux; -} diff --git a/packages/get_utils/lib/src/queue/get_queue.dart b/packages/get_utils/lib/src/queue/get_queue.dart deleted file mode 100644 index cfb524463..000000000 --- a/packages/get_utils/lib/src/queue/get_queue.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'dart:async'; - -class GetQueue { - final List<_Item> _queue = []; - bool _active = false; - - void _check() async { - if (!_active && _queue.isNotEmpty) { - _active = true; - var item = _queue.removeAt(0); - try { - item.completer.complete(await item.job()); - } on Exception catch (e) { - item.completer.completeError(e); - } - _active = false; - _check(); - } - } - - Future add(Function job) { - var completer = Completer(); - _queue.add(_Item(completer, job)); - _check(); - return completer.future; - } -} - -class _Item { - final dynamic completer; - final dynamic job; - - _Item(this.completer, this.job); -} diff --git a/packages/get_utils/pubspec.yaml b/packages/get_utils/pubspec.yaml deleted file mode 100644 index 3662139a2..000000000 --- a/packages/get_utils/pubspec.yaml +++ /dev/null @@ -1,55 +0,0 @@ -name: get_utils -description: A set of tools that allows you to access high-level APIs and obtain validation tools for Flutter and GetX™ framework. -version: 3.13.0 -homepage: https://github.com/jonataslaw/getx - -environment: - sdk: ">=2.7.0 <3.0.0" - flutter: ">=1.17.0 <2.0.0" - -dependencies: - flutter: - sdk: flutter - get_core: ">=3.13.0 <4.0.0" - meta: ">=1.1.0 <2.0.0" - -dev_dependencies: - flutter_test: - sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter. -flutter: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/get_utils/test/platform_test.dart b/packages/get_utils/test/platform_test.dart deleted file mode 100644 index e00065fc7..000000000 --- a/packages/get_utils/test/platform_test.dart +++ /dev/null @@ -1,16 +0,0 @@ -@TestOn('vm') -import 'dart:io'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_utils/get_utils.dart'; - -void main() { - test('Platform test', () { - expect(GetPlatform.isAndroid, Platform.isAndroid); - expect(GetPlatform.isIOS, Platform.isIOS); - expect(GetPlatform.isFuchsia, Platform.isFuchsia); - expect(GetPlatform.isLinux, Platform.isLinux); - expect(GetPlatform.isMacOS, Platform.isMacOS); - expect(GetPlatform.isWindows, Platform.isWindows); - expect(GetPlatform.isWeb, false); - }); -} diff --git a/packages/get_utils/test/platform_web_test.dart b/packages/get_utils/test/platform_web_test.dart deleted file mode 100644 index 240deb3eb..000000000 --- a/packages/get_utils/test/platform_web_test.dart +++ /dev/null @@ -1,16 +0,0 @@ -@TestOn('browser') -import 'dart:io'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:get_utils/get_utils.dart'; - -void main() { - test('Platform test', () { - expect(GetPlatform.isAndroid, Platform.isAndroid); - expect(GetPlatform.isIOS, Platform.isIOS); - expect(GetPlatform.isFuchsia, Platform.isFuchsia); - expect(GetPlatform.isLinux, Platform.isLinux); - expect(GetPlatform.isMacOS, Platform.isMacOS); - expect(GetPlatform.isWindows, Platform.isWindows); - expect(GetPlatform.isWeb, true); - }); -} diff --git a/pubspec.yaml b/pubspec.yaml index 42fbe7129..38ee26d1b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: get description: Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with GetX. -version: 3.13.1 +version: 3.13.2 homepage: https://github.com/jonataslaw/getx environment: