diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index dc8afb2..8ef85e5 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -50,6 +50,10 @@ + + diff --git a/i18n/en.json b/i18n/en.json index 4c5ba68..616d0b7 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -408,6 +408,7 @@ "Start":"Start", "Compact Test":"Compact Test", "Custom Test":"Custom Test", - "Set": "Set" + "Set": "Set", + "Add this exercise to execute it paralell":"Add this exercise to execute it paralell" } \ No newline at end of file diff --git a/i18n/hu.json b/i18n/hu.json index 830090c..becdf9e 100644 --- a/i18n/hu.json +++ b/i18n/hu.json @@ -404,7 +404,8 @@ "Start":"Kezdd el", "Compact Test":"Kompakt teszt", "Custom Test":"Egyedi teszt", - "Set": "Széria" + "Set": "Széria", + "Add this exercise to execute it paralell":"Adj hozzá egy gyakorlatot a párhuzamos végrehajtáshoz" } \ No newline at end of file diff --git a/ios/Podfile b/ios/Podfile index 4a8b85d..0a4d76d 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -platform :ios, '10.0' +platform :ios, '12.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/ios/Podfile.lock b/ios/Podfile.lock index e3ce06e..42b988b 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -6,102 +6,92 @@ PODS: - AppAuth/ExternalUserAgent (1.4.0) - apple_sign_in (0.0.1): - Flutter - - audioplayer (0.0.1): - - Flutter - devicelocale (0.0.1): - Flutter - - FBSDKCoreKit (9.0.0): - - FBSDKCoreKit/Basics (= 9.0.0) - - FBSDKCoreKit/Core (= 9.0.0) - - FBSDKCoreKit/Basics (9.0.0) - - FBSDKCoreKit/Core (9.0.0): + - FBSDKCoreKit (9.1.0): + - FBSDKCoreKit/Basics (= 9.1.0) + - FBSDKCoreKit/Core (= 9.1.0) + - FBSDKCoreKit/Basics (9.1.0) + - FBSDKCoreKit/Core (9.1.0): - FBSDKCoreKit/Basics - - FBSDKLoginKit (9.0.0): - - FBSDKLoginKit/Login (= 9.0.0) - - FBSDKLoginKit/Login (9.0.0): - - FBSDKCoreKit (~> 9.0.0) - - Firebase/Analytics (6.33.0): + - FBSDKLoginKit (9.1.0): + - FBSDKLoginKit/Login (= 9.1.0) + - FBSDKLoginKit/Login (9.1.0): + - FBSDKCoreKit (~> 9.1.0) + - Firebase/Analytics (7.3.0): - Firebase/Core - - Firebase/Auth (6.33.0): + - Firebase/Auth (7.3.0): - Firebase/CoreOnly - - FirebaseAuth (~> 6.9.2) - - Firebase/Core (6.33.0): + - FirebaseAuth (~> 7.3.0) + - Firebase/Core (7.3.0): - Firebase/CoreOnly - - FirebaseAnalytics (= 6.8.3) - - Firebase/CoreOnly (6.33.0): - - FirebaseCore (= 6.10.3) - - Firebase/Messaging (6.33.0): + - FirebaseAnalytics (= 7.3.0) + - Firebase/CoreOnly (7.3.0): + - FirebaseCore (= 7.3.0) + - Firebase/Messaging (7.3.0): - Firebase/CoreOnly - - FirebaseMessaging (~> 4.7.0) - - firebase_analytics (6.3.0): - - Firebase/Analytics (~> 6.33.0) - - Firebase/CoreOnly (~> 6.33.0) + - FirebaseMessaging (~> 7.3.0) + - firebase_analytics (8.0.0-dev.0): + - Firebase/Analytics (= 7.3.0) - firebase_core - Flutter - - firebase_auth (0.18.4-1): - - Firebase/Auth (~> 6.33.0) - - Firebase/CoreOnly (~> 6.33.0) + - firebase_auth (1.0.1): + - Firebase/Auth (= 7.3.0) - firebase_core - Flutter - - firebase_core (0.5.3): - - Firebase/CoreOnly (~> 6.33.0) + - firebase_core (1.0.2): + - Firebase/CoreOnly (= 7.3.0) - Flutter - - firebase_messaging (7.0.3): - - Firebase/CoreOnly (~> 6.33.0) - - Firebase/Messaging (~> 6.33.0) + - firebase_messaging (9.1.0): + - Firebase/Messaging (= 7.3.0) - firebase_core - Flutter - - FirebaseAnalytics (6.8.3): - - FirebaseCore (~> 6.10) - - FirebaseInstallations (~> 1.6) - - GoogleAppMeasurement (= 6.8.3) - - GoogleUtilities/AppDelegateSwizzler (~> 6.7) - - GoogleUtilities/MethodSwizzler (~> 6.7) - - GoogleUtilities/Network (~> 6.7) - - "GoogleUtilities/NSData+zlib (~> 6.7)" - - nanopb (~> 1.30906.0) - - FirebaseAuth (6.9.2): - - FirebaseCore (~> 6.10) - - GoogleUtilities/AppDelegateSwizzler (~> 6.7) - - GoogleUtilities/Environment (~> 6.7) - - GTMSessionFetcher/Core (~> 1.1) - - FirebaseCore (6.10.3): - - FirebaseCoreDiagnostics (~> 1.6) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/Logger (~> 6.7) - - FirebaseCoreDiagnostics (1.7.0): - - GoogleDataTransport (~> 7.4) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/Logger (~> 6.7) - - nanopb (~> 1.30906.0) - - FirebaseInstallations (1.7.0): - - FirebaseCore (~> 6.10) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/UserDefaults (~> 6.7) + - FirebaseAnalytics (7.3.0): + - FirebaseCore (~> 7.0) + - FirebaseInstallations (~> 7.0) + - GoogleAppMeasurement (= 7.3.0) + - GoogleUtilities/AppDelegateSwizzler (~> 7.0) + - GoogleUtilities/MethodSwizzler (~> 7.0) + - GoogleUtilities/Network (~> 7.0) + - "GoogleUtilities/NSData+zlib (~> 7.0)" + - nanopb (~> 2.30906.0) + - FirebaseAuth (7.3.0): + - FirebaseCore (~> 7.0) + - GoogleUtilities/AppDelegateSwizzler (~> 7.0) + - GoogleUtilities/Environment (~> 7.0) + - GTMSessionFetcher/Core (~> 1.4) + - FirebaseCore (7.3.0): + - FirebaseCoreDiagnostics (~> 7.0) + - GoogleUtilities/Environment (~> 7.0) + - GoogleUtilities/Logger (~> 7.0) + - FirebaseCoreDiagnostics (7.3.0): + - GoogleDataTransport (~> 8.0) + - GoogleUtilities/Environment (~> 7.0) + - GoogleUtilities/Logger (~> 7.0) + - nanopb (~> 2.30906.0) + - FirebaseInstallations (7.9.0): + - FirebaseCore (~> 7.0) + - GoogleUtilities/Environment (~> 7.0) + - GoogleUtilities/UserDefaults (~> 7.0) - PromisesObjC (~> 1.2) - - FirebaseInstanceID (4.8.0): - - FirebaseCore (~> 6.10) - - FirebaseInstallations (~> 1.6) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/UserDefaults (~> 6.7) - - FirebaseMessaging (4.7.1): - - FirebaseCore (~> 6.10) - - FirebaseInstanceID (~> 4.7) - - GoogleUtilities/AppDelegateSwizzler (~> 6.7) - - GoogleUtilities/Environment (~> 6.7) - - GoogleUtilities/Reachability (~> 6.7) - - GoogleUtilities/UserDefaults (~> 6.7) - - Protobuf (>= 3.9.2, ~> 3.9) - - flurry (0.0.4): - - Flurry-iOS-SDK/FlurrySDK - - Flutter - - Flurry-iOS-SDK/FlurrySDK (11.2.0) + - FirebaseInstanceID (7.9.0): + - FirebaseCore (~> 7.0) + - FirebaseInstallations (~> 7.0) + - GoogleUtilities/Environment (~> 7.0) + - GoogleUtilities/UserDefaults (~> 7.0) + - FirebaseMessaging (7.3.0): + - FirebaseCore (~> 7.0) + - FirebaseInstanceID (~> 7.0) + - GoogleUtilities/AppDelegateSwizzler (~> 7.0) + - GoogleUtilities/Environment (~> 7.0) + - GoogleUtilities/Reachability (~> 7.0) + - GoogleUtilities/UserDefaults (~> 7.0) - Flutter (1.0.0) - - flutter_facebook_auth (1.0.0): - - FBSDKCoreKit (~> 9.0.0) - - FBSDKLoginKit (~> 9.0.0) + - flutter_facebook_auth (2.0.0): + - FBSDKCoreKit (~> 9.1.0) + - FBSDKLoginKit (~> 9.1.0) - Flutter - - flutter_keyboard_visibility (0.0.1): + - flutter_local_notifications (0.0.1): - Flutter - flutter_secure_storage (3.3.1): - Flutter @@ -111,36 +101,36 @@ PODS: - google_sign_in (0.0.1): - Flutter - GoogleSignIn (~> 5.0) - - GoogleAppMeasurement (6.8.3): - - GoogleUtilities/AppDelegateSwizzler (~> 6.7) - - GoogleUtilities/MethodSwizzler (~> 6.7) - - GoogleUtilities/Network (~> 6.7) - - "GoogleUtilities/NSData+zlib (~> 6.7)" - - nanopb (~> 1.30906.0) - - GoogleDataTransport (7.5.1): - - nanopb (~> 1.30906.0) + - GoogleAppMeasurement (7.3.0): + - GoogleUtilities/AppDelegateSwizzler (~> 7.0) + - GoogleUtilities/MethodSwizzler (~> 7.0) + - GoogleUtilities/Network (~> 7.0) + - "GoogleUtilities/NSData+zlib (~> 7.0)" + - nanopb (~> 2.30906.0) + - GoogleDataTransport (8.1.0): + - nanopb (~> 2.30906.0) - GoogleSignIn (5.0.2): - AppAuth (~> 1.2) - GTMAppAuth (~> 1.0) - GTMSessionFetcher/Core (~> 1.1) - - GoogleUtilities/AppDelegateSwizzler (6.7.2): + - GoogleUtilities/AppDelegateSwizzler (7.3.1): - GoogleUtilities/Environment - GoogleUtilities/Logger - GoogleUtilities/Network - - GoogleUtilities/Environment (6.7.2): + - GoogleUtilities/Environment (7.3.1): - PromisesObjC (~> 1.2) - - GoogleUtilities/Logger (6.7.2): + - GoogleUtilities/Logger (7.3.1): - GoogleUtilities/Environment - - GoogleUtilities/MethodSwizzler (6.7.2): + - GoogleUtilities/MethodSwizzler (7.3.1): - GoogleUtilities/Logger - - GoogleUtilities/Network (6.7.2): + - GoogleUtilities/Network (7.3.1): - GoogleUtilities/Logger - "GoogleUtilities/NSData+zlib" - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (6.7.2)" - - GoogleUtilities/Reachability (6.7.2): + - "GoogleUtilities/NSData+zlib (7.3.1)" + - GoogleUtilities/Reachability (7.3.1): - GoogleUtilities/Logger - - GoogleUtilities/UserDefaults (6.7.2): + - GoogleUtilities/UserDefaults (7.3.1): - GoogleUtilities/Logger - GTMAppAuth (1.1.0): - AppAuth/Core (~> 1.4) @@ -150,25 +140,26 @@ PODS: - GTMSessionFetcher/Core (1.5.0) - GTMSessionFetcher/Full (1.5.0): - GTMSessionFetcher/Core (= 1.5.0) - - nanopb (1.30906.0): - - nanopb/decode (= 1.30906.0) - - nanopb/encode (= 1.30906.0) - - nanopb/decode (1.30906.0) - - nanopb/encode (1.30906.0) + - modal_progress_hud_nsn (0.0.1): + - Flutter + - nanopb (2.30906.0): + - nanopb/decode (= 2.30906.0) + - nanopb/encode (= 2.30906.0) + - nanopb/decode (2.30906.0) + - nanopb/encode (2.30906.0) - package_info (0.0.1): - Flutter - path_provider (0.0.1): - Flutter - PromisesObjC (1.2.12) - - Protobuf (3.14.0) - - Purchases (3.9.2): - - PurchasesCoreSwift (= 3.9.2) - - purchases_flutter (2.0.3): + - Purchases (3.10.6): + - PurchasesCoreSwift (= 3.10.6) + - purchases_flutter (3.1.0): - Flutter - - PurchasesHybridCommon (= 1.5.0) - - PurchasesCoreSwift (3.9.2) - - PurchasesHybridCommon (1.5.0): - - Purchases (= 3.9.2) + - PurchasesHybridCommon (= 1.6.1) + - PurchasesCoreSwift (3.10.6) + - PurchasesHybridCommon (1.6.1): + - Purchases (= 3.10.6) - shared_preferences (0.0.1): - Flutter - smartlook (0.0.5): @@ -185,18 +176,17 @@ PODS: DEPENDENCIES: - apple_sign_in (from `.symlinks/plugins/apple_sign_in/ios`) - - audioplayer (from `.symlinks/plugins/audioplayer/ios`) - devicelocale (from `.symlinks/plugins/devicelocale/ios`) - firebase_analytics (from `.symlinks/plugins/firebase_analytics/ios`) - firebase_auth (from `.symlinks/plugins/firebase_auth/ios`) - firebase_core (from `.symlinks/plugins/firebase_core/ios`) - firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`) - - flurry (from `.symlinks/plugins/flurry/ios`) - Flutter (from `Flutter`) - flutter_facebook_auth (from `.symlinks/plugins/flutter_facebook_auth/ios`) - - flutter_keyboard_visibility (from `.symlinks/plugins/flutter_keyboard_visibility/ios`) + - flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`) - flutter_secure_storage (from `.symlinks/plugins/flutter_secure_storage/ios`) - google_sign_in (from `.symlinks/plugins/google_sign_in/ios`) + - modal_progress_hud_nsn (from `.symlinks/plugins/modal_progress_hud_nsn/ios`) - package_info (from `.symlinks/plugins/package_info/ios`) - path_provider (from `.symlinks/plugins/path_provider/ios`) - purchases_flutter (from `.symlinks/plugins/purchases_flutter/ios`) @@ -220,7 +210,6 @@ SPEC REPOS: - FirebaseInstallations - FirebaseInstanceID - FirebaseMessaging - - Flurry-iOS-SDK - FMDB - GoogleAppMeasurement - GoogleDataTransport @@ -230,7 +219,6 @@ SPEC REPOS: - GTMSessionFetcher - nanopb - PromisesObjC - - Protobuf - Purchases - PurchasesCoreSwift - PurchasesHybridCommon @@ -238,8 +226,6 @@ SPEC REPOS: EXTERNAL SOURCES: apple_sign_in: :path: ".symlinks/plugins/apple_sign_in/ios" - audioplayer: - :path: ".symlinks/plugins/audioplayer/ios" devicelocale: :path: ".symlinks/plugins/devicelocale/ios" firebase_analytics: @@ -250,18 +236,18 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/firebase_core/ios" firebase_messaging: :path: ".symlinks/plugins/firebase_messaging/ios" - flurry: - :path: ".symlinks/plugins/flurry/ios" Flutter: :path: Flutter flutter_facebook_auth: :path: ".symlinks/plugins/flutter_facebook_auth/ios" - flutter_keyboard_visibility: - :path: ".symlinks/plugins/flutter_keyboard_visibility/ios" + flutter_local_notifications: + :path: ".symlinks/plugins/flutter_local_notifications/ios" flutter_secure_storage: :path: ".symlinks/plugins/flutter_secure_storage/ios" google_sign_in: :path: ".symlinks/plugins/google_sign_in/ios" + modal_progress_hud_nsn: + :path: ".symlinks/plugins/modal_progress_hud_nsn/ios" package_info: :path: ".symlinks/plugins/package_info/ios" path_provider: @@ -284,52 +270,49 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: AppAuth: 31bcec809a638d7bd2f86ea8a52bd45f6e81e7c7 apple_sign_in: 7716c7ddfa195aeab7dec0dc374ef4ff45d1adb4 - audioplayer: 0584f31a697e4b0bbad405ae7903d7a93585e784 - devicelocale: feebbe5e7a30adb8c4f83185de1b50ff19b44f00 - FBSDKCoreKit: ac6cc500b8e104bb9a4dd20b1527b5d199123c2e - FBSDKLoginKit: e9b6542fdee322333502ab497f628b011dce7d78 - Firebase: 8db6f2d1b2c5e2984efba4949a145875a8f65fe5 - firebase_analytics: 36a619088c46224900829f14f4daa71585693a6f - firebase_auth: d5159db3873478d1ac839af7b10d2f831516136a - firebase_core: 5d6a02f3d85acd5f8321c2d6d62877626a670659 - firebase_messaging: 0aea2cd5885b65e19ede58ee3507f485c992cc75 - FirebaseAnalytics: 5dd088bd2e67bb9d13dbf792d1164ceaf3052193 - FirebaseAuth: c92d49ada7948d1a23466e3db17bc4c2039dddc3 - FirebaseCore: d889d9e12535b7f36ac8bfbf1713a0836a3012cd - FirebaseCoreDiagnostics: 770ac5958e1372ce67959ae4b4f31d8e127c3ac1 - FirebaseInstallations: 466c7b4d1f58fe16707693091da253726a731ed2 - FirebaseInstanceID: bd3ffc24367f901a43c063b36c640b345a4a5dd1 - FirebaseMessaging: 5eca4ef173de76253352511aafef774caa1cba2a - flurry: 15b01f664ab1367c62b50291541ea7f78ca85aad - Flurry-iOS-SDK: 6636d30c30f12010e7c7c71d84b443416a168efc - Flutter: 0e3d915762c693b495b44d77113d4970485de6ec - flutter_facebook_auth: d952ca599c6a76439c54472b0b225004e1b880c4 - flutter_keyboard_visibility: 0339d06371254c3eb25eeb90ba8d17dca8f9c069 + devicelocale: b22617f40038496deffba44747101255cee005b0 + FBSDKCoreKit: a00fe2efd780c195a5e09201bf51c56106245b40 + FBSDKLoginKit: d98498c598ec09de657385a9349a1f21119b7f86 + Firebase: 26223c695fe322633274198cb19dca8cb7e54416 + firebase_analytics: c9b8ddc8e864e45cd70761c5d972bd11c83574ab + firebase_auth: 9f6491ea8e44570323361ae713a2ae3175b3f21a + firebase_core: e6cbb0d1f7091edfcae31559e58224bfc1e455dc + firebase_messaging: 9c746d6c52bb05764e73bbe745d0d698e5afb695 + FirebaseAnalytics: 2580c2d62535ae7b644143d48941fcc239ea897a + FirebaseAuth: c224a0cf1afa0949bd5c7bfcf154b4f5ce8ddef2 + FirebaseCore: 4d3c72622ce0e2106aaa07bb4b2935ba2c370972 + FirebaseCoreDiagnostics: d50e11039e5984d92c8a512be2395f13df747350 + FirebaseInstallations: 5e777e6640fa060405cc7632447b6c5ca5af4742 + FirebaseInstanceID: 53140c03b9f6136f890d7901399f85a4c90ab2d0 + FirebaseMessaging: 68d1bcb14880189558a8ae57167abe0b7e417232 + Flutter: 434fef37c0980e73bb6479ef766c45957d4b510c + flutter_facebook_auth: 4b170c07b7fce791497093fcc3f134fb215f3f07 + flutter_local_notifications: 0c0b1ae97e741e1521e4c1629a459d04b9aec743 flutter_secure_storage: 7953c38a04c3fdbb00571bcd87d8e3b5ceb9daec FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a google_sign_in: 6bd214b9c154f881422f5fe27b66aaa7bbd580cc - GoogleAppMeasurement: 966e88df9d19c15715137bb2ddaf52373f111436 - GoogleDataTransport: f56af7caa4ed338dc8e138a5d7c5973e66440833 + GoogleAppMeasurement: 8d3c0aeede16ab7764144b5a4ca8e1d4323841b7 + GoogleDataTransport: 116c84c4bdeb76be2a7a46de51244368f9794eab GoogleSignIn: 7137d297ddc022a7e0aa4619c86d72c909fa7213 - GoogleUtilities: 7f2f5a07f888cdb145101d6042bc4422f57e70b3 + GoogleUtilities: e1d9ed4e544fc32a93e00e721400cbc3f377200d GTMAppAuth: 197a8dabfea5d665224aa00d17f164fc2248dab9 GTMSessionFetcher: b3503b20a988c4e20cc189aa798fd18220133f52 - nanopb: 59317e09cf1f1a0af72f12af412d54edf52603fc + modal_progress_hud_nsn: f6fb744cd060653d66ed8f325360ef3650eb2fde + nanopb: 1bf24dd71191072e120b83dd02d08f3da0d65e53 package_info: 873975fc26034f0b863a300ad47e7f1ac6c7ec62 path_provider: abfe2b5c733d04e238b0d8691db0cfd63a27a93c PromisesObjC: 3113f7f76903778cf4a0586bd1ab89329a0b7b97 - Protobuf: 0cde852566359049847168e51bd1c690e0f70056 - Purchases: d8a798c9c7552fe66b550bf314a143e94ffa70c8 - purchases_flutter: c1ef4056da1346795a708bdefce81e0a56e8134f - PurchasesCoreSwift: ea4eabae180416e580ac60366f41aa1fefec0693 - PurchasesHybridCommon: d9bfb34309db4c9ba82a6f7f3a6275c13befdca7 + Purchases: 520fdb59140fed96932a30d02a3ec04858cb541c + purchases_flutter: 05472ba84c83f05a138a3a657f1013f5f7143539 + PurchasesCoreSwift: 31c2a3d7394432abbe64d46f0933835de0b33033 + PurchasesHybridCommon: 013c8072b73e752a206779747e88c068fbf999ec shared_preferences: af6bfa751691cdc24be3045c43ec037377ada40d smartlook: bda0b1561935a02ef0fea5448258d5ac75027859 sqflite: 6d358c025f5b867b29ed92fc697fd34924e11904 video_player: 9cc823b1d9da7e8427ee591e8438bfbcde500e6e - wakelock: bfc7955c418d0db797614075aabbc58a39ab5107 - webview_flutter: d2b4d6c66968ad042ad94cbb791f5b72b4678a96 + wakelock: b0843b2479edbf6504d8d262c2959446f35373aa + webview_flutter: 9f491a9b5a66f2573946a389b2677987b0ff8c0b -PODFILE CHECKSUM: ffdd26129895d158b3c89ac44e19a7e054386b90 +PODFILE CHECKSUM: f10c0438b63bc24e6bbc207956dc27d16c4408f2 -COCOAPODS: 1.10.0 +COCOAPODS: 1.10.1 diff --git a/lib/animations/test_progress_animation.dart b/lib/animations/test_progress_animation.dart index f144723..1aa3cb5 100644 --- a/lib/animations/test_progress_animation.dart +++ b/lib/animations/test_progress_animation.dart @@ -2,10 +2,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class TestProgress extends AnimatedWidget { - TestProgress({ - Key key, - @required Animation animation, + Key? key, + required Animation animation, }) : super(key: key, listenable: animation); @override @@ -15,14 +14,14 @@ class TestProgress extends AnimatedWidget { return Transform.scale( alignment: Alignment.center, scale: animation.value, - origin: Offset(-5,0), + origin: Offset(-5, 0), child: Container( - alignment: Alignment.center, - padding: EdgeInsets.only(left: 0), - child: Icon(Icons.star, color: Colors.yellow,) - ), + alignment: Alignment.center, + padding: EdgeInsets.only(left: 0), + child: Icon( + Icons.star, + color: Colors.yellow, + )), ); } - - -} \ No newline at end of file +} diff --git a/lib/bloc/account/account_bloc.dart b/lib/bloc/account/account_bloc.dart index 78d126a..b4d8920 100644 --- a/lib/bloc/account/account_bloc.dart +++ b/lib/bloc/account/account_bloc.dart @@ -16,9 +16,9 @@ class AccountBloc extends Bloc { final CustomerRepository customerRepository; bool loggedIn = false; int traineeId = 0; - AccountBloc({this.customerRepository}) : super(AccountInitial()) { + AccountBloc({required this.customerRepository}) : super(AccountInitial()) { if (Cache().userLoggedIn != null) { - customerRepository.customer = Cache().userLoggedIn; + customerRepository.customer = Cache().userLoggedIn!; loggedIn = true; } } @@ -74,7 +74,7 @@ class AccountBloc extends Bloc { yield AccountLoggedIn(); } else if (event is AccountLogout) { await Cache().logout(); - customerRepository.customer = null; + //customerRepository.customer = null; customerRepository.emptyTrainees(); loggedIn = false; yield AccountLoggedOut(); @@ -85,7 +85,7 @@ class AccountBloc extends Bloc { } else if (event is AccountSelectTrainee) { yield AccountLoading(); customerRepository.setTrainee(event.traineeId); - Cache().setTrainee(customerRepository.getTraineeById(event.traineeId)); + Cache().setTrainee(customerRepository.getTraineeById(event.traineeId)!); ExerciseRepository exerciseRepository = ExerciseRepository(); await exerciseRepository.getExercisesByCustomer(event.traineeId); this.traineeId = event.traineeId; diff --git a/lib/bloc/account/account_event.dart b/lib/bloc/account/account_event.dart index 5259cfd..616884b 100644 --- a/lib/bloc/account/account_event.dart +++ b/lib/bloc/account/account_event.dart @@ -9,37 +9,21 @@ abstract class AccountEvent extends Equatable { } class AccountChangeCustomer extends AccountEvent { - final Customer customer; - - const AccountChangeCustomer({this.customer}); - - @override - List get props => [customer]; + const AccountChangeCustomer(); } class AccountLogout extends AccountEvent { - final Customer customer; - - const AccountLogout({this.customer}); - - @override - List get props => [customer]; - + const AccountLogout(); } class AccountLogin extends AccountEvent { - final Customer customer; - - const AccountLogin({this.customer}); - - @override - List get props => [customer]; + const AccountLogin(); } class AccountLogInFinished extends AccountEvent { final Customer customer; - const AccountLogInFinished({this.customer}); + const AccountLogInFinished({required this.customer}); @override List get props => [customer]; @@ -51,8 +35,8 @@ class AccountGetTrainees extends AccountEvent { class AccountSelectTrainee extends AccountEvent { final int traineeId; - const AccountSelectTrainee({this.traineeId}); + const AccountSelectTrainee({required this.traineeId}); @override List get props => [traineeId]; -} \ No newline at end of file +} diff --git a/lib/bloc/account/account_state.dart b/lib/bloc/account/account_state.dart index 8fa858d..a968c1e 100644 --- a/lib/bloc/account/account_state.dart +++ b/lib/bloc/account/account_state.dart @@ -29,7 +29,7 @@ class AccountLoggedIn extends AccountState { class AccountError extends AccountState { final String message; - const AccountError({this.message}); + const AccountError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/body_development/body_development_bloc.dart b/lib/bloc/body_development/body_development_bloc.dart index 792358e..67054b5 100644 --- a/lib/bloc/body_development/body_development_bloc.dart +++ b/lib/bloc/body_development/body_development_bloc.dart @@ -13,14 +13,14 @@ class BodyDevelopmentBloc extends Bloc radarTicks = List(); - List radarFeatures = List(); - List> radarData = List(); + List radarTicks = []; + List radarFeatures = []; + List> radarData = []; @override - BodyDevelopmentBloc({this.workoutTreeRepository}): super(BodyDevelopmentInitial()); + BodyDevelopmentBloc({required this.workoutTreeRepository}) : super(BodyDevelopmentInitial()); - Future getData() async{ + Future getData() async { radarTicks = [20, 40, 60, 80, 100]; radarFeatures = ["Mell", "Bicepsz", "Tricepsz", "Hát", "Váll"]; radarData = [ diff --git a/lib/bloc/body_development/body_development_state.dart b/lib/bloc/body_development/body_development_state.dart index 8f5b881..3f4e370 100644 --- a/lib/bloc/body_development/body_development_state.dart +++ b/lib/bloc/body_development/body_development_state.dart @@ -22,9 +22,8 @@ class BodyDevelopmentReady extends BodyDevelopmentState { class BodyDevelopmentError extends BodyDevelopmentState { final String message; - const BodyDevelopmentError({this.message}); + const BodyDevelopmentError({required this.message}); @override List get props => [message]; } - diff --git a/lib/bloc/body_type/bodytype_bloc.dart b/lib/bloc/body_type/bodytype_bloc.dart index 482f94a..0212cbb 100644 --- a/lib/bloc/body_type/bodytype_bloc.dart +++ b/lib/bloc/body_type/bodytype_bloc.dart @@ -15,11 +15,11 @@ part 'bodytype_state.dart'; class BodytypeBloc extends Bloc { static const int numberQuestions = 22; final CustomerRepository repository; - final List questions = List(); - final List answers = List(); - final weights = List.generate(numberQuestions, (i) => List(3), growable: false); + final List questions = []; + final List answers = []; + final weights = List.generate(numberQuestions, (i) => []..length = 3, growable: false); - BodytypeBloc({this.repository}) : super(BodytypeInitial()) { + BodytypeBloc({required this.repository}) : super(BodytypeInitial()) { questions.add("1. Basicly I am skinny and bonny"); questions.add("2. question"); questions.add("3. question"); @@ -71,15 +71,14 @@ class BodytypeBloc extends Bloc { weights[21] = [7, 3, 0]; final double value = repository.getCustomerPropertyValue(PropertyEnum.Ectomorph.toStr()); - if (value != null) { - _ecto = value.toInt(); - _mezo = repository.getCustomerPropertyValue(PropertyEnum.Mesomorph.toStr()).toInt(); - _endo = repository.getCustomerPropertyValue(PropertyEnum.Endomorph.toStr()).toInt(); - print("** Init ecto: " + _ecto.toString() + " mezo: " + _mezo.toString() + " endo: " + _endo.toString()); - if (_ecto > 0 && _mezo > 0 && _endo > 0) { - calculateBodyType(init: true); - origBodyTypeValue = bodyTypeValue; - } + + _ecto = value.toInt(); + _mezo = repository.getCustomerPropertyValue(PropertyEnum.Mesomorph.toStr()).toInt(); + _endo = repository.getCustomerPropertyValue(PropertyEnum.Endomorph.toStr()).toInt(); + print("** Init ecto: " + _ecto.toString() + " mezo: " + _mezo.toString() + " endo: " + _endo.toString()); + if (_ecto > 0 && _mezo > 0 && _endo > 0) { + calculateBodyType(init: true); + origBodyTypeValue = bodyTypeValue; } } @@ -135,13 +134,13 @@ class BodytypeBloc extends Bloc { Future savePropertyDB(String name, double value) async { final now = DateTime.now(); - Property property = repository.propertyRepository.getPropertyByName(name); + Property? property = repository.propertyRepository.getPropertyByName(name); if (property != null) { int propertyId = property.propertyId; - CustomerProperty customerProperty = repository.getCustomerProperty(name); + CustomerProperty? customerProperty = repository.getCustomerProperty(name); if (customerProperty == null || customerProperty.customerPropertyId == null) { customerProperty = - CustomerProperty(customerId: Cache().userLoggedIn.customerId, propertyId: propertyId, propertyValue: value, dateAdd: now); + CustomerProperty(customerId: Cache().userLoggedIn!.customerId!, propertyId: propertyId, propertyValue: value, dateAdd: now); CustomerProperty newProperty = await CustomerApi().addProperty(customerProperty); repository.setCustomerProperty(name, value, id: newProperty.customerPropertyId); diff --git a/lib/bloc/body_type/bodytype_event.dart b/lib/bloc/body_type/bodytype_event.dart index ba94362..825011a 100644 --- a/lib/bloc/body_type/bodytype_event.dart +++ b/lib/bloc/body_type/bodytype_event.dart @@ -17,7 +17,7 @@ class BodytypeSave extends BodytypeEvent { class BodytypeClick extends BodytypeEvent { final int value; - const BodytypeClick({this.value}); + const BodytypeClick({required this.value}); @override List get props => [value]; diff --git a/lib/bloc/body_type/bodytype_state.dart b/lib/bloc/body_type/bodytype_state.dart index 4bd18e9..56085b4 100644 --- a/lib/bloc/body_type/bodytype_state.dart +++ b/lib/bloc/body_type/bodytype_state.dart @@ -25,7 +25,7 @@ class BodytypeFinished extends BodytypeState { class BodytypeError extends BodytypeState { final String error; - const BodytypeError({this.error}); + const BodytypeError({required this.error}); @override List get props => [error]; diff --git a/lib/bloc/custom_exercise_form_bloc.dart b/lib/bloc/custom_exercise_form_bloc.dart deleted file mode 100644 index c0755dd..0000000 --- a/lib/bloc/custom_exercise_form_bloc.dart +++ /dev/null @@ -1,127 +0,0 @@ -import 'dart:math'; -import 'package:aitrainer_app/repository/exercise_repository.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; - -class CustomExerciseFormBloc extends FormBloc { - final ExerciseRepository exerciseRepository; - bool loading = false; - final quantityField = TextFieldBloc( - validators: [ - FieldBlocValidators.required, - ], - ); - - final unitQuantityField = TextFieldBloc( - validators: [ - FieldBlocValidators.required, - ], - ); - - //1RM calculated Fields - final rmWendlerField = TextFieldBloc( - initialValue: "0", - ); - final rmMayhewField = TextFieldBloc(initialValue: "0"); - final rmOconnerField = TextFieldBloc(initialValue: "0"); - final rmWathenField = TextFieldBloc(initialValue: "0"); - final rmAverageField = TextFieldBloc(initialValue: "0"); - final rm90Field = TextFieldBloc(initialValue: "0"); - final rm80Field = TextFieldBloc(initialValue: "0"); - final rm75Field = TextFieldBloc(initialValue: "0"); - final rm75WendlerField = TextFieldBloc(initialValue: "0"); - final rm75OconnorField = TextFieldBloc(initialValue: "0"); - final rm70Field = TextFieldBloc(initialValue: "0"); - final rm60Field = TextFieldBloc(initialValue: "0"); - final rm50Field = TextFieldBloc(initialValue: "0"); - - CustomExerciseFormBloc({this.exerciseRepository}) { - addFieldBlocs(fieldBlocs: [ - quantityField, - unitQuantityField, - rmWendlerField, - rmMayhewField, - rmOconnerField, - rmWathenField, - rmAverageField, - rm90Field, - rm80Field, - rm70Field, - rm75Field, - rm75WendlerField, - rm75OconnorField, - rm60Field, - rm50Field - ]); - - quantityField.onValueChanges(onData: (previous, current) async* { - exerciseRepository.setQuantity(current.valueToDouble); - calculate1RM(); - }); - - unitQuantityField.onValueChanges(onData: (previous, current) async* { - exerciseRepository.setUnitQuantity(current.valueToDouble); - calculate1RM(); - }); - } - - @override - void onSubmitting() async { - try { - loading = true; - emitLoading(progress: 30); - // Emit either Loaded or Error - - emitSuccess(canSubmitAgain: false); - loading = false; - } on Exception catch (ex) { - emitFailure(failureResponse: ex.toString()); - } - } - - void calculate1RM() { - double weight = exerciseRepository.exercise.unitQuantity; - double repeat = exerciseRepository.exercise.quantity; - if (weight == 0 || repeat == 0) { - return; - } - exerciseRepository.rmWendler = weight * repeat * 0.0333 + weight; - rmWendlerField.updateValue(exerciseRepository.rmWendler.toStringAsFixed(1)); - exerciseRepository.rmOconner = weight * (1 + repeat / 40); - rmOconnerField.updateValue(exerciseRepository.rmOconner.toStringAsFixed(1)); - exerciseRepository.rmMayhew = 100 * weight / (52.2 + 41.9 * pow(e, -0.055 * repeat)); - rmMayhewField.updateValue(exerciseRepository.rmMayhew.toStringAsFixed(1)); - exerciseRepository.rmWathen = 100 * weight / (48.8 + 53.8 * pow(e, -0.075 * repeat)); - rmWathenField.updateValue(exerciseRepository.rmWathen.toStringAsFixed(1)); - double average = (exerciseRepository.rmWendler + exerciseRepository.rmOconner) / 2; - rmAverageField.updateValue(average.toStringAsFixed(1)); - rm90Field.updateValue((average * 0.9).toStringAsFixed(1)); - rm80Field.updateValue((average * 0.8).toStringAsFixed(1)); - rm75Field.updateValue((average * 0.75).toStringAsFixed(1)); - rm75OconnorField.updateValue((exerciseRepository.rmOconner * 0.75).toStringAsFixed(1)); - rm75WendlerField.updateValue((exerciseRepository.rmWendler * 0.75).toStringAsFixed(1)); - rm70Field.updateValue((average * 0.7).toStringAsFixed(1)); - rm60Field.updateValue((average * 0.6).toStringAsFixed(1)); - rm50Field.updateValue((average * 0.5).toStringAsFixed(1)); - } - - //@override - Future close() { - quantityField.close(); - unitQuantityField.close(); - - rmWendlerField.close(); - rmMayhewField.close(); - rmOconnerField.close(); - rmWathenField.close(); - rmAverageField.close(); - rm90Field.close(); - rm80Field.close(); - rm75WendlerField.close(); - rm75OconnorField.close(); - rm75Field.close(); - rm70Field.close(); - rm60Field.close(); - rm50Field.close(); - return super.close(); - } -} diff --git a/lib/bloc/customer_change/customer_change_bloc.dart b/lib/bloc/customer_change/customer_change_bloc.dart index fd9b401..f9b73d6 100644 --- a/lib/bloc/customer_change/customer_change_bloc.dart +++ b/lib/bloc/customer_change/customer_change_bloc.dart @@ -14,14 +14,13 @@ part 'customer_change_state.dart'; class CustomerChangeBloc extends Bloc with Trans { final CustomerRepository customerRepository; - final BuildContext context; bool visiblePassword = false; - int year = 1990; + int? year = 1990; double weight = 60; double height = 170; - CustomerChangeBloc({this.customerRepository, this.context}) : super(CustomerChangeInitial()) { + CustomerChangeBloc({required this.customerRepository}) : super(CustomerChangeInitial()) { year = this.customerRepository.customer.birthYear; - if (year == 0) { + if (year == null || year == 0) { year = 1990; } weight = this.customerRepository.getWeight() == 0 ? 60 : this.customerRepository.getWeight(); @@ -102,23 +101,23 @@ class CustomerChangeBloc extends Bloc (nameValidation(customerRepository.customer.name) == null); */ } - String emailValidation(String email) { - String message = Common.emailValidation(email); + String? emailValidation(String email) { + String? message = Common.emailValidation(email); if (message != null) { message = t(message); } return message; } - String passwordValidation(String value) { - String message = Common.passwordValidation(value); + String? passwordValidation(String value) { + String? message = Common.passwordValidation(value); if (message != null) { message = t(message); } return message; } - String nameValidation(String value) { + String? nameValidation(String? value) { if (value == null || value.length == 0) { return t("Name too short"); } diff --git a/lib/bloc/customer_change/customer_change_event.dart b/lib/bloc/customer_change/customer_change_event.dart index ec3d7f4..0a0a2a2 100644 --- a/lib/bloc/customer_change/customer_change_event.dart +++ b/lib/bloc/customer_change/customer_change_event.dart @@ -9,7 +9,7 @@ abstract class CustomerChangeEvent extends Equatable { class CustomerGoalChange extends CustomerChangeEvent { final String goal; - const CustomerGoalChange({this.goal}); + const CustomerGoalChange({required this.goal}); @override List get props => [goal]; @@ -17,7 +17,7 @@ class CustomerGoalChange extends CustomerChangeEvent { class CustomerFitnessChange extends CustomerChangeEvent { final String fitness; - const CustomerFitnessChange({this.fitness}); + const CustomerFitnessChange({required this.fitness}); @override List get props => [fitness]; @@ -25,7 +25,7 @@ class CustomerFitnessChange extends CustomerChangeEvent { class CustomerBodyTypeChange extends CustomerChangeEvent { final String bodyType; - const CustomerBodyTypeChange({this.bodyType}); + const CustomerBodyTypeChange({required this.bodyType}); @override List get props => [bodyType]; @@ -33,7 +33,7 @@ class CustomerBodyTypeChange extends CustomerChangeEvent { class CustomerBirthYearChange extends CustomerChangeEvent { final int year; - const CustomerBirthYearChange({this.year}); + const CustomerBirthYearChange({required this.year}); @override List get props => [year]; @@ -41,7 +41,7 @@ class CustomerBirthYearChange extends CustomerChangeEvent { class CustomerWeightChange extends CustomerChangeEvent { final int weight; - const CustomerWeightChange({this.weight}); + const CustomerWeightChange({required this.weight}); @override List get props => [weight]; @@ -49,7 +49,7 @@ class CustomerWeightChange extends CustomerChangeEvent { class CustomerHeightChange extends CustomerChangeEvent { final int height; - const CustomerHeightChange({this.height}); + const CustomerHeightChange({required this.height}); @override List get props => [height]; @@ -57,7 +57,7 @@ class CustomerHeightChange extends CustomerChangeEvent { class CustomerGenderChange extends CustomerChangeEvent { final int gender; - const CustomerGenderChange({this.gender}); + const CustomerGenderChange({required this.gender}); @override List get props => [gender]; @@ -65,7 +65,7 @@ class CustomerGenderChange extends CustomerChangeEvent { class CustomerEmailChange extends CustomerChangeEvent { final String email; - const CustomerEmailChange({this.email}); + const CustomerEmailChange({required this.email}); @override List get props => [email]; @@ -73,7 +73,7 @@ class CustomerEmailChange extends CustomerChangeEvent { class CustomerFirstNameChange extends CustomerChangeEvent { final String firstName; - const CustomerFirstNameChange({this.firstName}); + const CustomerFirstNameChange({required this.firstName}); @override List get props => [firstName]; @@ -81,7 +81,7 @@ class CustomerFirstNameChange extends CustomerChangeEvent { class CustomerNameChange extends CustomerChangeEvent { final String name; - const CustomerNameChange({this.name}); + const CustomerNameChange({required this.name}); @override List get props => [name]; @@ -89,7 +89,7 @@ class CustomerNameChange extends CustomerChangeEvent { class CustomerPasswordChange extends CustomerChangeEvent { final String password; - const CustomerPasswordChange({this.password}); + const CustomerPasswordChange({required this.password}); @override List get props => [password]; diff --git a/lib/bloc/customer_change/customer_change_state.dart b/lib/bloc/customer_change/customer_change_state.dart index 461f66d..149cad2 100644 --- a/lib/bloc/customer_change/customer_change_state.dart +++ b/lib/bloc/customer_change/customer_change_state.dart @@ -29,7 +29,7 @@ class CustomerSaveSuccess extends CustomerChangeState { class CustomerSaveError extends CustomerChangeState { final String message; - const CustomerSaveError({this.message}); + const CustomerSaveError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/customer_exercise_device/customer_exercise_device_bloc.dart b/lib/bloc/customer_exercise_device/customer_exercise_device_bloc.dart index 0dfdfc4..ae71d51 100644 --- a/lib/bloc/customer_exercise_device/customer_exercise_device_bloc.dart +++ b/lib/bloc/customer_exercise_device/customer_exercise_device_bloc.dart @@ -13,11 +13,11 @@ part 'customer_exercise_device_state.dart'; class CustomerExerciseDeviceBloc extends Bloc { final CustomerExerciseDeviceRepository repository; - final List devices; + final List? devices; - CustomerExerciseDeviceBloc({this.repository, this.devices}) : super(CustomerExerciseDeviceInitial()) { + CustomerExerciseDeviceBloc({required this.repository, required this.devices}) : super(CustomerExerciseDeviceInitial()) { if (repository.getDevices().isEmpty) { - repository.setDevices(Cache().getCustomerDevices()); + repository.setDevices(Cache().getCustomerDevices()!); } Track().track(TrackingEvent.exercise_device); } diff --git a/lib/bloc/customer_exercise_device/customer_exercise_device_event.dart b/lib/bloc/customer_exercise_device/customer_exercise_device_event.dart index cd4c90c..1015d36 100644 --- a/lib/bloc/customer_exercise_device/customer_exercise_device_event.dart +++ b/lib/bloc/customer_exercise_device/customer_exercise_device_event.dart @@ -13,7 +13,7 @@ class CustomerExerciseDeviceLoad extends CustomerExerciseDeviceEvent { class CustomerExerciseDeviceAdd extends CustomerExerciseDeviceEvent { final ExerciseDevice device; - const CustomerExerciseDeviceAdd({this.device}); + const CustomerExerciseDeviceAdd({required this.device}); @override List get props => [device]; @@ -21,7 +21,7 @@ class CustomerExerciseDeviceAdd extends CustomerExerciseDeviceEvent { class CustomerExerciseDeviceRemove extends CustomerExerciseDeviceEvent { final ExerciseDevice device; - const CustomerExerciseDeviceRemove({this.device}); + const CustomerExerciseDeviceRemove({required this.device}); @override List get props => [device]; diff --git a/lib/bloc/customer_exercise_device/customer_exercise_device_state.dart b/lib/bloc/customer_exercise_device/customer_exercise_device_state.dart index b958e24..4b42a8c 100644 --- a/lib/bloc/customer_exercise_device/customer_exercise_device_state.dart +++ b/lib/bloc/customer_exercise_device/customer_exercise_device_state.dart @@ -21,7 +21,7 @@ class CustomerExerciseDeviceReady extends CustomerExerciseDeviceState { class CustomerExerciseDeviceError extends CustomerExerciseDeviceState { final String message; - const CustomerExerciseDeviceError({this.message}); + const CustomerExerciseDeviceError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/development_by_muscle/development_by_muscle_bloc.dart b/lib/bloc/development_by_muscle/development_by_muscle_bloc.dart index 3101f07..d718565 100644 --- a/lib/bloc/development_by_muscle/development_by_muscle_bloc.dart +++ b/lib/bloc/development_by_muscle/development_by_muscle_bloc.dart @@ -13,11 +13,10 @@ import 'package:aitrainer_app/util/common.dart'; import 'package:aitrainer_app/util/enums.dart'; import 'package:aitrainer_app/util/group_data.dart'; import 'package:aitrainer_app/util/track.dart'; - +import 'package:intl/intl.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:meta/meta.dart'; import 'package:fl_chart/fl_chart.dart'; @@ -36,35 +35,35 @@ class DiagramType { */ class GroupDate extends GroupData with Calculate, Common { - final List inputList; - final List outputList; + final List inputList; + final List outputList; - String _origDatePart; - int _origExerciseTypeId; - Exercise _origExercise; + String? _origDatePart; + late int _origExerciseTypeId; + late Exercise _origExercise; - double _sumQuantity; - double _maxQuantity; - int _countExercises; + late double _sumQuantity; + late double _maxQuantity; + late int _countExercises; - String diagramType; - String dateRate; + late String diagramType; + late String dateRate; - GroupDate({this.inputList, this.outputList}); + GroupDate({required this.inputList, required this.outputList}); double getQuantityByDate(Exercise exercise) { double sum = 0; if (this.diagramType == DiagramType.sumMass) { if (exercise.unitQuantity != null) { - sum = exercise.quantity * exercise.unitQuantity; + sum = exercise.quantity! * exercise.unitQuantity!; } else { - sum = exercise.quantity; + sum = exercise.quantity!; } } else if (this.diagramType == DiagramType.oneRepMax || this.diagramType == DiagramType.percent) { if (exercise.unitQuantity != null) { - sum = calculate1RM(exercise.quantity, exercise.unitQuantity); + sum = calculate1RM(exercise.quantity!, exercise.unitQuantity!); } else { - sum = exercise.quantity; + sum = exercise.quantity!; } } return sum; @@ -73,26 +72,26 @@ class GroupDate extends GroupData with Calculate, Common { @override void addTempData(Exercise exercise) { double newQuantity = getQuantityByDate(exercise); - _sumQuantity += newQuantity; + _sumQuantity = _sumQuantity + newQuantity; if (_maxQuantity < newQuantity) { _maxQuantity = newQuantity; } - _countExercises++; - _origDatePart = getDatePart(exercise.dateAdd, dateRate); - _origExerciseTypeId = exercise.exerciseTypeId; + _countExercises = _countExercises + 1; + _origDatePart = getDatePart(exercise.dateAdd!, dateRate); + _origExerciseTypeId = exercise.exerciseTypeId!; _origExercise = exercise; } @override bool checkNewType(Exercise exercise) { - String exerciseDatePart = getDatePart(exercise.dateAdd, dateRate); - return _origDatePart != exerciseDatePart || _origExerciseTypeId != exercise.exerciseTypeId; + String exerciseDatePart = getDatePart(exercise.dateAdd!, dateRate); + return _origDatePart == null || _origDatePart != exerciseDatePart || _origExerciseTypeId != exercise.exerciseTypeId; } @override void iteration() { this.resetTemp(); - Exercise tempExercise; + Exercise? tempExercise; inputList.forEach((element) { tempExercise = element; if (this.checkNewType(element)) { @@ -108,7 +107,7 @@ class GroupDate extends GroupData with Calculate, Common { } }); if (tempExercise != null) { - this.temp2Output(tempExercise); + this.temp2Output(tempExercise!); } } @@ -142,21 +141,21 @@ class GroupChart extends GroupData with Calculate { final List inputList; LinkedHashMap outputList = LinkedHashMap(); - int _origExerciseTypeId; - double _minData = 999999999999; - double _maxData = 0; - List _chartData; - double _basePercent; + int? _origExerciseTypeId; + late double _minData = 999999999999; + late double _maxData = 0; + late List _chartData; + late double _basePercent; String diagramType = DiagramType.sumMass; - GroupChart({this.inputList, this.outputList}); + GroupChart({required this.inputList, required this.outputList}); double getBasePercent(Exercise exercise) { if (exercise.unitQuantity != null) { - this._basePercent = calculate1RM(exercise.quantity, exercise.unitQuantity); + this._basePercent = calculate1RM(exercise.quantity!, exercise.unitQuantity!); } else { - this._basePercent = exercise.quantity; + this._basePercent = exercise.quantity!; } return this._basePercent; } @@ -166,13 +165,13 @@ class GroupChart extends GroupData with Calculate { if (diagramType == DiagramType.percent) { if (exercise.unitQuantity != null) { - double oneRepMax = calculate1RM(exercise.quantity, exercise.unitQuantity); + double oneRepMax = calculate1RM(exercise.quantity!, exercise.unitQuantity!); value = (oneRepMax / this._basePercent) * 100; } else { - value = (exercise.quantity / this._basePercent) * 100; + value = (exercise.quantity! / this._basePercent) * 100; } } else if (diagramType == DiagramType.oneRepMax || diagramType == DiagramType.sumMass) { - value = exercise.calculated; + value = exercise.calculated!; } return value; } @@ -188,22 +187,22 @@ class GroupChart extends GroupData with Calculate { _minData = diagramValue; } - BarChartGroupData data = BarChartGroupData(x: exercise.dateAdd.millisecondsSinceEpoch, barRods: [ + BarChartGroupData data = BarChartGroupData(x: exercise.dateAdd!.millisecondsSinceEpoch, barRods: [ BarChartRodData(y: diagramValue, width: 12, colors: [Colors.lightBlue, Colors.lightBlueAccent]) ]); _chartData.add(data); - _origExerciseTypeId = exercise.exerciseTypeId; + _origExerciseTypeId = exercise.exerciseTypeId!; } @override bool checkNewType(Exercise exercise) { - return _origExerciseTypeId != exercise.exerciseTypeId; + return _origExerciseTypeId == null || _origExerciseTypeId != exercise.exerciseTypeId; } @override void iteration() { this.resetTemp(); - Exercise tempExercise; + Exercise? tempExercise; inputList.forEach((element) { tempExercise = element; @@ -222,7 +221,7 @@ class GroupChart extends GroupData with Calculate { } }); if (tempExercise != null) { - this.temp2Output(tempExercise); + this.temp2Output(tempExercise!); } } @@ -234,9 +233,9 @@ class GroupChart extends GroupData with Calculate { ChartDataExtended extended; if (outputList[_origExerciseTypeId] == null) { extended = ChartDataExtended(data: _chartData, interval: dInterval, gridInterval: gridInterval); - outputList[_origExerciseTypeId] = extended; + outputList[_origExerciseTypeId!] = extended; } else { - extended = outputList[_origExerciseTypeId]; + extended = outputList[_origExerciseTypeId]!; _chartData.forEach((element) { extended.data.add(element); }); @@ -247,7 +246,7 @@ class GroupChart extends GroupData with Calculate { void resetTemp() { _minData = 999999999999; _maxData = 0; - _chartData = List(); + _chartData = []; } } @@ -256,10 +255,10 @@ class ChartDataExtended { final double interval; final int gridInterval; - const ChartDataExtended({this.data, this.interval, this.gridInterval}); + const ChartDataExtended({required this.data, required this.interval, required this.gridInterval}); Map toJson() { - List listBarChartData = List(); + List listBarChartData = []; data.forEach((element) { element.barRods.forEach((rods) { var barChartData = { @@ -280,18 +279,19 @@ class ChartDataExtended { class DevelopmentByMuscleBloc extends Bloc with Calculate, Logging { final WorkoutTreeRepository workoutTreeRepository; + final ExerciseRepository exerciseRepository = ExerciseRepository(); LinkedHashMap listChartData = LinkedHashMap(); - List chartData; + late List chartData; String diagramType = DiagramType.sumMass; String dateRate = DateRate.daily; double basePercent = 0; @override - DevelopmentByMuscleBloc({this.workoutTreeRepository}) : super(DevelopmentByMuscleStateInitial()); + DevelopmentByMuscleBloc({required this.workoutTreeRepository}) : super(DevelopmentByMuscleStateInitial()); Future getData() async { - workoutTreeRepository.sortedTree = null; + workoutTreeRepository.sortedTree.clear(); workoutTreeRepository.sortByMuscleType(); workoutTreeRepository.sortedTree.forEach((key, value) { @@ -305,7 +305,7 @@ class DevelopmentByMuscleBloc extends Bloc exercises = exerciseRepository.getExerciseList(); + List? exercises = exerciseRepository.getExerciseList(); //print("-- Start calculate --- "); exercises = this.groupByDate(exercises); @@ -322,24 +322,25 @@ class DevelopmentByMuscleBloc extends Bloc groupByDate(List exercises) { - List groupedExercises = List(); + List groupByDate(List? exercises) { + List groupedExercises = []; + if (exercises != null) { + exercises = sort(exercises, false); + exercises.forEach((exercise) { + //trace("Date exercise " + exercise.toJsonDatePart().toString()); + }); - exercises = sort(exercises, false); - exercises.forEach((exercise) { - trace("Date exercise " + exercise.toJsonDatePart().toString()); - }); - - GroupDate groupDate = GroupDate(inputList: exercises, outputList: groupedExercises); - groupDate.dateRate = this.dateRate; - groupDate.diagramType = this.diagramType; - groupDate.iteration(); - groupedExercises = groupDate.outputList; + GroupDate groupDate = GroupDate(inputList: exercises, outputList: groupedExercises); + groupDate.dateRate = this.dateRate; + groupDate.diagramType = this.diagramType; + groupDate.iteration(); + groupedExercises = groupDate.outputList; + } /* groupedExercises.forEach((element) { print("Grouped " + element.toJsonDatePart().toString()); diff --git a/lib/bloc/development_by_muscle/development_by_muscle_event.dart b/lib/bloc/development_by_muscle/development_by_muscle_event.dart index 95c1111..dfe06d2 100644 --- a/lib/bloc/development_by_muscle/development_by_muscle_event.dart +++ b/lib/bloc/development_by_muscle/development_by_muscle_event.dart @@ -14,7 +14,7 @@ class DevelopmentByMuscleLoad extends DevelopmentByMuscleEvent { class DevelopmentByMuscleDateRateChange extends DevelopmentByMuscleEvent { final String dateRate; - const DevelopmentByMuscleDateRateChange({this.dateRate}); + const DevelopmentByMuscleDateRateChange({required this.dateRate}); @override List get props => [dateRate]; @@ -22,7 +22,7 @@ class DevelopmentByMuscleDateRateChange extends DevelopmentByMuscleEvent { class DevelopmentByMuscleDiagramTypeChange extends DevelopmentByMuscleEvent { final String diagramType; - const DevelopmentByMuscleDiagramTypeChange({this.diagramType}); + const DevelopmentByMuscleDiagramTypeChange({required this.diagramType}); @override List get props => [diagramType]; diff --git a/lib/bloc/development_by_muscle/development_by_muscle_state.dart b/lib/bloc/development_by_muscle/development_by_muscle_state.dart index d2241af..4b77d62 100644 --- a/lib/bloc/development_by_muscle/development_by_muscle_state.dart +++ b/lib/bloc/development_by_muscle/development_by_muscle_state.dart @@ -1,7 +1,7 @@ part of 'development_by_muscle_bloc.dart'; @immutable -abstract class DevelopmentByMuscleState extends Equatable{ +abstract class DevelopmentByMuscleState extends Equatable { const DevelopmentByMuscleState(); @override @@ -20,10 +20,9 @@ class DevelopmentByMuscleReadyState extends DevelopmentByMuscleState { const DevelopmentByMuscleReadyState(); } - class DevelopmentByMuscleErrorState extends DevelopmentByMuscleState { final String message; - const DevelopmentByMuscleErrorState({this.message}); + const DevelopmentByMuscleErrorState({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/development_sizes/development_sizes_bloc.dart b/lib/bloc/development_sizes/development_sizes_bloc.dart index 88cc1b7..5fea5ed 100644 --- a/lib/bloc/development_sizes/development_sizes_bloc.dart +++ b/lib/bloc/development_sizes/development_sizes_bloc.dart @@ -10,11 +10,11 @@ part 'development_sizes_state.dart'; class DevelopmentSizesBloc extends Bloc { final CustomerRepository customerRepository; - DevelopmentSizesBloc({this.customerRepository}) : super(DevelopmentSizesInitial()) { - isMan = Cache().userLoggedIn.sex == "m"; + DevelopmentSizesBloc({required this.customerRepository}) : super(DevelopmentSizesInitial()) { + isMan = Cache().userLoggedIn!.sex == "m"; } - bool isMan; + late bool isMan; @override Stream mapEventToState( diff --git a/lib/bloc/development_sizes/development_sizes_state.dart b/lib/bloc/development_sizes/development_sizes_state.dart index a91b6a4..c617da1 100644 --- a/lib/bloc/development_sizes/development_sizes_state.dart +++ b/lib/bloc/development_sizes/development_sizes_state.dart @@ -21,7 +21,7 @@ class DevelopmentSizesReady extends DevelopmentSizesState { class DevelopmentSizesError extends DevelopmentSizesState { final String message; - const DevelopmentSizesError({this.message}); + const DevelopmentSizesError({required this.message}); @override List get props => [this.message]; diff --git a/lib/bloc/exercise_control/exercise_control_bloc.dart b/lib/bloc/exercise_control/exercise_control_bloc.dart index 1977d65..1daa9a6 100644 --- a/lib/bloc/exercise_control/exercise_control_bloc.dart +++ b/lib/bloc/exercise_control/exercise_control_bloc.dart @@ -15,23 +15,24 @@ class ExerciseControlBloc extends Bloc get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart b/lib/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart index c8c1d98..3311622 100644 --- a/lib/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart +++ b/lib/bloc/exercise_execute_plan/exercise_execute_plan_bloc.dart @@ -14,16 +14,17 @@ part 'exercise_execute_plan_state.dart'; class ExerciseExecutePlanBloc extends Bloc { final WorkoutTreeRepository menuTreeRepository; final ExercisePlanRepository exercisePlanRepository = ExercisePlanRepository(); - int customerId; + int? customerId; int selectedNumber = 0; + @override - ExerciseExecutePlanBloc({this.menuTreeRepository}) : super(ExerciseByPlanStateInitial()); + ExerciseExecutePlanBloc({required this.menuTreeRepository}) : super(ExerciseByPlanStateInitial()); Future getData() async { - exercisePlanRepository.setCustomerId(customerId); + exercisePlanRepository.setCustomerId(customerId!); await exercisePlanRepository.getLastExercisePlan(); await exercisePlanRepository.getExercisePlanDetails(); - menuTreeRepository.sortedTree = null; + menuTreeRepository.sortedTree.clear(); menuTreeRepository.sortByMuscleType(); menuTreeRepository.sortedTree.forEach((key, value) { diff --git a/lib/bloc/exercise_execute_plan/exercise_execute_plan_event.dart b/lib/bloc/exercise_execute_plan/exercise_execute_plan_event.dart index b50a2c9..ff8e83a 100644 --- a/lib/bloc/exercise_execute_plan/exercise_execute_plan_event.dart +++ b/lib/bloc/exercise_execute_plan/exercise_execute_plan_event.dart @@ -10,7 +10,7 @@ abstract class ExerciseExecutePlanEvent extends Equatable { class AddExerciseByPlanEvent extends ExerciseExecutePlanEvent { final ExerciseType exerciseType; - const AddExerciseByPlanEvent({this.exerciseType}); + const AddExerciseByPlanEvent({required this.exerciseType}); @override List get props => [exerciseType]; diff --git a/lib/bloc/exercise_execute_plan/exercise_execute_plan_state.dart b/lib/bloc/exercise_execute_plan/exercise_execute_plan_state.dart index cf8e919..3ecbf68 100644 --- a/lib/bloc/exercise_execute_plan/exercise_execute_plan_state.dart +++ b/lib/bloc/exercise_execute_plan/exercise_execute_plan_state.dart @@ -24,8 +24,8 @@ class ExerciseByPlanReady extends ExerciseExecutePlanState { // error splash screen class ExerciseByPlanError extends ExerciseExecutePlanState { final String message; - const ExerciseByPlanError({this.message}); + const ExerciseByPlanError({required this.message}); @override List get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_bloc.dart b/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_bloc.dart index 8bc3cc0..cf48547 100644 --- a/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_bloc.dart +++ b/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_bloc.dart @@ -22,30 +22,35 @@ class ExerciseExecutePlanAddBloc extends Bloc get props => [quantity]; @@ -22,7 +22,7 @@ class ExerciseExecutePlanAddChangeQuantity extends ExerciseExecutePlanAddEvent { class ExerciseExecutePlanAddChangeUnitQuantity extends ExerciseExecutePlanAddEvent { final double quantity; - const ExerciseExecutePlanAddChangeUnitQuantity({this.quantity}); + const ExerciseExecutePlanAddChangeUnitQuantity({required this.quantity}); @override List get props => [quantity]; diff --git a/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_state.dart b/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_state.dart index 576b47c..3401da1 100644 --- a/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_state.dart +++ b/lib/bloc/exercise_execute_plan_add/exercise_execute_plan_add_state.dart @@ -24,8 +24,8 @@ class ExerciseExecutePlanAddReady extends ExerciseExecutePlanAddState { // error splash screen class ExerciseExecutePlanAddError extends ExerciseExecutePlanAddState { final String message; - const ExerciseExecutePlanAddError({this.message}); + const ExerciseExecutePlanAddError({required this.message}); @override List get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_log/exercise_log_bloc.dart b/lib/bloc/exercise_log/exercise_log_bloc.dart index 28a3244..b120125 100644 --- a/lib/bloc/exercise_log/exercise_log_bloc.dart +++ b/lib/bloc/exercise_log/exercise_log_bloc.dart @@ -15,7 +15,7 @@ part 'exercise_log_state.dart'; class ExerciseLogBloc extends Bloc { final ExerciseRepository exerciseRepository; @override - ExerciseLogBloc({this.exerciseRepository}) : super(ExerciseLogInitial()); + ExerciseLogBloc({required this.exerciseRepository}) : super(ExerciseLogInitial()); @override Stream mapEventToState(ExerciseLogEvent event) async* { @@ -27,7 +27,7 @@ class ExerciseLogBloc extends Bloc { yield ExerciseLogReady(); } else if (event is ExerciseLogDelete) { yield ExerciseLogLoading(); - exerciseRepository.exerciseList.remove(event.exercise); + exerciseRepository.exerciseList!.remove(event.exercise); await exerciseRepository.deleteExercise(event.exercise); Track().track(TrackingEvent.exercise_log_delete); yield ExerciseLogReady(); diff --git a/lib/bloc/exercise_log/exercise_log_event.dart b/lib/bloc/exercise_log/exercise_log_event.dart index bce4fb5..6bfdb1e 100644 --- a/lib/bloc/exercise_log/exercise_log_event.dart +++ b/lib/bloc/exercise_log/exercise_log_event.dart @@ -14,7 +14,7 @@ class ExerciseLogLoad extends ExerciseLogEvent { class ExerciseLogDelete extends ExerciseLogEvent { final Exercise exercise; - const ExerciseLogDelete({this.exercise}); + const ExerciseLogDelete({required this.exercise}); @override List get props => [exercise]; diff --git a/lib/bloc/exercise_log/exercise_log_state.dart b/lib/bloc/exercise_log/exercise_log_state.dart index 1ab2133..d97b338 100644 --- a/lib/bloc/exercise_log/exercise_log_state.dart +++ b/lib/bloc/exercise_log/exercise_log_state.dart @@ -22,9 +22,8 @@ class ExerciseLogReady extends ExerciseLogState { class ExerciseLogError extends ExerciseLogState { final String message; - const ExerciseLogError({this.message}); - + const ExerciseLogError({required this.message}); @override List get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_new/exercise_new_bloc.dart b/lib/bloc/exercise_new/exercise_new_bloc.dart index 0e28f3c..2398dce 100644 --- a/lib/bloc/exercise_new/exercise_new_bloc.dart +++ b/lib/bloc/exercise_new/exercise_new_bloc.dart @@ -1,4 +1,6 @@ import 'dart:async'; +import 'package:intl/intl.dart'; + import 'package:aitrainer_app/bloc/menu/menu_bloc.dart'; import 'package:aitrainer_app/model/cache.dart'; import 'package:aitrainer_app/model/exercise_type.dart'; @@ -12,7 +14,6 @@ import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/animation.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:meta/meta.dart'; import 'package:stop_watch_timer/stop_watch_timer.dart'; @@ -23,7 +24,7 @@ class ExerciseNewBloc extends Bloc with Logg final ExerciseRepository exerciseRepository; final CustomerRepository customerRepository; final MenuBloc menuBloc; - AnimationController bmiAnimationController; + late AnimationController bmiAnimationController; double quantity = 12; double unitQuantity = 30; double bmi = 0; @@ -35,11 +36,11 @@ class ExerciseNewBloc extends Bloc with Logg double bmiAngle = 0; double bmiTop = 0; double bmiLeft = 0; - double weight; - double height; + late double weight; + late double height; double bmrEnergy = 0; - int birthYear; - String fitnessLevel; + late int birthYear; + late String fitnessLevel; bool changedWeight = false; bool changedSizes = false; @@ -53,23 +54,24 @@ class ExerciseNewBloc extends Bloc with Logg final StopWatchTimer stopWatchTimer = StopWatchTimer( isLapHours: false, ); - int timerValue; + late int timerValue; @override - ExerciseNewBloc({this.exerciseRepository, this.menuBloc, this.customerRepository, ExerciseType exerciseType}) + ExerciseNewBloc( + {required this.exerciseRepository, required this.menuBloc, required this.customerRepository, required ExerciseType exerciseType}) : super(ExerciseNewInitial()) { exerciseRepository.exerciseType = exerciseType; exerciseRepository.setUnit(exerciseType.unit); exerciseRepository.setUnitQuantity(unitQuantity); exerciseRepository.setQuantity(quantity); - exerciseRepository.exercise.exercisePlanDetailId = 0; + exerciseRepository.exercise!.exercisePlanDetailId = 0; exerciseRepository.start = DateTime.now(); if (Cache().userLoggedIn != null) { - customerRepository.customer = Cache().userLoggedIn; + customerRepository.customer = Cache().userLoggedIn!; weight = customerRepository.customer.getProperty("Weight"); height = customerRepository.customer.getProperty("Height"); - birthYear = customerRepository.customer.birthYear; - fitnessLevel = customerRepository.customer.fitnessLevel; + birthYear = customerRepository.customer.birthYear!; + fitnessLevel = customerRepository.customer.fitnessLevel!; } if (exerciseType.unit == "second") { stopWatchTimer.rawTime.listen((value) => {timerValue = value, this.setQuantity((value / 1000).toDouble())}); @@ -151,7 +153,7 @@ class ExerciseNewBloc extends Bloc with Logg // exerciseRepository.initExercise(); menuBloc.add(MenuTreeDown(parent: 0)); Cache().initBadges(); - Track().track(TrackingEvent.exercise_new, eventValue: exerciseRepository.exerciseType.name); + Track().track(TrackingEvent.exercise_new, eventValue: exerciseRepository.exerciseType!.name); yield ExerciseNewSaved(); } else if (event is ExerciseNewBMIAnimate) { yield ExerciseNewLoading(); @@ -183,10 +185,10 @@ class ExerciseNewBloc extends Bloc with Logg if (customerRepository.customer.sex == "m") { //66.47 + ( 13.75 × tömeg kg-ban ) + ( 5.003 × magasság cm-ben ) − ( 6.755 × életkor évben kifejezve ) - bmr = 66.47 + (13.75 * weight) + (5.003 * height) - (6.755 * (year - customerRepository.customer.birthYear)); + bmr = 66.47 + (13.75 * weight) + (5.003 * height) - (6.755 * (year - customerRepository.customer.birthYear!)); } else { //BMR = 655.1 + ( 9.563 × ömeg kg-ban ) + ( 1.85 × magasság cm-ben) − ( 4.676 × életkor évben kifejezve ) - bmr = 655.1 + (9.563 * weight) + (1.85 * height) - (4.676 * (year - customerRepository.customer.birthYear)); + bmr = 655.1 + (9.563 * weight) + (1.85 * height) - (4.676 * (year - customerRepository.customer.birthYear!)); } bmrEnergy = bmr; diff --git a/lib/bloc/exercise_new/exercise_new_event.dart b/lib/bloc/exercise_new/exercise_new_event.dart index bdb01cf..e701619 100644 --- a/lib/bloc/exercise_new/exercise_new_event.dart +++ b/lib/bloc/exercise_new/exercise_new_event.dart @@ -14,7 +14,7 @@ class ExerciseNewLoad extends ExerciseNewEvent { class ExerciseNewQuantityChange extends ExerciseNewEvent { final double quantity; - const ExerciseNewQuantityChange({this.quantity}); + const ExerciseNewQuantityChange({required this.quantity}); @override List get props => [quantity]; @@ -22,7 +22,7 @@ class ExerciseNewQuantityChange extends ExerciseNewEvent { class ExerciseNewQuantityUnitChange extends ExerciseNewEvent { final double quantity; - const ExerciseNewQuantityUnitChange({this.quantity}); + const ExerciseNewQuantityUnitChange({required this.quantity}); @override List get props => [quantity]; @@ -30,21 +30,21 @@ class ExerciseNewQuantityUnitChange extends ExerciseNewEvent { class ExerciseNewBirthyearChange extends ExerciseNewEvent { final int value; - const ExerciseNewBirthyearChange({this.value}); + const ExerciseNewBirthyearChange({required this.value}); @override List get props => [value]; } class ExerciseNewWeightChange extends ExerciseNewEvent { final double value; - const ExerciseNewWeightChange({this.value}); + const ExerciseNewWeightChange({required this.value}); @override List get props => [value]; } class ExerciseNewHeightChange extends ExerciseNewEvent { final double value; - const ExerciseNewHeightChange({this.value}); + const ExerciseNewHeightChange({required this.value}); @override List get props => [value]; @@ -52,7 +52,7 @@ class ExerciseNewHeightChange extends ExerciseNewEvent { class ExerciseNewFitnessLevelChange extends ExerciseNewEvent { final String value; - const ExerciseNewFitnessLevelChange({this.value}); + const ExerciseNewFitnessLevelChange({required this.value}); @override List get props => [value]; @@ -61,7 +61,7 @@ class ExerciseNewFitnessLevelChange extends ExerciseNewEvent { class ExerciseNewSizeChange extends ExerciseNewEvent { final String propertyName; final double value; - const ExerciseNewSizeChange({this.propertyName, this.value}); + const ExerciseNewSizeChange({required this.propertyName, required this.value}); @override List get props => [propertyName, value]; diff --git a/lib/bloc/exercise_new/exercise_new_state.dart b/lib/bloc/exercise_new/exercise_new_state.dart index db081fd..3a3ace7 100644 --- a/lib/bloc/exercise_new/exercise_new_state.dart +++ b/lib/bloc/exercise_new/exercise_new_state.dart @@ -26,7 +26,7 @@ class ExerciseNewSaved extends ExerciseNewState { class ExerciseNewError extends ExerciseNewState { final String message; - const ExerciseNewError({this.message}); + const ExerciseNewError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/exercise_plan/exercise_plan_bloc.dart b/lib/bloc/exercise_plan/exercise_plan_bloc.dart index 01a6d49..f0d64ff 100644 --- a/lib/bloc/exercise_plan/exercise_plan_bloc.dart +++ b/lib/bloc/exercise_plan/exercise_plan_bloc.dart @@ -17,15 +17,15 @@ part 'exercise_plan_state.dart'; class ExercisePlanBloc extends Bloc { final WorkoutTreeRepository menuTreeRepository; ExercisePlanRepository exercisePlanRepository = ExercisePlanRepository(); - int customerId; + late int customerId; - ExercisePlanBloc({this.menuTreeRepository}) : super(ExercisePlanInitial()); + ExercisePlanBloc({required this.menuTreeRepository}) : super(ExercisePlanInitial()); Future getData() async { exercisePlanRepository.setCustomerId(customerId); await exercisePlanRepository.getLastExercisePlan(); await exercisePlanRepository.getExercisePlanDetails(); - menuTreeRepository.sortedTree = null; + menuTreeRepository.sortedTree.clear(); menuTreeRepository.sortByMuscleType(); menuTreeRepository.sortedTree.forEach((key, value) { @@ -33,7 +33,7 @@ class ExercisePlanBloc extends Bloc { listWorkoutTree.forEach((workoutTree) { workoutTree.selected = false; if (exercisePlanRepository.getExercisePlanDetailSize() > 0) { - ExercisePlanDetail planDetail = exercisePlanRepository.getExercisePlanDetailByExerciseId(workoutTree.exerciseTypeId); + ExercisePlanDetail? planDetail = exercisePlanRepository.getExercisePlanDetailByExerciseId(workoutTree.exerciseTypeId); if (planDetail != null && planDetail.change != ModelChange.deleted) { workoutTree.selected = true; } @@ -58,10 +58,8 @@ class ExercisePlanBloc extends Bloc { yield ExercisePlanLoading(); WorkoutMenuTree workoutTree = event.workoutTree; - if (workoutTree != null) { - exercisePlanRepository.setActualPlanDetailByExerciseType(workoutTree.exerciseType); - workoutTree.selected = true; - } + exercisePlanRepository.setActualPlanDetailByExerciseType(workoutTree.exerciseType!); + workoutTree.selected = true; yield ExercisePlanReady(); } else if (event is ExercisePlanAddExercise) { @@ -76,7 +74,7 @@ class ExercisePlanBloc extends Bloc { this.menuTreeRepository.sortedTree.forEach((key, value) { List listTreeItem = value; listTreeItem.forEach((element) { - if (element.exerciseType.exerciseTypeId == planDetail.exerciseTypeId) { + if (element.exerciseType!.exerciseTypeId == planDetail.exerciseTypeId) { element.selected = true; } }); @@ -91,7 +89,7 @@ class ExercisePlanBloc extends Bloc { this.menuTreeRepository.sortedTree.forEach((key, value) { List listTreeItem = value; listTreeItem.forEach((element) { - if (element.exerciseType.exerciseTypeId == planDetail.exerciseTypeId) { + if (element.exerciseType!.exerciseTypeId == planDetail.exerciseTypeId) { element.selected = false; } }); diff --git a/lib/bloc/exercise_plan/exercise_plan_event.dart b/lib/bloc/exercise_plan/exercise_plan_event.dart index 924030c..1b6813c 100644 --- a/lib/bloc/exercise_plan/exercise_plan_event.dart +++ b/lib/bloc/exercise_plan/exercise_plan_event.dart @@ -11,20 +11,18 @@ class ExercisePlanLoad extends ExercisePlanEvent { const ExercisePlanLoad(); } - // update UI class ExercisePlanUpdateUI extends ExercisePlanEvent { final WorkoutMenuTree workoutTree; - const ExercisePlanUpdateUI({this.workoutTree}); + const ExercisePlanUpdateUI({required this.workoutTree}); @override List get props => [workoutTree]; } - class ExercisePlanRemoveExercise extends ExercisePlanEvent { final ExercisePlanDetail exercisePlanDetail; - const ExercisePlanRemoveExercise({this.exercisePlanDetail}); + const ExercisePlanRemoveExercise({required this.exercisePlanDetail}); @override List get props => [exercisePlanDetail]; @@ -32,8 +30,8 @@ class ExercisePlanRemoveExercise extends ExercisePlanEvent { class ExercisePlanAddExercise extends ExercisePlanEvent { final ExercisePlanDetail exercisePlanDetail; - const ExercisePlanAddExercise({this.exercisePlanDetail}); + const ExercisePlanAddExercise({required this.exercisePlanDetail}); @override List get props => [exercisePlanDetail]; -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_plan/exercise_plan_state.dart b/lib/bloc/exercise_plan/exercise_plan_state.dart index 131a0e6..42b2731 100644 --- a/lib/bloc/exercise_plan/exercise_plan_state.dart +++ b/lib/bloc/exercise_plan/exercise_plan_state.dart @@ -1,7 +1,7 @@ part of 'exercise_plan_bloc.dart'; @immutable -abstract class ExercisePlanState extends Equatable{ +abstract class ExercisePlanState extends Equatable { const ExercisePlanState(); @override @@ -26,12 +26,8 @@ class ExercisePlanReady extends ExercisePlanState { // error splash screen class ExercisePlanError extends ExercisePlanState { final String message; - const ExercisePlanError({this.message}); + const ExercisePlanError({required this.message}); @override List get props => [message]; } - - - - diff --git a/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_bloc.dart b/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_bloc.dart index c0c6f01..87683cd 100644 --- a/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_bloc.dart +++ b/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_bloc.dart @@ -22,23 +22,30 @@ class ExercisePlanCustomAddBloc extends Bloc get props => [quantity]; @@ -22,7 +22,7 @@ class ExercisePlanCustomAddChangeSerie extends ExercisePlanCustomAddEvent { class ExercisePlanCustomAddChangeQuantity extends ExercisePlanCustomAddEvent { final double quantity; - const ExercisePlanCustomAddChangeQuantity({this.quantity}); + const ExercisePlanCustomAddChangeQuantity({required this.quantity}); @override List get props => [quantity]; @@ -30,7 +30,7 @@ class ExercisePlanCustomAddChangeQuantity extends ExercisePlanCustomAddEvent { class ExercisePlanCustomAddChangeQuantityUnit extends ExercisePlanCustomAddEvent { final double quantity; - const ExercisePlanCustomAddChangeQuantityUnit({this.quantity}); + const ExercisePlanCustomAddChangeQuantityUnit({required this.quantity}); @override List get props => [quantity]; @@ -42,4 +42,4 @@ class ExercisePlanCustomAddSubmit extends ExercisePlanCustomAddEvent { class ExercisePlanCustomAddRemove extends ExercisePlanCustomAddEvent { const ExercisePlanCustomAddRemove(); -} \ No newline at end of file +} diff --git a/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_state.dart b/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_state.dart index 0924a0e..cdddb18 100644 --- a/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_state.dart +++ b/lib/bloc/exercise_plan_custom_add/exercise_plan_custom_add_state.dart @@ -22,9 +22,8 @@ class ExercisePlanCustomAddReady extends ExercisePlanCustomAddState { class ExercisePlanCustomAddError extends ExercisePlanCustomAddState { final String message; - const ExercisePlanCustomAddError({this.message}); - + const ExercisePlanCustomAddError({required this.message}); @override List get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/login/login_bloc.dart b/lib/bloc/login/login_bloc.dart index e6b9910..a40ea5d 100644 --- a/lib/bloc/login/login_bloc.dart +++ b/lib/bloc/login/login_bloc.dart @@ -23,7 +23,9 @@ class LoginBloc extends Bloc with Trans { final bool isRegistration; bool dataPolicyAllowed = false; bool obscure = true; - LoginBloc({this.accountBloc, this.userRepository, this.context, this.isRegistration}) : super(LoginInitial()); + + LoginBloc({required this.accountBloc, required this.userRepository, required this.context, required this.isRegistration}) + : super(LoginInitial()); @override Stream mapEventToState( @@ -43,7 +45,7 @@ class LoginBloc extends Bloc with Trans { } else if (event is LoginSubmit) { yield LoginLoading(); await userRepository.getUser(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); Track().track(TrackingEvent.login, eventValue: "email"); Cache().setLoginType(LoginType.email); yield LoginSuccess(); @@ -51,31 +53,30 @@ class LoginBloc extends Bloc with Trans { yield LoginLoading(); Cache().setLoginType(LoginType.fb); await userRepository.getUserByFB(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); Track().track(TrackingEvent.login, eventValue: "FB"); yield LoginSuccess(); } else if (event is LoginGoogle) { yield LoginLoading(); Cache().setLoginType(LoginType.google); await userRepository.getUserByGoogle(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); Track().track(TrackingEvent.login, eventValue: "Google"); yield LoginSuccess(); } else if (event is LoginApple) { yield LoginLoading(); Cache().setLoginType(LoginType.apple); await userRepository.getUserByApple(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); Track().track(TrackingEvent.login, eventValue: "Apple"); yield LoginSuccess(); } else if (event is RegistrationSubmit) { yield LoginLoading(); if (!this.dataPolicyAllowed) { - yield LoginError(); throw Exception("Please accept our data policy"); } await userRepository.addUser(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); await saveCustomer(); Track().track(TrackingEvent.registration, eventValue: "email"); Cache().setLoginType(LoginType.email); @@ -83,36 +84,33 @@ class LoginBloc extends Bloc with Trans { } else if (event is RegistrationFB) { yield LoginLoading(); if (!this.dataPolicyAllowed) { - yield LoginError(); throw Exception("Please accept our data policy"); } Cache().setLoginType(LoginType.fb); await userRepository.addUserFB(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); await saveCustomer(); Track().track(TrackingEvent.registration, eventValue: "FB"); yield LoginSuccess(); } else if (event is RegistrationGoogle) { yield LoginLoading(); if (!this.dataPolicyAllowed) { - yield LoginError(); throw Exception("Please accept our data policy"); } Cache().setLoginType(LoginType.google); await userRepository.addUserGoogle(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); await saveCustomer(); Track().track(TrackingEvent.registration, eventValue: "Google"); yield LoginSuccess(); } else if (event is RegistrationApple) { yield LoginLoading(); if (!this.dataPolicyAllowed) { - yield LoginError(); throw Exception("Please accept our data policy"); } Cache().setLoginType(LoginType.apple); await userRepository.addUserApple(); - accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn)); + accountBloc.add(AccountLogInFinished(customer: Cache().userLoggedIn!)); await saveCustomer(); Track().track(TrackingEvent.registration, eventValue: "Apple"); @@ -132,21 +130,18 @@ class LoginBloc extends Bloc with Trans { } Future saveCustomer() async { - customerRepository.customer = Cache().userLoggedIn; + customerRepository.customer = Cache().userLoggedIn!; customerRepository.customer.dataPolicyAllowed = 1; await customerRepository.saveCustomer(); } - String emailValidation(String email) { - String message = Common.emailValidation(email); - if (message != null) { - message = t(message); - } + String? emailValidation(String email) { + String? message = Common.emailValidation(email); return message; } - String passwordValidation(String value) { - String message = Common.passwordValidation(value); + String? passwordValidation(String value) { + String? message = Common.passwordValidation(value); if (message != null) { message = t(message); } diff --git a/lib/bloc/login/login_event.dart b/lib/bloc/login/login_event.dart index 908df30..1e4a008 100644 --- a/lib/bloc/login/login_event.dart +++ b/lib/bloc/login/login_event.dart @@ -9,7 +9,7 @@ abstract class LoginEvent extends Equatable { class LoginEmailChange extends LoginEvent { final String email; - const LoginEmailChange({this.email}); + const LoginEmailChange({required this.email}); @override List get props => [email]; @@ -17,7 +17,7 @@ class LoginEmailChange extends LoginEvent { class LoginPasswordChange extends LoginEvent { final String password; - const LoginPasswordChange({this.password}); + const LoginPasswordChange({required this.password}); @override List get props => [password]; @@ -45,7 +45,7 @@ class LoginApple extends LoginEvent { class DataProtectionClicked extends LoginEvent { final bool marked; - const DataProtectionClicked({this.marked}); + const DataProtectionClicked({required this.marked}); } class RegistrationSubmit extends LoginEvent { diff --git a/lib/bloc/login/login_state.dart b/lib/bloc/login/login_state.dart index e075b3e..8918cdf 100644 --- a/lib/bloc/login/login_state.dart +++ b/lib/bloc/login/login_state.dart @@ -25,7 +25,7 @@ class LoginSuccess extends LoginState { class LoginError extends LoginState { final String message; - const LoginError({this.message}); + const LoginError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/menu/menu_bloc.dart b/lib/bloc/menu/menu_bloc.dart index 1b01783..8af724f 100644 --- a/lib/bloc/menu/menu_bloc.dart +++ b/lib/bloc/menu/menu_bloc.dart @@ -23,8 +23,8 @@ class MenuBloc extends Bloc with Trans, Logging { final ExerciseRepository exerciseRepository = ExerciseRepository(); ExerciseDeviceRepository exerciseDeviceRepository = ExerciseDeviceRepository(); int parent = 0; - WorkoutMenuTree workoutItem; - final List listFilterDevice = List(); + WorkoutMenuTree? workoutItem; + final List listFilterDevice = []; String infoTitle = ""; String infoText = ""; @@ -32,13 +32,13 @@ class MenuBloc extends Bloc with Trans, Logging { String infoText3 = ""; String infoLink = ""; int missingParent = 0; - String missingTreeName = ""; + String? missingTreeName = ""; - BuildContext context; + late BuildContext context; - ExerciseAbility ability; + ExerciseAbility? ability; - MenuBloc({this.menuTreeRepository}) : super(MenuInitial()) { + MenuBloc({required this.menuTreeRepository}) : super(MenuInitial()) { parent = 0; } @@ -48,7 +48,7 @@ class MenuBloc extends Bloc with Trans, Logging { exerciseRepository.getBaseExerciseFinishedPercent(); percent = Cache().getPercentExercises(); } - if (context == null) return; + percent = percent * 100; //log("Percent " + percent.toString()); if (percent == -1 || percent == 0) { @@ -78,7 +78,7 @@ class MenuBloc extends Bloc with Trans, Logging { //log("Missing " + missingTreeName); if (missingTreeName != null) { if (percent > 0) { - infoText = t("Please continue your tests with a") + " '" + missingTreeName + "' " + t("exercise!"); + infoText = t("Please continue your tests with a") + " '" + missingTreeName! + "' " + t("exercise!"); infoLink = t("Bring me there"); } } @@ -97,13 +97,13 @@ class MenuBloc extends Bloc with Trans, Logging { yield MenuLoading(); //await menuTreeRepository.createTree(); //menuTreeRepository.getBranch(this.parent); - setMenuInfo(); - exerciseDeviceRepository.setDevices(Cache().getDevices()); + //setMenuInfo(); + exerciseDeviceRepository.setDevices(Cache().getDevices()!); yield MenuReady(); } else if (event is MenuRecreateTree) { yield MenuLoading(); // ie. at language changes - await menuTreeRepository.createTree(); + menuTreeRepository.createTree(); yield MenuReady(); } else if (event is MenuTreeDown) { yield MenuLoading(); @@ -111,7 +111,7 @@ class MenuBloc extends Bloc with Trans, Logging { workoutItem = event.item; if (workoutItem != null) { - setAbility(workoutItem.nameEnglish); + setAbility(workoutItem!.nameEnglish); } final LinkedHashMap branch = menuTreeRepository.getBranch(event.parent); @@ -126,8 +126,8 @@ class MenuBloc extends Bloc with Trans, Logging { LinkedHashMap branch; if (workoutItem != null) { - setAbility(workoutItem.nameEnglish); - branch = menuTreeRepository.getBranch(workoutItem.parent); + setAbility(workoutItem!.nameEnglish); + branch = menuTreeRepository.getBranch(workoutItem!.parent); await getImages(branch); } @@ -138,12 +138,11 @@ class MenuBloc extends Bloc with Trans, Logging { workoutItem = menuTreeRepository.getParentItem(parent); if (workoutItem != null) { - setAbility(workoutItem.nameEnglish); - } - final LinkedHashMap branch = menuTreeRepository.getBranch(workoutItem.parent); - if (branch != null) { - await getImages(branch); + setAbility(workoutItem!.nameEnglish); } + final LinkedHashMap branch = menuTreeRepository.getBranch(workoutItem!.parent); + await getImages(branch); + yield MenuReady(); } else if (event is MenuClickExercise) { yield MenuLoading(); @@ -193,15 +192,15 @@ class MenuBloc extends Bloc with Trans, Logging { Future putBranchImageToHash(LinkedHashMap branch) async { await Future.forEach(branch.keys, (key) async { - final WorkoutMenuTree value = branch[key]; - if (!value.imageName.contains("asset")) { + final WorkoutMenuTree? value = branch[key]; + if (value != null && !value.imageName.contains("asset")) { await wt.ImageCache().putImageToList(value.id, value.imageName); } }); } - String getImage(int id, String name) { - String imageString; + String? getImage(int id, String name) { + String? imageString; if (name.contains("http")) { imageString = wt.ImageCache().getImageString(id, name); } @@ -212,7 +211,7 @@ class MenuBloc extends Bloc with Trans, Logging { return !listFilterDevice.contains(deviceId); } - LinkedHashMap getFilteredBranch(int parent) { + LinkedHashMap getFilteredBranch(int? parent) { if (parent == null) return LinkedHashMap(); LinkedHashMap branch = menuTreeRepository.getBranch(parent); @@ -224,8 +223,8 @@ class MenuBloc extends Bloc with Trans, Logging { branch.forEach((key, value) { final WorkoutMenuTree elem = value; if (elem.exerciseType != null) { - for (int i = 0; i < elem.exerciseType.devices.length; i++) { - if (listFilterDevice.contains(elem.exerciseType.devices[i])) { + for (int i = 0; i < elem.exerciseType!.devices.length; i++) { + if (listFilterDevice.contains(elem.exerciseType!.devices[i])) { filtered[elem.name] = elem; } } diff --git a/lib/bloc/menu/menu_event.dart b/lib/bloc/menu/menu_event.dart index 6c45322..56b33a3 100644 --- a/lib/bloc/menu/menu_event.dart +++ b/lib/bloc/menu/menu_event.dart @@ -16,26 +16,26 @@ class MenuCreate extends MenuEvent { } class MenuTreeDown extends MenuEvent { - final WorkoutMenuTree item; + final WorkoutMenuTree? item; final int parent; - const MenuTreeDown({this.parent, this.item}); + MenuTreeDown({required this.parent, this.item}); @override - List get props => [parent, item]; + List get props => [parent]; } class MenuTreeUp extends MenuEvent { final int parent; - final WorkoutMenuTree item; - const MenuTreeUp({this.parent, this.item}); + final WorkoutMenuTree? item; + const MenuTreeUp({required this.parent, this.item}); @override - List get props => [parent, item]; + List get props => [parent]; } class MenuTreeJump extends MenuEvent { final int parent; - const MenuTreeJump({this.parent}); + const MenuTreeJump({required this.parent}); @override List get props => [parent]; @@ -43,7 +43,7 @@ class MenuTreeJump extends MenuEvent { class MenuClickExercise extends MenuEvent { final int exerciseTypeId; - const MenuClickExercise({this.exerciseTypeId}); + const MenuClickExercise({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; @@ -55,5 +55,5 @@ class MenuRecreateTree extends MenuEvent { class MenuFilterExerciseType extends MenuEvent { final int deviceId; - const MenuFilterExerciseType({this.deviceId}); + const MenuFilterExerciseType({required this.deviceId}); } diff --git a/lib/bloc/menu/menu_state.dart b/lib/bloc/menu/menu_state.dart index 0184d80..d262eaa 100644 --- a/lib/bloc/menu/menu_state.dart +++ b/lib/bloc/menu/menu_state.dart @@ -1,7 +1,7 @@ part of 'menu_bloc.dart'; @immutable -abstract class MenuState extends Equatable { +abstract class MenuState extends Equatable { const MenuState(); @override @@ -12,22 +12,15 @@ class MenuInitial extends MenuState { const MenuInitial(); } -class MenuLoading extends MenuState { - -} +class MenuLoading extends MenuState {} class MenuReady extends MenuState { - final WorkoutMenuTree workoutTree; - - const MenuReady({this.workoutTree}); - - @override - List get props => [workoutTree]; + const MenuReady(); } class MenuError extends MenuState { final String message; - const MenuError({this.message}); + const MenuError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/password_reset/password_reset_bloc.dart b/lib/bloc/password_reset/password_reset_bloc.dart new file mode 100644 index 0000000..c0659ee --- /dev/null +++ b/lib/bloc/password_reset/password_reset_bloc.dart @@ -0,0 +1,40 @@ +import 'dart:async'; + +import 'package:aitrainer_app/repository/user_repository.dart'; +import 'package:aitrainer_app/util/common.dart'; +import 'package:bloc/bloc.dart'; +import 'package:equatable/equatable.dart'; + +part 'password_reset_event.dart'; +part 'password_reset_state.dart'; + +class PasswordResetBloc extends Bloc { + final UserRepository userRepository; + PasswordResetBloc({required this.userRepository}) : super(PasswordResetInitial()); + + @override + Stream mapEventToState( + PasswordResetEvent event, + ) async* { + try { + if (event is PasswordResetEmailChange) { + yield PasswordResetLoading(); + final String email = event.email; + userRepository.setEmail(email); + yield PasswordResetReady(); + } else if (event is PasswordResetSubmit) { + yield PasswordResetLoading(); + await userRepository.resetPassword(); + yield PasswordResetReady(); + } + } on Exception catch (e) { + yield PasswordResetError(message: e.toString()); + } + } + + String? emailValidation(String email) { + String? message = Common.emailValidation(email); + + return message; + } +} diff --git a/lib/bloc/password_reset/password_reset_event.dart b/lib/bloc/password_reset/password_reset_event.dart new file mode 100644 index 0000000..12177b2 --- /dev/null +++ b/lib/bloc/password_reset/password_reset_event.dart @@ -0,0 +1,24 @@ +part of 'password_reset_bloc.dart'; + +abstract class PasswordResetEvent extends Equatable { + const PasswordResetEvent(); + + @override + List get props => []; +} + +class PasswordResetEmailChange extends PasswordResetEvent { + final String email; + const PasswordResetEmailChange({required this.email}); + + @override + List get props => [email]; +} + +class PasswordResetLoad extends PasswordResetEvent { + const PasswordResetLoad(); +} + +class PasswordResetSubmit extends PasswordResetEvent { + const PasswordResetSubmit(); +} diff --git a/lib/bloc/password_reset/password_reset_state.dart b/lib/bloc/password_reset/password_reset_state.dart new file mode 100644 index 0000000..f323b23 --- /dev/null +++ b/lib/bloc/password_reset/password_reset_state.dart @@ -0,0 +1,28 @@ +part of 'password_reset_bloc.dart'; + +abstract class PasswordResetState extends Equatable { + const PasswordResetState(); + + @override + List get props => []; +} + +class PasswordResetInitial extends PasswordResetState { + const PasswordResetInitial(); +} + +class PasswordResetLoading extends PasswordResetState { + const PasswordResetLoading(); +} + +class PasswordResetError extends PasswordResetState { + final String message; + const PasswordResetError({required this.message}); + + @override + List get props => [message]; +} + +class PasswordResetReady extends PasswordResetState { + const PasswordResetReady(); +} diff --git a/lib/bloc/reset_password_bloc.dart b/lib/bloc/reset_password_bloc.dart deleted file mode 100644 index 63b3025..0000000 --- a/lib/bloc/reset_password_bloc.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'package:aitrainer_app/repository/user_repository.dart'; -import 'package:aitrainer_app/util/common.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; - -class ResetPasswordFormBloc extends FormBloc with Common { - final UserRepository userRepository; - bool loading = false; - - final emailField = TextFieldBloc( - validators: [ - FieldBlocValidators.required, - ], - ); - - ResetPasswordFormBloc({this.userRepository}) { - addFieldBlocs(fieldBlocs: [emailField]); - - emailField.onValueChanges(onData: (previous, current) async* { - userRepository.setEmail(current.value); - }); - } - - @override - void onSubmitting() async { - try { - emitLoading(progress: 30); - loading = true; - if (!validateEmail(userRepository)) { - emailField.addFieldError(EMAIL_ERROR, isPermanent: true); - - emitFailure(failureResponse: EMAIL_ERROR); - } else { - // Emit either Loaded or Error - await userRepository.resetPassword(); - emitSuccess(canSubmitAgain: false); - } - loading = false; - } on Exception catch (ex) { - emitFailure(failureResponse: ex.toString()); - } - } - - Future close() { - emailField.close(); - return super.close(); - } -} diff --git a/lib/bloc/result/result_bloc.dart b/lib/bloc/result/result_bloc.dart index a5643d0..5dd1837 100644 --- a/lib/bloc/result/result_bloc.dart +++ b/lib/bloc/result/result_bloc.dart @@ -8,7 +8,7 @@ import 'package:aitrainer_app/util/trans.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; + //import 'package:health/health.dart'; part 'result_event.dart'; @@ -18,9 +18,9 @@ class ResultBloc extends Bloc with Logging, Trans { final ExerciseResultRepository resultRepository; final ExerciseRepository exerciseRepository; final BuildContext context; - //List _healthDataList = List(); - DateTime startTime; - DateTime endTime; + //List _healthDataList = []; + DateTime? startTime; + DateTime? endTime; /* final HealthFactory health = HealthFactory(); final List types = [ HealthDataType.ACTIVE_ENERGY_BURNED, @@ -34,12 +34,12 @@ class ResultBloc extends Bloc with Logging, Trans { HealthDataType.RESTING_HEART_RATE ]; */ - ResultBloc({this.resultRepository, this.exerciseRepository, this.context}) : super(ResultInitial()) { + ResultBloc({required this.resultRepository, required this.exerciseRepository, required this.context}) : super(ResultInitial()) { this.startTime = exerciseRepository.start; this.endTime = exerciseRepository.end; if (this.startTime == null) { - this.startTime = exerciseRepository.exercise.dateAdd; - exerciseRepository.start = exerciseRepository.exercise.dateAdd; + this.startTime = exerciseRepository.exercise!.dateAdd!; + exerciseRepository.start = exerciseRepository.exercise!.dateAdd!; } } @@ -65,7 +65,7 @@ class ResultBloc extends Bloc with Logging, Trans { resultRepository.getResults().forEach((element) { element.dateFrom = startTime; element.dateTo = endTime; - element.exerciseId = exerciseRepository.actualExerciseList[0].exerciseId; + element.exerciseId = exerciseRepository.actualExerciseList![0].exerciseId; switch (element.item) { case ResultItem.bpm_avg: //element.data = _gethHealthDataPointValueAvg(HealthDataType.HEART_RATE); @@ -80,11 +80,10 @@ class ResultBloc extends Bloc with Logging, Trans { //element.data = _gethHealthDataPointValueSum(HealthDataType.ACTIVE_ENERGY_BURNED); break; case ResultItem.development_percent_bodypart: - // TODO: Handle this case. break; case ResultItem.distance: - if (exerciseRepository.exerciseType.unit == "meter") { - element.data = exerciseRepository.exercise.quantity; + if (exerciseRepository.exerciseType!.unit == "meter") { + element.data = exerciseRepository.exercise!.quantity!; } break; case ResultItem.fatburn_percent: @@ -109,13 +108,12 @@ class ResultBloc extends Bloc with Logging, Trans { } */ break; case ResultItem.speed_max: - // TODO: Handle this case. break; case ResultItem.reps_volume: - if (exerciseRepository.exerciseType.unit == "repeat") { + if (exerciseRepository.exerciseType!.unit == "repeat") { double value = 0; - exerciseRepository.actualExerciseList.forEach((actual) { - value += actual.quantity; + exerciseRepository.actualExerciseList!.forEach((actual) { + value += actual.quantity!; }); element.data = value; } @@ -128,10 +126,10 @@ class ResultBloc extends Bloc with Logging, Trans { element.data = _printDuration(duration); break; */ case ResultItem.weight_volume: - if (exerciseRepository.exerciseType.unitQuantityUnit == "kilogram") { + if (exerciseRepository.exerciseType!.unitQuantityUnit == "kilogram") { double value = 0; - exerciseRepository.actualExerciseList.forEach((actual) { - value += actual.quantity * actual.unitQuantity; + exerciseRepository.actualExerciseList!.forEach((actual) { + value += actual.quantity! * actual.unitQuantity!; }); element.data = value; } @@ -233,12 +231,12 @@ class ResultBloc extends Bloc with Logging, Trans { } } */ - double calculate1RM({double percent}) { + double calculate1RM({double percent = 0.75}) { if (exerciseRepository.exercise == null) { exerciseRepository.getLastExercise(); } - double weight = exerciseRepository.exercise.unitQuantity; - double repeat = exerciseRepository.exercise.quantity; + double weight = exerciseRepository.exercise!.unitQuantity!; + double repeat = exerciseRepository.exercise!.quantity!; if (weight == 0 || repeat == 0) { return 0; } diff --git a/lib/bloc/result/result_state.dart b/lib/bloc/result/result_state.dart index d9fa5ae..7cad7d9 100644 --- a/lib/bloc/result/result_state.dart +++ b/lib/bloc/result/result_state.dart @@ -21,7 +21,7 @@ class ResultReady extends ResultState { class ResultError extends ResultState { final String error; - const ResultError({this.error}); + const ResultError({required this.error}); @override List get props => [this.error]; diff --git a/lib/bloc/sales/sales_bloc.dart b/lib/bloc/sales/sales_bloc.dart index 8d63f27..f046cd8 100644 --- a/lib/bloc/sales/sales_bloc.dart +++ b/lib/bloc/sales/sales_bloc.dart @@ -8,21 +8,19 @@ import 'package:aitrainer_app/model/product_test.dart'; import 'package:aitrainer_app/model/purchase.dart'; import 'package:aitrainer_app/service/logging.dart'; import 'package:aitrainer_app/service/purchase_service.dart'; -import 'package:aitrainer_app/util/common.dart'; import 'package:aitrainer_app/util/enums.dart'; import 'package:aitrainer_app/util/purchases.dart'; import 'package:aitrainer_app/util/track.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; -import 'package:flurry/flurry.dart'; import 'package:purchases_flutter/offering_wrapper.dart'; part 'sales_event.dart'; part 'sales_state.dart'; class SalesBloc extends Bloc with Logging { - List tests = List(); - List product2Display = List(); + List? tests = []; + List product2Display = []; int productSet = -1; SalesBloc() : super(SalesInitial()); @@ -35,7 +33,6 @@ class SalesBloc extends Bloc with Logging { yield SalesLoading(); log("Load Sales"); Track().track(TrackingEvent.sales_page); - //await PlatformPurchaseApi().initPurchasePlatform(); await RevenueCatPurchases().getOfferings(); this.getProductSet(); yield SalesReady(); @@ -47,27 +44,30 @@ class SalesBloc extends Bloc with Logging { final int productId = event.productId; log("Requesting purchase for: " + productId.toString()); Track().track(TrackingEvent.purchase_request); - final Product selectedProduct = this.getSelectedProduct(productId); - log("SelectedProduct for purchase " + selectedProduct.toString()); - await RevenueCatPurchases().makePurchase(selectedProduct); - if (Cache().hasPurchased) { - Purchase purchase = Purchase(customerId: Cache().userLoggedIn.customerId, productId: productId); - purchase.dateAdd = DateTime.now(); - purchase.purchaseSum = 0; - purchase.currency = "EUR"; - await PurchaseApi().savePurchase(purchase); - Track().track(TrackingEvent.purchase_successful, eventValue: selectedProduct.localizedPrice.toString()); - Common.sendMessage("Purchase: " + purchase.toJson().toString()); + final Product? selectedProduct = this.getSelectedProduct(productId); + log("SelectedProduct for purchase $selectedProduct"); + if (selectedProduct != null) { + await RevenueCatPurchases().makePurchase(selectedProduct); + if (Cache().hasPurchased) { + Purchase purchase = Purchase(customerId: Cache().userLoggedIn!.customerId!, productId: productId); + purchase.dateAdd = DateTime.now(); + purchase.purchaseSum = 0; + purchase.currency = "EUR"; + await PurchaseApi().savePurchase(purchase); + Track().track(TrackingEvent.purchase_successful, eventValue: selectedProduct.localizedPrice.toString()); + } + yield SalesSuccessful(); + } else { + yield SalesError(message: "No selected product"); } - yield SalesSuccessful(); } } on Exception catch (ex) { yield SalesError(message: ex.toString()); } } - Product getSelectedProduct(int productId) { - Product prod; + Product? getSelectedProduct(int productId) { + Product? prod; for (var product in this.product2Display) { if (product.productId == productId) { prod = product; @@ -78,7 +78,7 @@ class SalesBloc extends Bloc with Logging { String getLocalizedPrice(String productId) { String price = ""; - Offering offering = RevenueCatPurchases().offering; + Offering? offering = RevenueCatPurchases().offering; if (offering != null) { for (var package in offering.availablePackages) { log("PlatformProduct " + package.toString()); @@ -100,15 +100,19 @@ class SalesBloc extends Bloc with Logging { void getProductSet() { int productId = 0; this.tests = Cache().productTests; + List? products = Cache().products; + if (products == null) { + return; + } - if (tests.isEmpty) { + if (tests != null && tests!.isEmpty) { var rand = math.Random.secure(); productSet = rand.nextInt(5) + 1; } else { - trace("Previous ProductTest: " + tests[0].toJson().toString()); - productId = tests[0].productId; - for (var elem in Cache().products) { - final Product product = elem as Product; + trace("Previous ProductTest: " + tests![0].toJson().toString()); + productId = tests![0].productId; + for (var elem in products) { + final Product product = elem; if (product.productId == productId) { productSet = product.productSet; break; @@ -120,12 +124,12 @@ class SalesBloc extends Bloc with Logging { productSet = 2; log("ProductSet: " + productSet.toString()); - for (var elem in Cache().products) { - Product product = elem as Product; + for (var elem in products) { + Product product = elem; if (product.productSet == productSet) { productId = product.productId; - final String platformProductId = Platform.isAndroid ? product.productIdAndroid : product.productIdIos; + final String platformProductId = Platform.isAndroid ? product.productIdAndroid! : product.productIdIos!; product.localizedPrice = getLocalizedPrice(platformProductId); product2Display.add(product); } @@ -136,7 +140,7 @@ class SalesBloc extends Bloc with Logging { }); productTest.productId = productId; - productTest.customerId = Cache().userLoggedIn.customerId; + productTest.customerId = Cache().userLoggedIn!.customerId!; productTest.dateView = DateTime.now(); //ProductTestApi().saveProductTest(productTest); //Cache().productTests.add(productTest); diff --git a/lib/bloc/sales/sales_event.dart b/lib/bloc/sales/sales_event.dart index fffce71..af62439 100644 --- a/lib/bloc/sales/sales_event.dart +++ b/lib/bloc/sales/sales_event.dart @@ -13,5 +13,5 @@ class SalesLoad extends SalesEvent { class SalesPurchase extends SalesEvent { final int productId; - const SalesPurchase({this.productId}); + const SalesPurchase({required this.productId}); } diff --git a/lib/bloc/sales/sales_state.dart b/lib/bloc/sales/sales_state.dart index 3cc5c09..b0a0d4b 100644 --- a/lib/bloc/sales/sales_state.dart +++ b/lib/bloc/sales/sales_state.dart @@ -25,7 +25,7 @@ class SalesSuccessful extends SalesState { class SalesError extends SalesState { final String message; - const SalesError({this.message}); + const SalesError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/session/session_bloc.dart b/lib/bloc/session/session_bloc.dart index e13d6e9..d76dee4 100644 --- a/lib/bloc/session/session_bloc.dart +++ b/lib/bloc/session/session_bloc.dart @@ -13,7 +13,7 @@ part 'session_state.dart'; class SessionBloc extends Bloc with Logging { final Session session; - SessionBloc({this.session}) : super(SessionInitial()); + SessionBloc({required this.session}) : super(SessionInitial()); @override Stream mapEventToState( diff --git a/lib/bloc/session/session_event.dart b/lib/bloc/session/session_event.dart index dbfbf8f..3b0e0f1 100644 --- a/lib/bloc/session/session_event.dart +++ b/lib/bloc/session/session_event.dart @@ -9,7 +9,7 @@ abstract class SessionEvent extends Equatable { class SessionStart extends SessionEvent { final SettingsBloc settingsBloc; - const SessionStart({this.settingsBloc}); + const SessionStart({required this.settingsBloc}); @override List get props => [settingsBloc]; diff --git a/lib/bloc/session/session_state.dart b/lib/bloc/session/session_state.dart index 82d1bc0..2d8c1b9 100644 --- a/lib/bloc/session/session_state.dart +++ b/lib/bloc/session/session_state.dart @@ -21,7 +21,7 @@ class SessionReady extends SessionState { class SessionFailure extends SessionState { final String message; - const SessionFailure({this.message}); + const SessionFailure({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/settings/settings_bloc.dart b/lib/bloc/settings/settings_bloc.dart index a702296..63100d1 100644 --- a/lib/bloc/settings/settings_bloc.dart +++ b/lib/bloc/settings/settings_bloc.dart @@ -16,9 +16,9 @@ part 'settings_event.dart'; part 'settings_state.dart'; class SettingsBloc extends Bloc with Logging { - String language; - Locale _locale; - BuildContext context; + String? language; + Locale? _locale; + BuildContext? context; SettingsBloc({this.context}) : super(SettingsInitial()); @@ -26,7 +26,7 @@ class SettingsBloc extends Bloc with Logging { _locale = locale; } - Locale getLocale() { + Locale? getLocale() { return _locale; } @@ -37,11 +37,11 @@ class SettingsBloc extends Bloc with Logging { if (event is SettingsChangeLanguage) { yield SettingsLoading(); await _changeLang(event.language); - yield SettingsReady(_locale); + yield SettingsReady(); } else if (event is SettingsGetLanguage) { await AppLanguage().fetchLocale(); _locale = AppLanguage().appLocal; - yield SettingsReady(_locale); + yield SettingsReady(); } else if (event is SettingsSetServer) { //yield SettingsLoading(); final bool live = event.live; @@ -60,7 +60,7 @@ class SettingsBloc extends Bloc with Logging { await _accessHealthData(); } Cache().initBadges(); - yield SettingsReady(_locale); + yield SettingsReady(); } } @@ -97,17 +97,17 @@ class SettingsBloc extends Bloc with Logging { break; } this.language = lang; - AppLanguage().changeLanguage(_locale); + AppLanguage().changeLanguage(_locale!); await loadLang(); - await Cache().initBadges(); + Cache().initBadges(); } Future loadLang() async { if (_locale != null) { log(" -- Loading lang $_locale"); if (context != null) { - AppLocalizations.of(context).setLocale(_locale); - await AppLocalizations.of(context).load(); + AppLocalizations.of(context!)!.setLocale(_locale!); + await AppLocalizations.of(context!)!.load(); } else { log("no context, does not load"); } diff --git a/lib/bloc/settings/settings_event.dart b/lib/bloc/settings/settings_event.dart index 0605cbc..bbfb0fe 100644 --- a/lib/bloc/settings/settings_event.dart +++ b/lib/bloc/settings/settings_event.dart @@ -9,7 +9,7 @@ abstract class SettingsEvent extends Equatable { class SettingsChangeLanguage extends SettingsEvent { final String language; - const SettingsChangeLanguage({this.language}); + const SettingsChangeLanguage({required this.language}); } class SettingsGetLanguage extends SettingsEvent { @@ -18,7 +18,7 @@ class SettingsGetLanguage extends SettingsEvent { class SettingsSetServer extends SettingsEvent { final bool live; - const SettingsSetServer({this.live}); + const SettingsSetServer({required this.live}); @override List get props => [this.live]; @@ -26,7 +26,7 @@ class SettingsSetServer extends SettingsEvent { class SettingsSetHardware extends SettingsEvent { final bool hasHardware; - const SettingsSetHardware({this.hasHardware}); + const SettingsSetHardware({required this.hasHardware}); @override List get props => [this.hasHardware]; diff --git a/lib/bloc/settings/settings_state.dart b/lib/bloc/settings/settings_state.dart index 6935d0f..1cf9c1a 100644 --- a/lib/bloc/settings/settings_state.dart +++ b/lib/bloc/settings/settings_state.dart @@ -10,31 +10,15 @@ abstract class SettingsState extends Equatable { // ignore: must_be_immutable class SettingsInitial extends SettingsState { - Locale locale; SettingsInitial(); - - setLocale(locale) { - this.locale = locale; - } - - @override - List get props => [locale]; } class SettingsLoading extends SettingsState { - final Locale locale; - const SettingsLoading({this.locale}); - - @override - List get props => [locale]; + const SettingsLoading(); } class SettingsReady extends SettingsState { - final Locale locale; - const SettingsReady(this.locale); - - @override - List get props => [locale]; + const SettingsReady(); } class SettingsError extends SettingsState { @@ -43,4 +27,4 @@ class SettingsError extends SettingsState { @override List get props => [message]; -} \ No newline at end of file +} diff --git a/lib/bloc/test_set_control/test_set_control_bloc.dart b/lib/bloc/test_set_control/test_set_control_bloc.dart index e3ecc0c..3cc8a2b 100644 --- a/lib/bloc/test_set_control/test_set_control_bloc.dart +++ b/lib/bloc/test_set_control/test_set_control_bloc.dart @@ -17,30 +17,31 @@ class TestSetControlBloc extends Bloc final TestSetExecuteBloc executeBloc; final ExerciseType exerciseType; final ExerciseRepository exerciseRepository = ExerciseRepository(); - TestSetControlBloc({this.exercisePlanDetail, this.executeBloc, this.exerciseType}) : super(TestSetControlInitial()) { + + late double initQuantity; + late double initUnitQuantity; + late double quantity; + late double unitQuantity; + late double oneRepMax; + late int step; + + TestSetControlBloc({required this.exercisePlanDetail, required this.executeBloc, required this.exerciseType}) + : super(TestSetControlInitial()) { initBloc(); } void initBloc() { - if (exercisePlanDetail.exerciseType.unitQuantity != null) { - oneRepMax = executeBloc.calculate1RM(exercisePlanDetail.exercises.last.unitQuantity, exercisePlanDetail.exercises.last.quantity); - initQuantity = 12; - quantity = initQuantity; - initUnitQuantity = oneRepMax * 0.75; - unitQuantity = initUnitQuantity; - } - step = exercisePlanDetail.exercises.length; + oneRepMax = executeBloc.calculate1RM(exercisePlanDetail.exercises!.last.unitQuantity, exercisePlanDetail.exercises!.last.quantity); + initQuantity = 12; + quantity = initQuantity; + initUnitQuantity = oneRepMax * 0.75; + unitQuantity = initUnitQuantity; + + step = exercisePlanDetail.exercises!.length; exerciseRepository.customer = Cache().userLoggedIn; exerciseRepository.exerciseType = exerciseType; } - double initQuantity; - double initUnitQuantity; - double quantity; - double unitQuantity; - double oneRepMax; - int step; - @override Stream mapEventToState( TestSetControlEvent event, diff --git a/lib/bloc/test_set_control/test_set_control_event.dart b/lib/bloc/test_set_control/test_set_control_event.dart index 0eb4620..058b800 100644 --- a/lib/bloc/test_set_control/test_set_control_event.dart +++ b/lib/bloc/test_set_control/test_set_control_event.dart @@ -13,7 +13,7 @@ class TestSetControlLoad extends TestSetControlEvent { class TestSetControlQuantityChange extends TestSetControlEvent { final double quantity; - const TestSetControlQuantityChange({this.quantity}); + const TestSetControlQuantityChange({required this.quantity}); @override List get props => [quantity]; @@ -21,7 +21,7 @@ class TestSetControlQuantityChange extends TestSetControlEvent { class TestSetControlUnitQuantityChange extends TestSetControlEvent { final double quantity; - const TestSetControlUnitQuantityChange({this.quantity}); + const TestSetControlUnitQuantityChange({required this.quantity}); @override List get props => [quantity]; diff --git a/lib/bloc/test_set_control/test_set_control_state.dart b/lib/bloc/test_set_control/test_set_control_state.dart index c3e6f98..c62adcc 100644 --- a/lib/bloc/test_set_control/test_set_control_state.dart +++ b/lib/bloc/test_set_control/test_set_control_state.dart @@ -21,7 +21,7 @@ class TestSetControlReady extends TestSetControlState { class TestSetControlError extends TestSetControlState { final String message; - const TestSetControlError({this.message}); + const TestSetControlError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/test_set_edit/test_set_edit_bloc.dart b/lib/bloc/test_set_edit/test_set_edit_bloc.dart index ca27793..0e750be 100644 --- a/lib/bloc/test_set_edit/test_set_edit_bloc.dart +++ b/lib/bloc/test_set_edit/test_set_edit_bloc.dart @@ -21,14 +21,15 @@ part 'test_set_edit_state.dart'; class TestSetEditBloc extends Bloc { final String templateName; final String templateNameTranslation; - String templateDescription; + late String templateDescription; final WorkoutTreeRepository workoutTreeRepository; final MenuBloc menuBloc; - final List _exerciseTypes = List(); - final List _actualExerciseTypes = List(); - final HashMap _exercisePlanDetails = HashMap(); + final List _exerciseTypes = []; + final List _actualExerciseTypes = []; + final HashMap _exercisePlanDetails = HashMap(); - TestSetEditBloc({this.templateName, this.templateNameTranslation, this.workoutTreeRepository, this.menuBloc}) + TestSetEditBloc( + {required this.templateName, required this.templateNameTranslation, required this.workoutTreeRepository, required this.menuBloc}) : super(TestSetEditInitial()) { if (Cache().exercisePlanTemplates.isNotEmpty) { Cache().exercisePlanTemplates.forEach((element) { @@ -36,10 +37,12 @@ class TestSetEditBloc extends Bloc { if (template.name == templateName) { templateDescription = template.descriptionTranslation; template.exerciseTypes.forEach((id) { - final ExerciseType exerciseType = Cache().getExerciseTypeById(id); - _exerciseTypes.add(exerciseType); - _actualExerciseTypes.add(exerciseType); - _exercisePlanDetails[exerciseType.exerciseTypeId] = exerciseType; + final ExerciseType? exerciseType = Cache().getExerciseTypeById(id); + if (exerciseType != null) { + _exerciseTypes.add(exerciseType); + _actualExerciseTypes.add(exerciseType); + _exercisePlanDetails[exerciseType.exerciseTypeId] = exerciseType; + } }); } }); @@ -52,17 +55,18 @@ class TestSetEditBloc extends Bloc { if (event is TestSetEditChangeExerciseType) { yield TestSetEditLoading(); final List alternatives = workoutTreeRepository.getExerciseTypeAlternatives(event.exerciseTypeId); - final ExerciseType exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId); - - if (_exercisePlanDetails[event.exerciseTypeId] == null) { - /// it was skipped - _exercisePlanDetails[exerciseType.exerciseTypeId] = exerciseType; - } else { - if (event.index == 0) { + final ExerciseType? exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId); + if (exerciseType != null) { + if (_exercisePlanDetails[event.exerciseTypeId] == null) { + /// it was skipped _exercisePlanDetails[exerciseType.exerciseTypeId] = exerciseType; } else { - final changedExerciseType = alternatives[event.index - 1]; - _exercisePlanDetails[exerciseType.exerciseTypeId] = changedExerciseType; + if (event.index == 0) { + _exercisePlanDetails[exerciseType.exerciseTypeId] = exerciseType; + } else { + final changedExerciseType = alternatives[event.index - 1]; + _exercisePlanDetails[exerciseType.exerciseTypeId] = changedExerciseType; + } } } @@ -71,28 +75,30 @@ class TestSetEditBloc extends Bloc { yield TestSetEditReady(); } else if (event is TestSetEditDeleteExerciseType) { yield TestSetEditLoading(); - final ExerciseType exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId); - _exercisePlanDetails[exerciseType.exerciseTypeId] = null; + final ExerciseType? exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId); + if (exerciseType != null) { + _exercisePlanDetails[exerciseType.exerciseTypeId] = null; + } refreshActualPlan(); yield TestSetEditReady(); } else if (event is TestSetEditSubmit) { yield TestSetEditLoading(); - ExercisePlan exercisePlan = ExercisePlan(templateNameTranslation, Cache().userLoggedIn.customerId); + ExercisePlan exercisePlan = ExercisePlan(templateNameTranslation, Cache().userLoggedIn!.customerId!); exercisePlan.private = true; exercisePlan.type = ExerciseAbility.mini_test_set.enumToString(); exercisePlan.dateAdd = DateTime.now(); ExercisePlan savedExercisePlan = await ExercisePlanApi().saveExercisePlan(exercisePlan); - List details = List(); + List details = []; for (var entry in _exercisePlanDetails.entries) { if (entry.value != null) { - ExercisePlanDetail exercisePlanDetail = ExercisePlanDetail(entry.value.exerciseTypeId); - exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId; + ExercisePlanDetail exercisePlanDetail = ExercisePlanDetail(entry.value!.exerciseTypeId); + exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId!; exercisePlanDetail.serie = 1; ExercisePlanDetail savedDetail = await ExercisePlanApi().saveExercisePlanDetail(exercisePlanDetail); exercisePlanDetail.exercisePlanDetailId = savedDetail.exercisePlanDetailId; - exercisePlanDetail.exercises = List(); + exercisePlanDetail.exercises = []; details.add(exercisePlanDetail); } } @@ -112,8 +118,10 @@ class TestSetEditBloc extends Bloc { void refreshActualPlan() { _actualExerciseTypes.removeRange(0, _actualExerciseTypes.length - 1); _exercisePlanDetails.keys.forEach((element) { - final ExerciseType exerciseType = Cache().getExerciseTypeById(element); - _actualExerciseTypes.add(exerciseType); + final ExerciseType? exerciseType = Cache().getExerciseTypeById(element); + if (exerciseType != null) { + _actualExerciseTypes.add(exerciseType); + } }); } } diff --git a/lib/bloc/test_set_edit/test_set_edit_event.dart b/lib/bloc/test_set_edit/test_set_edit_event.dart index 8b33f73..8649cae 100644 --- a/lib/bloc/test_set_edit/test_set_edit_event.dart +++ b/lib/bloc/test_set_edit/test_set_edit_event.dart @@ -14,7 +14,7 @@ class TestSetEditLoad extends TestSetEditEvent { class TestSetEditChangeExerciseType extends TestSetEditEvent { final int index; final int exerciseTypeId; - const TestSetEditChangeExerciseType({this.index, this.exerciseTypeId}); + const TestSetEditChangeExerciseType({required this.index, required this.exerciseTypeId}); @override List get props => [index, exerciseTypeId]; @@ -22,7 +22,7 @@ class TestSetEditChangeExerciseType extends TestSetEditEvent { class TestSetEditDeleteExerciseType extends TestSetEditEvent { final int exerciseTypeId; - const TestSetEditDeleteExerciseType({this.exerciseTypeId}); + const TestSetEditDeleteExerciseType({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; @@ -30,7 +30,7 @@ class TestSetEditDeleteExerciseType extends TestSetEditEvent { class TestSetEditSkipExerciseType extends TestSetEditEvent { final int exerciseTypeId; - const TestSetEditSkipExerciseType({this.exerciseTypeId}); + const TestSetEditSkipExerciseType({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; diff --git a/lib/bloc/test_set_edit/test_set_edit_state.dart b/lib/bloc/test_set_edit/test_set_edit_state.dart index b34b444..fa4424b 100644 --- a/lib/bloc/test_set_edit/test_set_edit_state.dart +++ b/lib/bloc/test_set_edit/test_set_edit_state.dart @@ -25,7 +25,7 @@ class TestSetEditLoading extends TestSetEditState { class TestSetEditError extends TestSetEditState { final String message; - const TestSetEditError({this.message}); + const TestSetEditError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/test_set_execute/test_set_execute_bloc.dart b/lib/bloc/test_set_execute/test_set_execute_bloc.dart index b9e106c..a6960e7 100644 --- a/lib/bloc/test_set_execute/test_set_execute_bloc.dart +++ b/lib/bloc/test_set_execute/test_set_execute_bloc.dart @@ -18,17 +18,17 @@ part 'test_set_execute_state.dart'; class TestSetExecuteBloc extends Bloc { // ignore: close_sinks - MenuBloc menuBloc; - int exerciseTypeId; - String testName; + late MenuBloc menuBloc; + int? exerciseTypeId; + String? testName; String testType = ""; bool miniTestSet = false; bool paralellTest = false; double scrollOffset = 0; - ExercisePlan exercisePlan; + ExercisePlan? exercisePlan; bool isDone100 = false; - List exercisePlanDetails; + List? exercisePlanDetails; TestSetExecuteBloc() : super(TestSetExecuteInitial()); @@ -37,19 +37,19 @@ class TestSetExecuteBloc extends Bloc void initExercisePlan() { exercisePlan = Cache().activeExercisePlan; if (exercisePlan != null) { - testName = exercisePlan.name; - this.miniTestSet = exercisePlan.type != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan.type); - this.paralellTest = exercisePlan.type != null && ExerciseAbility.paralell_test.equalsStringTo(exercisePlan.type); + testName = exercisePlan!.name; + this.miniTestSet = exercisePlan!.type != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan!.type!); + this.paralellTest = exercisePlan!.type != null && ExerciseAbility.paralell_test.equalsStringTo(exercisePlan!.type!); - testType = ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan.type) + testType = ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan!.type!) ? ExerciseAbility.mini_test_set.description : ExerciseAbility.paralell_test.description; print("exercisePlan: $testName type: $testType"); } exercisePlanDetails = Cache().activeExercisePlanDetails; if (exercisePlanDetails != null) { - exercisePlanDetails.forEach((element) { - final ExerciseType exerciseType = Cache().getExerciseTypeById(element.exerciseTypeId); + exercisePlanDetails!.forEach((element) { + final ExerciseType? exerciseType = Cache().getExerciseTypeById(element.exerciseTypeId); if (exerciseType != null) { element.exerciseType = exerciseType; } @@ -69,7 +69,7 @@ class TestSetExecuteBloc extends Bloc if (exerciseTypeId != null) { int step = 0; if (exercisePlanDetails != null) { - exercisePlanDetails.forEach((element) { + exercisePlanDetails!.forEach((element) { if (element.exerciseTypeId == this.exerciseTypeId) { scrollOffset = (step * 85).toDouble() + 10; } @@ -79,44 +79,44 @@ class TestSetExecuteBloc extends Bloc } yield TestSetExecuteReady(); } else if (event is TestSetExecuteDeleteActive) { - print("Delete: ${exercisePlan.type} paralellTest: $paralellTest"); - if (exercisePlan != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan.type)) { + print("Delete: ${exercisePlan!.type} paralellTest: $paralellTest"); + if (exercisePlan != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan!.type!)) { exercisePlan = null; if (exercisePlanDetails != null) { - exercisePlanDetails.removeRange(0, exercisePlanDetails.length - 1); + exercisePlanDetails!.removeRange(0, exercisePlanDetails!.length - 1); } await Cache().deleteActiveExercisePlan(); } } else if (event is TestSetExecuteDeleteAllActive) { - print("DeleteAll Test Set: ${exercisePlan.type}"); if (exercisePlan != null) { + print("DeleteAll Test Set: ${exercisePlan!.type}"); exercisePlan = null; if (exercisePlanDetails != null) { - exercisePlanDetails.removeRange(0, exercisePlanDetails.length - 1); + exercisePlanDetails!.removeRange(0, exercisePlanDetails!.length - 1); } await Cache().deleteActiveExercisePlan(); } } else if (event is TestSetExecuteExerciseFinished) { yield TestSetExecuteLoading(); - exercisePlanDetails.forEach((element) { + exercisePlanDetails!.forEach((element) { if (element.exerciseTypeId == event.exerciseTypeId) { element.repeats = event.quantity.toInt(); element.weightEquation = event.unitQuantity.toString(); if (element.exercises == null) { - element.exercises = List(); + element.exercises = []; } final Exercise exercise = Exercise(); - exercise.customerId = Cache().userLoggedIn.customerId; + exercise.customerId = Cache().userLoggedIn!.customerId!; exercise.exerciseTypeId = event.exerciseTypeId; exercise.quantity = event.quantity; - exercise.unit = element.exerciseType.unit; + exercise.unit = element.exerciseType!.unit; exercise.unitQuantity = event.unitQuantity; exercise.dateAdd = DateTime.now(); - element.exercises.add(exercise); + element.exercises!.add(exercise); setPlanDetailState(element); } }); - Cache().saveActiveExercisePlan(exercisePlan, exercisePlanDetails); + Cache().saveActiveExercisePlan(exercisePlan!, exercisePlanDetails!); if (this.isDone100Percent()) { add(TestSetExecuteFinish()); } else { @@ -125,45 +125,51 @@ class TestSetExecuteBloc extends Bloc } else if (event is TestSetExecuteNewExercise) { yield TestSetExecuteLoading(); if (exercisePlan == null) { - exercisePlan = ExercisePlan(Cache().userLoggedIn.name + " Custom Test", Cache().userLoggedIn.customerId); - exercisePlan.private = true; - exercisePlan.dateAdd = DateTime.now(); - exercisePlan.type = ExerciseAbility.paralell_test.enumToString(); - ExercisePlan savedExercisePlan = await ExercisePlanApi().saveExercisePlan(exercisePlan); + exercisePlan = ExercisePlan(Cache().userLoggedIn!.name! + " Custom Test", Cache().userLoggedIn!.customerId!); + exercisePlan!.private = true; + exercisePlan!.dateAdd = DateTime.now(); + exercisePlan!.type = ExerciseAbility.paralell_test.enumToString(); + ExercisePlan savedExercisePlan = await ExercisePlanApi().saveExercisePlan(exercisePlan!); exercisePlan = savedExercisePlan; - exercisePlanDetails = List(); + exercisePlanDetails = []; } if (!this.existsInPlanDetails(event.exerciseTypeId)) { ExercisePlanDetail exercisePlanDetail = ExercisePlanDetail(event.exerciseTypeId); - exercisePlanDetail.exercisePlanId = exercisePlan.exercisePlanId; - final ExerciseType exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId); + exercisePlanDetail.exercisePlanId = exercisePlan!.exercisePlanId!; + final ExerciseType exerciseType = Cache().getExerciseTypeById(event.exerciseTypeId)!; + exercisePlanDetail.serie = exerciseType.unitQuantityUnit == null ? 1 : 4; exercisePlanDetail.exerciseType = exerciseType; exercisePlanDetail.exerciseTypeId = event.exerciseTypeId; ExercisePlanDetail savedDetail = await ExercisePlanApi().saveExercisePlanDetail(exercisePlanDetail); exercisePlanDetail.exercisePlanDetailId = savedDetail.exercisePlanDetailId; exercisePlanDetail.state = ExercisePlanDetailState.start; - exercisePlanDetail.exercises = List(); - exercisePlanDetails.add(exercisePlanDetail); - await Cache().saveActiveExercisePlan(exercisePlan, exercisePlanDetails); + exercisePlanDetail.exercises = []; + if (exercisePlanDetails == null) { + exercisePlanDetails = []; + } + exercisePlanDetails!.add(exercisePlanDetail); + await Cache().saveActiveExercisePlan(exercisePlan!, exercisePlanDetails!); paralellTest = true; } yield TestSetExecuteReady(); } else if (event is TestSetExecuteDeleteExercise) { yield TestSetExecuteLoading(); - ExercisePlanDetail deleteDetail; - exercisePlanDetails.forEach((element) { - if (element.exerciseTypeId == event.exerciseTypeId) { - deleteDetail = element; - } - }); - if (deleteDetail != null) { - exercisePlanDetails.remove(deleteDetail); - if (exercisePlanDetails.isEmpty) { - exercisePlan = null; - exercisePlanDetails = null; - Cache().deleteActiveExercisePlan(); + ExercisePlanDetail? deleteDetail; + if (exercisePlanDetails != null) { + exercisePlanDetails!.forEach((element) { + if (element.exerciseTypeId == event.exerciseTypeId) { + deleteDetail = element; + } + }); + if (deleteDetail != null) { + exercisePlanDetails!.remove(deleteDetail); + if (exercisePlanDetails!.isEmpty) { + exercisePlan = null; + exercisePlanDetails = null; + Cache().deleteActiveExercisePlan(); + } } } yield TestSetExecuteReady(); @@ -181,9 +187,9 @@ class TestSetExecuteBloc extends Bloc bool hasBegun() { if (exercisePlanDetails == null || - exercisePlanDetails.isEmpty || - exercisePlanDetails[0].exercises == null || - exercisePlanDetails[0].exercises.length == 0) { + exercisePlanDetails!.isEmpty || + exercisePlanDetails![0].exercises == null || + exercisePlanDetails![0].exercises!.length == 0) { return false; } @@ -191,14 +197,14 @@ class TestSetExecuteBloc extends Bloc } void setPlanDetailState(ExercisePlanDetail exercisePlanDetail) { - if (exercisePlanDetail.exercises == null || exercisePlanDetail.exercises.length == 0) { + if (exercisePlanDetail.exercises == null || exercisePlanDetail.exercises!.length == 0) { exercisePlanDetail.state = ExercisePlanDetailState.start; } else { int maxLength = 1; - if (exercisePlanDetail.exerciseType.unitQuantityUnit != null) { + if (exercisePlanDetail.exerciseType!.unitQuantityUnit != null) { maxLength = 4; } - if (exercisePlanDetail.exercises.length >= maxLength) { + if (exercisePlanDetail.exercises!.length >= maxLength) { exercisePlanDetail.state = ExercisePlanDetailState.finished; } else { exercisePlanDetail.state = ExercisePlanDetailState.inProgress; @@ -208,7 +214,8 @@ class TestSetExecuteBloc extends Bloc ExercisePlanDetailState actualState(int exerciseTypeId) { ExercisePlanDetailState state = ExercisePlanDetailState.start; - exercisePlanDetails.forEach((element) { + if (exercisePlanDetails == null) return state; + exercisePlanDetails!.forEach((element) { if (element.exerciseTypeId == exerciseTypeId) { state = element.state; } @@ -218,7 +225,8 @@ class TestSetExecuteBloc extends Bloc bool existsInPlanDetails(int exerciseTypeId) { bool found = false; - exercisePlanDetails.forEach((element) { + if (exercisePlanDetails == null) return found; + exercisePlanDetails!.forEach((element) { if (element.exerciseTypeId == exerciseTypeId) { found = true; } @@ -226,9 +234,11 @@ class TestSetExecuteBloc extends Bloc return found; } - ExercisePlanDetail actualExercisePlanDetail(int exerciseTypeId) { - ExercisePlanDetail found; - exercisePlanDetails.forEach((element) { + ExercisePlanDetail? actualExercisePlanDetail(int exerciseTypeId) { + ExercisePlanDetail? found; + if (exercisePlanDetails == null) return found; + + exercisePlanDetails!.forEach((element) { if (element.exerciseTypeId == exerciseTypeId) { found = element; } @@ -238,10 +248,10 @@ class TestSetExecuteBloc extends Bloc bool isDone100Percent() { bool done = true; - if (exercisePlanDetails == null || exercisePlanDetails.isEmpty) { + if (exercisePlanDetails == null || exercisePlanDetails!.isEmpty) { return false; } - exercisePlanDetails.forEach((element) { + exercisePlanDetails!.forEach((element) { if (!element.state.equalsTo(ExercisePlanDetailState.finished)) { done = false; } @@ -251,7 +261,7 @@ class TestSetExecuteBloc extends Bloc HashMap canAddNewExercise() { HashMap ret = HashMap(); - if (exercisePlan != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan.type)) { + if (exercisePlan != null && ExerciseAbility.mini_test_set.equalsStringTo(exercisePlan!.type!)) { final String message = "You have an active Test Set!"; final String message2 = "Do you want you to override it?"; ret['message'] = message; @@ -264,8 +274,8 @@ class TestSetExecuteBloc extends Bloc return ret; } - int getActualWorkoutTreeId(int exerciseTypeId) { - final WorkoutMenuTree workoutTree = this.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseTypeId); + int? getActualWorkoutTreeId(int exerciseTypeId) { + final WorkoutMenuTree? workoutTree = this.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseTypeId); if (workoutTree == null) { return null; } @@ -276,7 +286,7 @@ class TestSetExecuteBloc extends Bloc if (exerciseTypeId <= 0) { return ""; } - final WorkoutMenuTree workoutTree = this.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseTypeId); + final WorkoutMenuTree? workoutTree = this.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseTypeId); if (workoutTree == null) { return ""; } @@ -288,14 +298,14 @@ class TestSetExecuteBloc extends Bloc if (exercisePlanDetails == null) { return true; } - if (exercisePlanDetails.isEmpty) { + if (exercisePlanDetails!.isEmpty) { return true; } - return (exercisePlanDetails[0].exercises == null || exercisePlanDetails[0].exercises.length == 0); + return (exercisePlanDetails![0].exercises == null || exercisePlanDetails![0].exercises!.length == 0); } bool existsActivePlan() { - final bool exists = exercisePlan != null && exercisePlanDetails.length > 0; + final bool exists = exercisePlan != null && exercisePlanDetails != null && exercisePlanDetails!.isNotEmpty; print("Exists active plan: $exists"); return exists; } @@ -304,20 +314,22 @@ class TestSetExecuteBloc extends Bloc return (exercisePlanDetail.state.equalsTo(ExercisePlanDetailState.finished)); } - ExercisePlanDetail getNext() { - ExercisePlanDetail nextExercisePlanDetail; + ExercisePlanDetail? getNext() { + ExercisePlanDetail? nextExercisePlanDetail; int minStep = 99; - for (final detail in this.exercisePlanDetails) { - if (!detail.state.equalsTo(ExercisePlanDetailState.finished)) { - if (detail.exercises == null) { - nextExercisePlanDetail = detail; - minStep = 1; - break; - } else { - final int step = detail.exercises.length; - if (step < minStep) { + if (this.exercisePlanDetails == null) { + for (final detail in this.exercisePlanDetails!) { + if (!detail.state.equalsTo(ExercisePlanDetailState.finished)) { + if (detail.exercises == null) { nextExercisePlanDetail = detail; - minStep = step; + minStep = 1; + break; + } else { + final int step = detail.exercises!.length; + if (step < minStep) { + nextExercisePlanDetail = detail; + minStep = step; + } } } } @@ -341,10 +353,10 @@ class TestSetExecuteBloc extends Bloc String repeatTimesText(ExercisePlanDetail exercisePlanDetail) { String text = "maximum"; - if (!hasBegun() || exercisePlanDetail.exerciseType.unitQuantityUnit == null) { + if (!hasBegun() || exercisePlanDetail.exerciseType!.unitQuantityUnit == null) { return text; } - int step = exercisePlanDetail.exercises.length; + int step = exercisePlanDetail.exercises!.length; print("repeatTimes step $step"); if (step == 2) { text = "12"; @@ -354,13 +366,13 @@ class TestSetExecuteBloc extends Bloc String getExerciseWeight(ExercisePlanDetail exercisePlanDetail) { String text = "you are able to do 12-20 repeats with"; - if (!hasBegun() || exercisePlanDetail.exercises.length < 2) { + if (!hasBegun() || exercisePlanDetail.exercises!.length < 2) { return text; } - final double unitQuantity = exercisePlanDetail.exercises.last.unitQuantity; - final double quantity = exercisePlanDetail.exercises.last.quantity; + final double unitQuantity = exercisePlanDetail.exercises!.last.unitQuantity; + final double quantity = exercisePlanDetail.exercises!.last.quantity; double oneRepMax = this.calculate1RM(quantity, unitQuantity); - text = (oneRepMax * 0.75).round().toStringAsFixed(0) + " " + exercisePlanDetail.exerciseType.unitQuantityUnit; + text = (oneRepMax * 0.75).round().toStringAsFixed(0) + " " + exercisePlanDetail.exerciseType!.unitQuantityUnit!; return text; } } diff --git a/lib/bloc/test_set_execute/test_set_execute_event.dart b/lib/bloc/test_set_execute/test_set_execute_event.dart index a23fd8b..5db453f 100644 --- a/lib/bloc/test_set_execute/test_set_execute_event.dart +++ b/lib/bloc/test_set_execute/test_set_execute_event.dart @@ -13,7 +13,7 @@ class TestSetExecuteLoad extends TestSetExecuteEvent { class TestSetExecuteExecute extends TestSetExecuteEvent { final int exerciseTypeId; - const TestSetExecuteExecute({this.exerciseTypeId}); + const TestSetExecuteExecute({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; @@ -27,7 +27,7 @@ class TestSetExecuteExerciseFinished extends TestSetExecuteEvent { final int exerciseTypeId; final double quantity; final double unitQuantity; - const TestSetExecuteExerciseFinished({this.exerciseTypeId, this.quantity, this.unitQuantity}); + const TestSetExecuteExerciseFinished({required this.exerciseTypeId, required this.quantity, required this.unitQuantity}); @override List get props => [exerciseTypeId, quantity, unitQuantity]; @@ -35,7 +35,7 @@ class TestSetExecuteExerciseFinished extends TestSetExecuteEvent { class TestSetExecuteNewExercise extends TestSetExecuteEvent { final int exerciseTypeId; - const TestSetExecuteNewExercise({this.exerciseTypeId}); + const TestSetExecuteNewExercise({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; @@ -43,7 +43,7 @@ class TestSetExecuteNewExercise extends TestSetExecuteEvent { class TestSetExecuteDeleteExercise extends TestSetExecuteEvent { final int exerciseTypeId; - const TestSetExecuteDeleteExercise({this.exerciseTypeId}); + const TestSetExecuteDeleteExercise({required this.exerciseTypeId}); @override List get props => [exerciseTypeId]; diff --git a/lib/bloc/test_set_execute/test_set_execute_state.dart b/lib/bloc/test_set_execute/test_set_execute_state.dart index fce639b..3e56381 100644 --- a/lib/bloc/test_set_execute/test_set_execute_state.dart +++ b/lib/bloc/test_set_execute/test_set_execute_state.dart @@ -25,7 +25,7 @@ class TestSetExecuteReady extends TestSetExecuteState { class TestSetExecuteError extends TestSetExecuteState { final String message; - const TestSetExecuteError({this.message}); + const TestSetExecuteError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/test_set_new/test_set_new_bloc.dart b/lib/bloc/test_set_new/test_set_new_bloc.dart index f3bc07f..74b11b9 100644 --- a/lib/bloc/test_set_new/test_set_new_bloc.dart +++ b/lib/bloc/test_set_new/test_set_new_bloc.dart @@ -18,21 +18,23 @@ class TestSetNewBloc extends Bloc { final int exercisePlanDetailId; final TestSetExecuteBloc executeBloc; - TestSetNewBloc({this.exerciseRepository, this.exerciseType, this.exercisePlanDetailId, this.executeBloc}) : super(TestSetNewInitial()) { + late double quantity; + late double unitQuantity; + + TestSetNewBloc( + {required this.exerciseRepository, required this.exerciseType, required this.exercisePlanDetailId, required this.executeBloc}) + : super(TestSetNewInitial()) { exerciseRepository.exerciseType = exerciseType; quantity = 12; unitQuantity = 30; exerciseRepository.setQuantity(quantity); exerciseRepository.setUnit(exerciseType.unit); exerciseRepository.setUnitQuantity(unitQuantity); - exerciseRepository.exercise.exercisePlanDetailId = exercisePlanDetailId; + exerciseRepository.exercise!.exercisePlanDetailId = exercisePlanDetailId; exerciseRepository.start = DateTime.now(); - exerciseRepository.setCustomer(Cache().userLoggedIn); + exerciseRepository.setCustomer(Cache().userLoggedIn!); } - double quantity; - double unitQuantity; - @override Stream mapEventToState( TestSetNewEvent event, diff --git a/lib/bloc/test_set_new/test_set_new_event.dart b/lib/bloc/test_set_new/test_set_new_event.dart index 4390db6..3b70cf6 100644 --- a/lib/bloc/test_set_new/test_set_new_event.dart +++ b/lib/bloc/test_set_new/test_set_new_event.dart @@ -13,7 +13,7 @@ class TestSetNewLoad extends TestSetNewEvent { class TestSetNewChangeQuantity extends TestSetNewEvent { final double quantity; - const TestSetNewChangeQuantity({this.quantity}); + const TestSetNewChangeQuantity({required this.quantity}); @override List get props => [quantity]; @@ -21,7 +21,7 @@ class TestSetNewChangeQuantity extends TestSetNewEvent { class TestSetNewChangeQuantityUnit extends TestSetNewEvent { final double quantity; - const TestSetNewChangeQuantityUnit({this.quantity}); + const TestSetNewChangeQuantityUnit({required this.quantity}); @override List get props => [quantity]; diff --git a/lib/bloc/test_set_new/test_set_new_state.dart b/lib/bloc/test_set_new/test_set_new_state.dart index ac0998b..d5d42d8 100644 --- a/lib/bloc/test_set_new/test_set_new_state.dart +++ b/lib/bloc/test_set_new/test_set_new_state.dart @@ -21,7 +21,7 @@ class TestSetNewReady extends TestSetNewState { class TestSetNewError extends TestSetNewState { final String message; - const TestSetNewError({this.message}); + const TestSetNewError({required this.message}); @override List get props => [message]; diff --git a/lib/bloc/timer/timer_bloc.dart b/lib/bloc/timer/timer_bloc.dart index 1abb16f..cf1d29b 100644 --- a/lib/bloc/timer/timer_bloc.dart +++ b/lib/bloc/timer/timer_bloc.dart @@ -1,6 +1,6 @@ import 'dart:async'; -import 'package:audioplayer/audioplayer.dart'; +//import 'package:audioplayer/audioplayer.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; @@ -8,7 +8,7 @@ part 'timer_event.dart'; part 'timer_state.dart'; class Ticker { - Stream tick({int ticks}) { + Stream tick({required int ticks}) { return Stream.periodic(Duration(seconds: 1), (x) => compute(ticks, x)).take(ticks); } @@ -22,11 +22,12 @@ class TimerBloc extends Bloc { final Ticker _ticker = Ticker(); int _duration = 0; - final AudioPlayer audioPlayer = AudioPlayer(); + //final AudioPlayer audioPlayer = AudioPlayer(); int minutes = 0; int seconds = 0; - StreamSubscription _tickerSubscription; + // ignore: cancel_subscriptions + StreamSubscription? _tickerSubscription; TimerBloc() : super(TimerReady(300)); @@ -52,21 +53,27 @@ class TimerBloc extends Bloc { yield* _mapTickToState(event); } else if (event is TimerEnd) { print("$event"); - _tickerSubscription?.cancel(); + if (_tickerSubscription != null) { + _tickerSubscription!.cancel(); + } yield TimerFinished(state.duration); } } @override Future close() { - _tickerSubscription?.cancel(); + if (_tickerSubscription != null) { + _tickerSubscription!.cancel(); + } return super.close(); } Stream _mapStartToState(TimerStart start) async* { //print("$start"); yield TimerRunning(start.duration); - _tickerSubscription?.cancel(); + if (_tickerSubscription != null) { + _tickerSubscription!.cancel(); + } _tickerSubscription = _ticker.tick(ticks: start.duration).listen( (localDuration) { //print("local: $localDuration"); @@ -77,14 +84,19 @@ class TimerBloc extends Bloc { Stream _mapPauseToState(TimerPause pause) async* { if (state is TimerRunning) { - _tickerSubscription?.pause(); + if (_tickerSubscription != null) { + _tickerSubscription!.pause(); + } yield TimerPaused(state.duration); } } Stream _mapResumeToState(TimerResume pause) async* { if (state is TimerPaused) { - _tickerSubscription?.resume(); + if (_tickerSubscription != null) { + _tickerSubscription!.resume(); + } + yield TimerRunning(state.duration); } } @@ -100,7 +112,7 @@ class TimerBloc extends Bloc { yield tick.duration >= 0 ? TimerRunning(tick.duration) : TimerFinished(tick.duration); } - Future _play() async { + /* Future _play() async { await audioPlayer.play('asset/wine-glass.mp3', isLocal: true); - } + } */ } diff --git a/lib/bloc/timer/timer_event.dart b/lib/bloc/timer/timer_event.dart index 0d935a1..7732103 100644 --- a/lib/bloc/timer/timer_event.dart +++ b/lib/bloc/timer/timer_event.dart @@ -9,7 +9,7 @@ abstract class TimerEvent extends Equatable { class TimerStart extends TimerEvent { final int duration; - const TimerStart({this.duration}); + const TimerStart({required this.duration}); @override String toString() => "TimerStart { duration: $duration }"; @@ -17,12 +17,12 @@ class TimerStart extends TimerEvent { class TimerEnd extends TimerEvent { final int duration; - const TimerEnd({this.duration}); + const TimerEnd({required this.duration}); } class TimerTick extends TimerEvent { final int duration; - const TimerTick({this.duration}); + const TimerTick({required this.duration}); @override String toString() => "Tick { duration: $duration }"; diff --git a/lib/bloc/timer/timer_state.dart b/lib/bloc/timer/timer_state.dart index 0c69778..426911a 100644 --- a/lib/bloc/timer/timer_state.dart +++ b/lib/bloc/timer/timer_state.dart @@ -45,5 +45,5 @@ class TimerFinished extends TimerState { class TimerError extends TimerState { final String message; - TimerError(int duration, {this.message}) : super(duration); + TimerError(int duration, {required this.message}) : super(duration); } diff --git a/lib/helper/database.dart b/lib/helper/database.dart index 4e807dd..63d8768 100644 --- a/lib/helper/database.dart +++ b/lib/helper/database.dart @@ -5,7 +5,7 @@ import 'package:sqflite/sqflite.dart'; class DB { static final DB _singleton = DB._internal(); String dbName = "workouttest.db"; - Database _db; + late Database _db; factory DB() { return _singleton; @@ -30,9 +30,7 @@ class DB { } Future closeDb() async { - if ( _db != null ) { - this._db.close(); - } + this._db.close(); } Database getDB() => this._db; diff --git a/lib/library/clock.dart b/lib/library/clock.dart index fcd8356..a4d9242 100644 --- a/lib/library/clock.dart +++ b/lib/library/clock.dart @@ -1,9 +1,11 @@ -import 'package:aitrainer_app/bloc/timer/timer_bloc.dart'; +import 'dart:math'; + import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'dart:math'; import 'package:google_fonts/google_fonts.dart'; +import 'package:aitrainer_app/bloc/timer/timer_bloc.dart'; + final temperatureColors = [ const Color(0xFFB50DE2), // -20 Celsius , friggin cold const Color(0xFFAE0DE2), @@ -42,7 +44,7 @@ class Clock extends StatelessWidget { final TimerBloc bloc; final List colors = temperatureColors; - Clock({this.bloc}); + Clock({required this.bloc}); // ignore: close_sinks @@ -109,10 +111,10 @@ class ArcPainter extends CustomPainter { List _gradient; - Offset center; + Offset? center; double _radius; - Paint paintMarkerEmpty; + late Paint paintMarkerEmpty; ArcPainter( this._progress, @@ -132,7 +134,7 @@ class ArcPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { center = Offset(size.width / 2, size.height / 2); - var rect = Rect.fromCircle(center: center, radius: this._radius); + var rect = Rect.fromCircle(center: center!, radius: this._radius); final gradient2 = new SweepGradient( startAngle: -pi / 2, diff --git a/lib/library/dropdown_search.dart b/lib/library/dropdown_search.dart deleted file mode 100644 index b15de21..0000000 --- a/lib/library/dropdown_search.dart +++ /dev/null @@ -1,529 +0,0 @@ -library dropdown_search; - -import 'dart:async'; - -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; - -import 'popup_menu.dart'; -import 'select_dialog.dart'; - -typedef Future> DropdownSearchOnFind(String text); -typedef String DropdownSearchItemAsString(T item); -typedef bool DropdownSearchFilterFn(T item, String filter); -typedef bool DropdownSearchCompareFn(T item, T selectedItem); -typedef Widget DropdownSearchBuilder(BuildContext context, T selectedItem, String itemAsString); -typedef Widget DropdownSearchPopupItemBuilder( - BuildContext context, - T item, - bool isSelected, -); -typedef bool DropdownSearchPopupItemEnabled(T item); -typedef Widget ErrorBuilder(BuildContext context, String searchEntry, dynamic exception); -typedef Widget EmptyBuilder(BuildContext context, String searchEntry); -typedef Widget LoadingBuilder(BuildContext context, String searchEntry); -typedef Widget IconButtonBuilder(BuildContext context); -typedef Future BeforeChange(T prevItem, T nextItem); - -enum Mode { DIALOG, BOTTOM_SHEET, MENU } - -class DropdownSearch extends StatefulWidget { - ///DropDownSearch label - final String label; - - ///DropDownSearch hint - final String hint; - - ///show/hide the search box - final bool showSearchBox; - - ///true if the filter on items is applied onlie (via API) - final bool isFilteredOnline; - - ///show/hide clear selected item - final bool showClearButton; - - ///offline items list - final List items; - - ///selected item - final T selectedItem; - - ///function that returns item from API - final DropdownSearchOnFind onFind; - - ///called when a new item is selected - final ValueChanged onChanged; - - ///to customize list of items UI - final DropdownSearchBuilder dropdownBuilder; - - ///to customize selected item - final DropdownSearchPopupItemBuilder popupItemBuilder; - - ///decoration for search box - final InputDecoration searchBoxDecoration; - - ///the title for dialog/menu/bottomSheet - final Color popupBackgroundColor; - - ///custom widget for the popup title - final Widget popupTitle; - - ///customize the fields the be shown - final DropdownSearchItemAsString itemAsString; - - /// custom filter function - final DropdownSearchFilterFn filterFn; - - ///enable/disable dropdownSearch - final bool enabled; - - ///MENU / DIALOG/ BOTTOM_SHEET - final Mode mode; - - ///the max height for dialog/bottomSheet/Menu - final double maxHeight; - - ///the max width for the dialog - final double dialogMaxWidth; - - ///select the selected item in the menu/dialog/bottomSheet of items - final bool showSelectedItem; - - ///function that compares two object with the same type to detected if it's the selected item or not - final DropdownSearchCompareFn compareFn; - - ///dropdownSearch input decoration - final InputDecoration dropdownSearchDecoration; - - ///custom layout for empty results - final EmptyBuilder emptyBuilder; - - ///custom layout for loading items - final LoadingBuilder loadingBuilder; - - ///custom layout for error - final ErrorBuilder errorBuilder; - - ///the search box will be focused if true - final bool autoFocusSearchBox; - - ///custom shape for the popup - final ShapeBorder popupShape; - - final AutovalidateMode autoValidateMode; - - /// An optional method to call with the final value when the form is saved via - final FormFieldSetter onSaved; - - /// An optional method that validates an input. Returns an error string to - /// display if the input is invalid, or null otherwise. - final FormFieldValidator validator; - - ///custom dropdown clear button icon widget - final Widget clearButton; - - ///custom clear button widget builder - final IconButtonBuilder clearButtonBuilder; - - ///custom dropdown icon button widget - final Widget dropDownButton; - - ///custom dropdown button widget builder - final IconButtonBuilder dropdownButtonBuilder; - - ///whether to manage the clear and dropdown icons via InputDecoration suffixIcon - final bool showAsSuffixIcons; - - ///If true, the dropdownBuilder will continue the uses of material behavior - ///This will be useful if you want to handle a custom UI only if the item !=null - final bool dropdownBuilderSupportsNullItem; - - ///defines if an item of the popup is enabled or not, if the item is disabled, - ///it cannot be clicked - final DropdownSearchPopupItemEnabled popupItemDisabled; - - ///set a custom color for the popup barrier - final Color popupBarrierColor; - - ///text controller to set default search word for example - final TextEditingController searchBoxController; - - ///called when popup is dismissed - final VoidCallback onPopupDismissed; - - /// callback executed before applying value change - ///delay before searching, change it to Duration(milliseconds: 0) - ///if you do not use online search - final Duration searchDelay; - - /// callback executed before applying value change - final BeforeChange onBeforeChange; - - DropdownSearch({ - Key key, - this.onSaved, - this.validator, - this.autoValidateMode = AutovalidateMode.disabled, - this.onChanged, - this.mode = Mode.DIALOG, - this.label, - this.hint, - this.isFilteredOnline = false, - this.popupTitle, - this.items, - this.selectedItem, - this.onFind, - this.dropdownBuilder, - this.popupItemBuilder, - this.showSearchBox = false, - this.showClearButton = false, - this.searchBoxDecoration, - this.popupBackgroundColor, - this.enabled = true, - this.maxHeight, - this.filterFn, - this.itemAsString, - this.showSelectedItem = false, - this.compareFn, - this.dropdownSearchDecoration, - this.emptyBuilder, - this.loadingBuilder, - this.errorBuilder, - this.autoFocusSearchBox = false, - this.dialogMaxWidth, - this.clearButton, - this.clearButtonBuilder, - this.dropDownButton, - this.dropdownButtonBuilder, - this.showAsSuffixIcons = false, - this.dropdownBuilderSupportsNullItem = false, - this.popupShape, - this.popupItemDisabled, - this.popupBarrierColor, - this.onPopupDismissed, - this.searchBoxController, - this.searchDelay, - this.onBeforeChange, - }) : assert(isFilteredOnline != null), - assert(dropdownBuilderSupportsNullItem != null), - assert(enabled != null), - assert(showSelectedItem != null), - assert(autoFocusSearchBox != null), - assert(showClearButton != null), - assert(showSearchBox != null), - assert(!showSelectedItem || T == String || compareFn != null), - super(key: key); - - @override - DropdownSearchState createState() => DropdownSearchState(); -} - -class DropdownSearchState extends State> { - final ValueNotifier _selectedItemNotifier = ValueNotifier(null); - final ValueNotifier _isFocused = ValueNotifier(false); - - @override - void initState() { - super.initState(); - _selectedItemNotifier.value = widget.selectedItem; - } - - @override - void didUpdateWidget(DropdownSearch oldWidget) { - final oldSelectedItem = oldWidget.selectedItem; - final newSelectedItem = widget.selectedItem; - if (oldSelectedItem != newSelectedItem) { - _selectedItemNotifier.value = newSelectedItem; - } - super.didUpdateWidget(oldWidget); - } - - @override - Widget build(BuildContext context) { - return ValueListenableBuilder( - valueListenable: _selectedItemNotifier, - builder: (context, T data, wt) { - return IgnorePointer( - ignoring: !widget.enabled, - child: GestureDetector( - onTap: () => _selectSearchMode(data), - child: _formField(data), - ), - ); - }, - ); - } - - Widget _defaultSelectItemWidget(T data) { - return Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: widget.dropdownBuilder != null - ? widget.dropdownBuilder( - context, - data, - _selectedItemAsString(data), - ) - : Text(_selectedItemAsString(data), style: Theme.of(context).textTheme.subtitle1), - ), - if (!widget.showAsSuffixIcons) _manageTrailingIcons(data), - ], - ); - } - - Widget _formField(T value) { - return FormField( - enabled: widget.enabled, - onSaved: widget.onSaved, - validator: widget.validator, - autovalidateMode: widget.autoValidateMode, - initialValue: widget.selectedItem, - builder: (FormFieldState state) { - if (state.value != value) { - WidgetsBinding.instance.addPostFrameCallback((_) { - state.didChange(value); - }); - } - return ValueListenableBuilder( - valueListenable: _isFocused, - builder: (context, bool isFocused, w) { - return InputDecorator( - isEmpty: value == null && (widget.dropdownBuilder == null || widget.dropdownBuilderSupportsNullItem), - isFocused: isFocused, - decoration: _manageDropdownDecoration(state, value), - child: _defaultSelectItemWidget(value), - ); - }); - }, - ); - } - - ///manage dropdownSearch field decoration - InputDecoration _manageDropdownDecoration(FormFieldState state, T data) { - return (widget.dropdownSearchDecoration ?? - InputDecoration(contentPadding: EdgeInsets.fromLTRB(12, 12, 0, 0), border: OutlineInputBorder())) - .applyDefaults(Theme.of(state.context).inputDecorationTheme) - .copyWith( - enabled: widget.enabled, - labelText: widget.label, - hintText: widget.hint, - suffixIcon: widget.showAsSuffixIcons ? _manageTrailingIcons(data) : null, - errorText: state.errorText); - } - - ///function that return the String value of an object - String _selectedItemAsString(T data) { - if (data == null) { - return ""; - } else if (widget.itemAsString != null) { - return widget.itemAsString(data); - } else { - return data.toString(); - } - } - - ///function that manage Trailing icons(close, dropDown) - Widget _manageTrailingIcons(T data) { - final clearButtonPressed = () => _handleOnChangeSelectedItem(null); - final dropdownButtonPressed = () => _selectSearchMode(data); - - return Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.end, - children: [ - if (data != null && widget.showClearButton) - widget.clearButtonBuilder != null - ? GestureDetector( - onTap: clearButtonPressed, - child: widget.clearButtonBuilder(context), - ) - : IconButton( - icon: widget.clearButton ?? const Icon(Icons.clear, size: 24), - onPressed: clearButtonPressed, - ), - widget.dropdownButtonBuilder != null - ? GestureDetector( - onTap: dropdownButtonPressed, - child: widget.dropdownButtonBuilder(context), - ) - : IconButton( - icon: widget.dropDownButton ?? const Icon(Icons.arrow_drop_down, size: 24), - onPressed: dropdownButtonPressed, - ), - ], - ); - } - - ///open dialog - Future _openSelectDialog(T data) { - return showGeneralDialog( - barrierDismissible: true, - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - transitionDuration: const Duration(milliseconds: 400), - barrierColor: widget.popupBarrierColor ?? const Color(0x80000000), - context: context, - pageBuilder: (context, animation, secondaryAnimation) { - return AlertDialog( - contentPadding: EdgeInsets.all(0), - shape: widget.popupShape, - backgroundColor: widget.popupBackgroundColor, - content: _selectDialogInstance(data), - ); - }, - ); - } - - ///open BottomSheet (Dialog mode) - Future _openBottomSheet(T data) { - return showModalBottomSheet( - barrierColor: widget.popupBarrierColor, - isScrollControlled: true, - backgroundColor: widget.popupBackgroundColor, - shape: widget.popupShape, - context: context, - builder: (context) { - return AnimatedPadding( - duration: Duration(milliseconds: 300), - padding: EdgeInsets.only( - bottom: MediaQuery.of(context).viewInsets.bottom, - ), - child: _selectDialogInstance(data, defaultHeight: 350), - ); - }); - } - - ///openMenu - Future _openMenu(T data) { - // Here we get the render object of our physical button, later to get its size & position - final RenderBox popupButtonObject = context.findRenderObject(); - // Get the render object of the overlay used in `Navigator` / `MaterialApp`, i.e. screen size reference - final RenderBox overlay = Overlay.of(context).context.findRenderObject(); - // Calculate the show-up area for the dropdown using button's size & position based on the `overlay` used as the coordinate space. - final RelativeRect position = RelativeRect.fromSize( - Rect.fromPoints( - popupButtonObject.localToGlobal(popupButtonObject.size.bottomLeft(Offset.zero), ancestor: overlay), - popupButtonObject.localToGlobal(popupButtonObject.size.bottomRight(Offset.zero), ancestor: overlay), - ), - Size(overlay.size.width, overlay.size.height), - ); - return customShowMenu( - barrierColor: widget.popupBarrierColor, - shape: widget.popupShape, - color: widget.popupBackgroundColor, - context: context, - position: position, - elevation: 8, - items: [ - CustomPopupMenuItem( - enabled: false, - child: Container( - width: popupButtonObject.size.width, - child: _selectDialogInstance(data, defaultHeight: 224), - ), - ), - ]); - } - - SelectDialog _selectDialogInstance(T data, {double defaultHeight}) { - return SelectDialog( - popupTitle: widget.popupTitle, - maxHeight: widget.maxHeight ?? defaultHeight, - isFilteredOnline: widget.isFilteredOnline, - itemAsString: widget.itemAsString, - filterFn: widget.filterFn, - items: widget.items, - onFind: widget.onFind, - showSearchBox: widget.showSearchBox, - itemBuilder: widget.popupItemBuilder, - selectedValue: data, - searchBoxDecoration: widget.searchBoxDecoration, - onChanged: _handleOnChangeSelectedItem, - showSelectedItem: widget.showSelectedItem, - compareFn: widget.compareFn, - emptyBuilder: widget.emptyBuilder, - loadingBuilder: widget.loadingBuilder, - errorBuilder: widget.errorBuilder, - autoFocusSearchBox: widget.autoFocusSearchBox, - dialogMaxWidth: widget.dialogMaxWidth, - itemDisabled: widget.popupItemDisabled, - searchBoxController: widget.searchBoxController ?? TextEditingController(), - searchDelay: widget.searchDelay, - ); - } - - ///Function that manage focus listener - ///set true only if the widget already not focused to prevent unnecessary build - ///same thing for clear focus, - void _handleFocus(bool isFocused) { - if (isFocused && !_isFocused.value) { - FocusScope.of(context).unfocus(); - _isFocused.value = true; - } else if (!isFocused && _isFocused.value) _isFocused.value = false; - } - - ///handle on change value , if the validation is active , we validate the new selected item - void _handleOnChangeSelectedItem(T selectedItem) { - final changeItem = () { - _selectedItemNotifier.value = selectedItem; - if (widget.onChanged != null) widget.onChanged(selectedItem); - }; - - if (widget.onBeforeChange != null) { - widget.onBeforeChange(_selectedItemNotifier.value, selectedItem).then((value) { - if (value == true) { - changeItem(); - } - }); - } else { - changeItem(); - } - - _handleFocus(false); - } - - ///Function that return then UI based on searchMode - ///[data] selected item to be passed to the UI - ///If we close the popup , or maybe we just selected - ///another widget we should clear the focus - Future _selectSearchMode(T data) async { - _handleFocus(true); - T selectedItem; - if (widget.mode == Mode.MENU) { - selectedItem = await _openMenu(data); - } else if (widget.mode == Mode.BOTTOM_SHEET) { - selectedItem = await _openBottomSheet(data); - } else { - selectedItem = await _openSelectDialog(data); - } - _handleFocus(false); - widget.onPopupDismissed?.call(); - - return selectedItem; - } - - ///Public Function that return then UI based on searchMode - ///[data] selected item to be passed to the UI - ///If we close the popup , or maybe we just selected - ///another widget we should clear the focus - ///THIS USED FOR OPEN DROPDOWN_SEARCH PROGRAMMATICALLY, - ///otherwise you can you [_selectSearchMode] - Future openDropDownSearch() => _selectSearchMode(_selectedItemNotifier.value); - - ///Change selected Value; this function is public USED to change the selected - ///value PROGRAMMATICALLY, Otherwise you can use [_handleOnChangeSelectedItem] - void changeSelectedItem(T selectedItem) => _handleOnChangeSelectedItem(selectedItem); - - ///Change selected Value; this function is public USED to clear selected - ///value PROGRAMMATICALLY, Otherwise you can use [_handleOnChangeSelectedItem] - void clear() => _handleOnChangeSelectedItem(null); - - ///get selected value programmatically - T get getSelectedItem => _selectedItemNotifier.value; - - ///check if the dropdownSearch is focused - bool get isFocused => _isFocused.value; -} diff --git a/lib/library/fade_in.dart b/lib/library/fade_in.dart index 42a0a4b..12d9e0f 100644 --- a/lib/library/fade_in.dart +++ b/lib/library/fade_in.dart @@ -16,9 +16,9 @@ class FadeIn extends StatefulWidget { final Curve curve; const FadeIn({ - Key key, - this.controller, - this.child, + Key? key, + required this.controller, + required this.child, this.duration = const Duration(milliseconds: 250), this.curve = Curves.easeIn, }) : super(key: key); @@ -57,8 +57,8 @@ class FadeInController { } class _FadeInState extends State with TickerProviderStateMixin { - AnimationController _controller; - StreamSubscription _listener; + late AnimationController _controller; + late StreamSubscription _listener; @override void initState() { @@ -71,11 +71,11 @@ class _FadeInState extends State with TickerProviderStateMixin { _setupCurve(); - if (widget.controller?.autoStart != false) { + if (widget.controller.autoStart != false) { fadeIn(); } - _listen(); + _listener = widget.controller.stream.listen(_onAction); } void _setupCurve() { @@ -87,17 +87,6 @@ class _FadeInState extends State with TickerProviderStateMixin { ).animate(curve); } - void _listen() { - if (_listener != null) { - _listener.cancel(); - _listener = null; - } - - if (widget.controller != null) { - _listener = widget.controller.stream.listen(_onAction); - } - } - void _onAction(FadeInAction action) { switch (action) { case FadeInAction.fadeIn: @@ -112,7 +101,7 @@ class _FadeInState extends State with TickerProviderStateMixin { @override void didUpdateWidget(FadeIn oldWidget) { if (oldWidget.controller != widget.controller) { - _listen(); + _listener = widget.controller.stream.listen(_onAction); } if (oldWidget.duration != widget.duration) { @@ -129,6 +118,7 @@ class _FadeInState extends State with TickerProviderStateMixin { @override void dispose() { _controller.dispose(); + _listener.cancel(); super.dispose(); } diff --git a/lib/library/flurry.dart b/lib/library/flurry.dart new file mode 100644 index 0000000..4d9f17b --- /dev/null +++ b/lib/library/flurry.dart @@ -0,0 +1,39 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; + +class Flurry { + static const MethodChannel _channel = const MethodChannel('flurry'); + + static Future get platformVersion async { + final String version = await _channel.invokeMethod('getPlatformVersion'); + return version; + } + + static Future initialize({String androidKey = "", String iosKey = "", bool enableLog = true}) async { + Map args = {}; + args.putIfAbsent("api_key_android", () => androidKey); + args.putIfAbsent("api_key_ios", () => iosKey); + args.putIfAbsent("is_log_enabled", () => enableLog); + + await _channel.invokeMethod('initialize', args); + + return null; + } + + static Future logEvent(String message) async { + Map args = {}; + args.putIfAbsent("message", () => message); + + await _channel.invokeMethod('logEvent', args); + return null; + } + + static Future setUserId(String userId) async { + Map args = {}; + args.putIfAbsent("userId", () => userId); + + await _channel.invokeMethod('userId', args); + return null; + } +} diff --git a/lib/library/gradient_bottom_navigation_bar.dart b/lib/library/gradient_bottom_navigation_bar.dart index f069acd..ee63338 100644 --- a/lib/library/gradient_bottom_navigation_bar.dart +++ b/lib/library/gradient_bottom_navigation_bar.dart @@ -119,21 +119,17 @@ class GradientBottomNavigationBar extends StatefulWidget { /// [ThemeData.primaryColor], is used. However if [GradientBottomNavigationBar.type] is /// [BottomNavigationBarType.shifting] then [fixedColor] is ignored. GradientBottomNavigationBar({ - Key key, - @required this.items, - this.onTap, - @required this.backgroundColorStart, - @required this.backgroundColorEnd, + Key? key, + required this.items, + required this.onTap, + required this.backgroundColorStart, + required this.backgroundColorEnd, this.currentIndex = 0, - BottomNavigationBarType type, - this.fixedColor, + BottomNavigationBarType? type, + this.fixedColor = Colors.white, this.iconSize = 24.0, - }) : assert(items != null), - assert(items.length >= 2), - assert(backgroundColorStart != null), - assert(backgroundColorEnd != null), + }) : assert(items.length >= 2), assert(0 <= currentIndex && currentIndex < items.length), - assert(iconSize != null), type = type ?? (items.length <= 3 ? BottomNavigationBarType.fixed : BottomNavigationBarType.shifting), super(key: key); @@ -188,30 +184,30 @@ class _BottomNavigationTile extends StatelessWidget { this.item, this.animation, this.iconSize, { - this.onTap, + required this.onTap, this.colorTween, this.flex, this.selected = false, - this.indexLabel, - }) : assert(selected != null); + required this.indexLabel, + }); final BottomNavigationBarType type; final BottomNavigationBarItem item; final Animation animation; final double iconSize; final VoidCallback onTap; - final ColorTween colorTween; - final double flex; + final ColorTween? colorTween; + final double? flex; final bool selected; final String indexLabel; Widget _buildIcon() { double tweenStart; - Color iconColor; + Color? iconColor; switch (type) { case BottomNavigationBarType.fixed: tweenStart = 8.0; - iconColor = colorTween.evaluate(animation); + iconColor = colorTween!.evaluate(animation); break; case BottomNavigationBarType.shifting: tweenStart = 16.0; @@ -248,7 +244,7 @@ class _BottomNavigationTile extends StatelessWidget { child: DefaultTextStyle.merge( style: TextStyle( fontSize: _kActiveFontSize, - color: colorTween.evaluate(animation), + color: colorTween!.evaluate(animation), ), // The font size should grow here when active, but because of the way // font rendering works, it doesn't grow smoothly if we just animate @@ -293,7 +289,7 @@ class _BottomNavigationTile extends StatelessWidget { fontSize: _kActiveFontSize, color: Colors.white, ), - child: item.title, + child: item.title!, ), ), ), @@ -314,7 +310,7 @@ class _BottomNavigationTile extends StatelessWidget { label = _buildFixedLabel(); break; case BottomNavigationBarType.shifting: - size = (flex * 1000.0).round(); + size = (flex! * 1000.0).round(); label = _buildShiftingLabel(); break; } @@ -350,14 +346,14 @@ class _BottomNavigationTile extends StatelessWidget { class _GradientBottomNavigationBarState extends State with TickerProviderStateMixin { List _controllers = []; - List _animations; + late List _animations; // A queue of color splashes currently being animated. final Queue<_Circle> _circles = Queue<_Circle>(); // Last splash circle's color, and the final color of the control after // animation is complete. - Color _backgroundColor; + late Color _backgroundColor; static final Animatable _flexTween = Tween(begin: 1.0, end: 1.5); @@ -380,7 +376,7 @@ class _GradientBottomNavigationBarState extends State _createTiles() { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - assert(localizations != null); + final List children = []; switch (widget.type) { case BottomNavigationBarType.fixed: final ThemeData themeData = Theme.of(context); final TextTheme textTheme = themeData.textTheme; - Color themeColor; - switch (themeData.brightness) { - case Brightness.light: - themeColor = themeData.primaryColor; - break; - case Brightness.dark: - themeColor = themeData.accentColor; - break; - } + final ColorTween colorTween = ColorTween( - begin: textTheme.caption.color, - end: widget.fixedColor ?? themeColor, + begin: textTheme.caption!.color, + end: widget.fixedColor, ); for (int i = 0; i < widget.items.length; i += 1) { children.add( @@ -488,9 +476,7 @@ class _GradientBottomNavigationBarState extends State widget.onTap(i), colorTween: colorTween, selected: i == widget.currentIndex, indexLabel: localizations.tabLabel(tabIndex: i + 1, tabCount: widget.items.length), @@ -506,9 +492,7 @@ class _GradientBottomNavigationBarState extends State widget.onTap(i), flex: _evaluateFlex(_animations[i]), selected: i == widget.currentIndex, indexLabel: localizations.tabLabel(tabIndex: i + 1, tabCount: widget.items.length), @@ -599,13 +583,11 @@ class _GradientBottomNavigationBarState extends State> animations) { @@ -646,10 +628,9 @@ class _Circle { // Paints the animating color splash circles. class _RadialPainter extends CustomPainter { _RadialPainter({ - @required this.circles, - @required this.textDirection, - }) : assert(circles != null), - assert(textDirection != null); + required this.circles, + required this.textDirection, + }); final List<_Circle> circles; final TextDirection textDirection; diff --git a/lib/library/image_cache.dart b/lib/library/image_cache.dart index d37d2d3..16ff14e 100644 --- a/lib/library/image_cache.dart +++ b/lib/library/image_cache.dart @@ -4,7 +4,7 @@ import 'package:aitrainer_app/service/logging.dart'; import 'package:aitrainer_app/util/not_found_exception.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; -import 'package:network_image_to_byte/network_image_to_byte.dart'; +import 'package:aitrainer_app/library//network_image_to_byte.dart'; import 'dart:collection'; class ImageCache with Logging { @@ -31,7 +31,7 @@ class ImageCache with Logging { return _imageMap[imageKey] != null && _imageMap[imageKey] == true; } - String getImageString(int id, String url) { + String? getImageString(int id, String url) { final String imageKey = generateMd5(url + "_" + id.toString()); return _images[imageKey]; } @@ -40,11 +40,10 @@ class ImageCache with Logging { final String imageKey = generateMd5(url + "_" + id.toString()); // get from storage - final String imageString = await getImageAs64BaseString(id, url); - if (imageString != null) { - _images[imageKey] = imageString; - _imageMap[imageKey] = true; - } + final String imageString = (await getImageAs64BaseString(id, url))!; + + _images[imageKey] = imageString; + _imageMap[imageKey] = true; /* final String imageString = await getImageAs64BaseString(id, url); if (imageString != null) { @@ -67,8 +66,8 @@ class ImageCache with Logging { return; } - Future loadImageFromPrefs(String key) async { - String value = await storage.read(key: key); + Future loadImageFromPrefs(String key) async { + String? value = await storage.read(key: key); return value; } @@ -83,47 +82,40 @@ class ImageCache with Logging { // decode bytes from a string Image imageFrom64BaseString(String base64String) { - if (base64String == null) { - return null; - } return Image.memory( base64Decode(base64String), fit: BoxFit.fill, ); } - Future getImage(int id, String name) async { - if (storage == null) { - return null; - } - - if (name == null || name.length == 0) { + Future getImage(int id, String name) async { + if (name.length == 0) { return null; } final String imageKey = generateMd5(name + "_" + id.toString()); - final String imageString = await storage.read(key: imageKey); + final String? imageString = await storage.read(key: imageKey); + if (imageString == null) { + return null; + } final Image image = imageFrom64BaseString(imageString); return image; } - Future getImageAs64BaseString(int id, String name) async { - if (name == null) { - return null; - } + Future getImageAs64BaseString(int id, String name) async { final String imageKey = generateMd5(name + "_" + id.toString()); - String imageString; + String? imageString; if (await storage.containsKey(key: imageKey)) { //log(" .. get from storage"); imageString = await storage.read(key: imageKey); } else { - imageString = await downloadAndSaveImage(id, name); + imageString = (await downloadAndSaveImage(id, name))!; //log(" .. downloaded"); } return imageString; } - Future downloadAndSaveImage(int id, String url) async { + Future downloadAndSaveImage(int id, String url) async { final String imageKey = generateMd5(url + "_" + id.toString()); if (!await existImageInPrefs(imageKey)) { try { @@ -143,12 +135,7 @@ class ImageCache with Logging { } } else { //log(" .. from storage"); - final String storageString = await storage.read(key: imageKey); - if (storageString != null) { - //log(" .. storage String: " + storageString); - } else { - // log(" .. storage String is NULL"); - } + //await storage.read(key: imageKey); } return null; } diff --git a/lib/library/network_image_to_byte.dart b/lib/library/network_image_to_byte.dart new file mode 100644 index 0000000..6a1fe74 --- /dev/null +++ b/lib/library/network_image_to_byte.dart @@ -0,0 +1,14 @@ +library network_image_to_byte; + +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart'; + +Future networkImageToByte(String path) async { + HttpClient httpClient = HttpClient(); + var request = await httpClient.getUrl(Uri.parse(path)); + var response = await request.close(); + Uint8List bytes = await consolidateHttpClientResponseBytes(response); + return bytes; +} diff --git a/lib/library/popup_menu.dart b/lib/library/popup_menu.dart deleted file mode 100644 index a969a4e..0000000 --- a/lib/library/popup_menu.dart +++ /dev/null @@ -1,599 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; -import 'package:flutter/widgets.dart'; - -const Duration _kMenuDuration = Duration(milliseconds: 300); -const double _kMenuCloseIntervalEnd = 2.0 / 3.0; -const double _kMenuHorizontalPadding = 0.0; -const double _kMenuMinWidth = 2.0 * _kMenuWidthStep; -const double _kMenuVerticalPadding = 0.0; -const double _kMenuWidthStep = 1.0; -const double _kMenuScreenPadding = 0.0; - -// This widget only exists to enable _PopupMenuRoute to save the sizes of -// each menu item. The sizes are used by _PopupMenuRouteLayout to compute the -// y coordinate of the menu's origin so that the center of selected menu -// item lines up with the center of its PopupMenuButton. -class _MenuItem extends SingleChildRenderObjectWidget { - const _MenuItem({ - Key key, - @required this.onLayout, - Widget child, - }) : assert(onLayout != null), - super(key: key, child: child); - - final ValueChanged onLayout; - - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderMenuItem(onLayout); - } - - @override - void updateRenderObject(BuildContext context, covariant _RenderMenuItem renderObject) { - renderObject.onLayout = onLayout; - } -} - -class _RenderMenuItem extends RenderShiftedBox { - _RenderMenuItem(this.onLayout, [RenderBox child]) - : assert(onLayout != null), - super(child); - - ValueChanged onLayout; - - @override - void performLayout() { - if (child == null) { - size = Size.zero; - } else { - child.layout(constraints, parentUsesSize: true); - size = constraints.constrain(child.size); - } - final BoxParentData childParentData = child.parentData; - childParentData.offset = Offset.zero; - onLayout(size); - } -} - -/// An item in a material design popup menu. -/// -/// To show a popup menu, use the [customShowMenu] function. To create a button that -/// shows a popup menu, consider using [PopupMenuButton]. -/// -/// To show a checkmark next to a popup menu item, consider using -/// [CheckedPopupMenuItem]. -/// -/// Typically the [child] of a [CustomPopupMenuItem] is a [Text] widget. More -/// elaborate menus with icons can use a [ListTile]. By default, a -/// [CustomPopupMenuItem] is kMinInteractiveDimension pixels high. If you use a widget -/// with a different height, it must be specified in the [height] property. -/// -/// {@tool sample} -/// -/// Here, a [Text] widget is used with a popup menu item. The `WhyFarther` type -/// is an enum, not shown here. -/// -/// ```dart -/// const CustomPopupMenuItem( -/// value: WhyFarther.harder, -/// child: Text('Working a lot harder'), -/// ) -/// ``` -/// {@end-tool} -/// -/// See the example at [PopupMenuButton] for how this example could be used in a -/// complete menu, and see the example at [CheckedPopupMenuItem] for one way to -/// keep the text of [CustomPopupMenuItem]s that use [Text] widgets in their [child] -/// slot aligned with the text of [CheckedPopupMenuItem]s or of [CustomPopupMenuItem] -/// that use a [ListTile] in their [child] slot. -/// -/// See also: -/// -/// * [PopupMenuDivider], which can be used to divide items from each other. -/// * [CheckedPopupMenuItem], a variant of [CustomPopupMenuItem] with a checkmark. -/// * [customShowMenu], a method to dynamically show a popup menu at a given location. -/// * [PopupMenuButton], an [IconButton] that automatically shows a menu when -/// it is tapped. -class CustomPopupMenuItem extends PopupMenuEntry { - /// Creates an item for a popup menu. - /// - /// By default, the item is [enabled]. - /// - /// The `enabled` and `height` arguments must not be null. - const CustomPopupMenuItem({ - Key key, - this.value, - this.enabled = true, - this.height = kMinInteractiveDimension, - this.textStyle, - @required this.child, - }) : assert(enabled != null), - assert(height != null), - super(key: key); - - /// The value that will be returned by [customShowMenu] if this entry is selected. - final T value; - - /// Whether the user is permitted to select this item. - /// - /// Defaults to true. If this is false, then the item will not react to - /// touches. - final bool enabled; - - /// The minimum height height of the menu item. - /// - /// Defaults to [kMinInteractiveDimension] pixels. - @override - final double height; - - /// The text style of the popup menu item. - /// - /// If this property is null, then [PopupMenuThemeData.textStyle] is used. - /// If [PopupMenuThemeData.textStyle] is also null, then [ThemeData.textTheme.subhead] is used. - final TextStyle textStyle; - - /// The widget below this widget in the tree. - /// - /// Typically a single-line [ListTile] (for menus with icons) or a [Text]. An - /// appropriate [DefaultTextStyle] is put in scope for the child. In either - /// case, the text should be short enough that it won't wrap. - final Widget child; - - @override - bool represents(T value) => value == this.value; - - @override - PopupMenuItemState> createState() => PopupMenuItemState>(); -} - -/// The [State] for [CustomPopupMenuItem] subclasses. -/// -/// By default this implements the basic styling and layout of Material Design -/// popup menu items. -/// -/// The [buildChild] method can be overridden to adjust exactly what gets placed -/// in the menu. By default it returns [CustomPopupMenuItem.child]. -/// -/// The [handleTap] method can be overridden to adjust exactly what happens when -/// the item is tapped. By default, it uses [Navigator.pop] to return the -/// [CustomPopupMenuItem.value] from the menu route. -/// -/// This class takes two type arguments. The second, `W`, is the exact type of -/// the [Widget] that is using this [State]. It must be a subclass of -/// [CustomPopupMenuItem]. The first, `T`, must match the type argument of that widget -/// class, and is the type of values returned from this menu. -class PopupMenuItemState> extends State { - /// The menu item contents. - /// - /// Used by the [build] method. - /// - /// By default, this returns [CustomPopupMenuItem.child]. Override this to put - /// something else in the menu entry. - @protected - Widget buildChild() => widget.child; - - /// The handler for when the user selects the menu item. - /// - /// Used by the [InkWell] inserted by the [build] method. - /// - /// By default, uses [Navigator.pop] to return the [CustomPopupMenuItem.value] from - /// the menu route. - @protected - void handleTap() { - Navigator.pop(context, widget.value); - } - - @override - Widget build(BuildContext context) { - final ThemeData theme = Theme.of(context); - final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); - TextStyle style = widget.textStyle ?? popupMenuTheme.textStyle ?? theme.textTheme.subtitle1; - - if (!widget.enabled) style = style.copyWith(color: theme.disabledColor); - - Widget item = AnimatedDefaultTextStyle( - style: style, - duration: kThemeChangeDuration, - child: Container( - alignment: AlignmentDirectional.centerStart, - constraints: BoxConstraints(minHeight: widget.height), - padding: const EdgeInsets.symmetric(horizontal: _kMenuHorizontalPadding), - child: buildChild(), - ), - ); - - if (!widget.enabled) { - final bool isDark = theme.brightness == Brightness.dark; - item = IconTheme.merge( - data: IconThemeData(opacity: isDark ? 0.5 : 0.38), - child: item, - ); - } - - return InkWell( - onTap: widget.enabled ? handleTap : null, - canRequestFocus: widget.enabled, - child: item, - ); - } -} - -class _PopupMenu extends StatelessWidget { - const _PopupMenu({ - Key key, - this.route, - this.semanticLabel, - }) : super(key: key); - - final _PopupMenuRoute route; - final String semanticLabel; - - @override - Widget build(BuildContext context) { - final double unit = 1.0 / (route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. - final List children = []; - final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); - - for (int i = 0; i < route.items.length; i += 1) { - final double start = (i + 1) * unit; - final double end = (start + 1.5 * unit).clamp(0.0, 1.0); - final CurvedAnimation opacity = CurvedAnimation( - parent: route.animation, - curve: Interval(start, end), - ); - Widget item = route.items[i]; - if (route.initialValue != null && route.items[i].represents(route.initialValue)) { - item = Container( - color: Theme.of(context).highlightColor, - child: item, - ); - } - children.add( - _MenuItem( - onLayout: (Size size) { - route.itemSizes[i] = size; - }, - child: FadeTransition( - opacity: opacity, - child: item, - ), - ), - ); - } - - final CurveTween opacity = CurveTween(curve: const Interval(0.0, 1.0 / 3.0)); - final CurveTween width = CurveTween(curve: Interval(0.0, unit)); - final CurveTween height = CurveTween(curve: Interval(0.0, unit * route.items.length)); - - final Widget child = ConstrainedBox( - constraints: const BoxConstraints(minWidth: _kMenuMinWidth), - child: IntrinsicWidth( - stepWidth: _kMenuWidthStep, - child: Semantics( - scopesRoute: true, - namesRoute: true, - explicitChildNodes: true, - label: semanticLabel, - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(vertical: _kMenuVerticalPadding), - child: ListBody(children: children), - ), - ), - ), - ); - - return AnimatedBuilder( - animation: route.animation, - builder: (BuildContext context, Widget child) { - return Opacity( - opacity: opacity.evaluate(route.animation), - child: Material( - shape: route.shape ?? popupMenuTheme.shape, - color: route.color ?? popupMenuTheme.color, - type: MaterialType.card, - elevation: route.elevation ?? popupMenuTheme.elevation ?? 8.0, - child: Align( - alignment: AlignmentDirectional.topEnd, - widthFactor: width.evaluate(route.animation), - heightFactor: height.evaluate(route.animation), - child: child, - ), - ), - ); - }, - child: child, - ); - } -} - -// Positioning of the menu on the screen. -class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { - _PopupMenuRouteLayout(this.position, this.itemSizes, this.selectedItemIndex, this.textDirection); - - // Rectangle of underlying button, relative to the overlay's dimensions. - final RelativeRect position; - - // The sizes of each item are computed when the menu is laid out, and before - // the route is laid out. - List itemSizes; - - // The index of the selected item, or null if PopupMenuButton.initialValue - // was not specified. - final int selectedItemIndex; - - // Whether to prefer going to the left or to the right. - final TextDirection textDirection; - - // We put the child wherever position specifies, so long as it will fit within - // the specified parent size padded (inset) by 8. If necessary, we adjust the - // child's position so that it fits. - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - // The menu can be at most the size of the overlay minus 8.0 pixels in each - // direction. - return BoxConstraints.loose(constraints.biggest - const Offset(_kMenuScreenPadding * 2.0, _kMenuScreenPadding * 2.0)); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - // size: The size of the overlay. - // childSize: The size of the menu, when fully open, as determined by - // getConstraintsForChild. - - // Find the ideal vertical position. - double y = position.top; - if (selectedItemIndex != null && itemSizes != null) { - double selectedItemOffset = _kMenuVerticalPadding; - for (int index = 0; index < selectedItemIndex; index += 1) selectedItemOffset += itemSizes[index].height; - selectedItemOffset += itemSizes[selectedItemIndex].height / 2; - y = position.top + (size.height - position.top - position.bottom) / 2.0 - selectedItemOffset; - } - - // Find the ideal horizontal position. - double x; - if (position.left > position.right) { - // Menu button is closer to the right edge, so grow to the left, aligned to the right edge. - x = size.width - position.right - childSize.width; - } else if (position.left < position.right) { - // Menu button is closer to the left edge, so grow to the right, aligned to the left edge. - x = position.left; - } else { - // Menu button is equidistant from both edges, so grow in reading direction. - assert(textDirection != null); - switch (textDirection) { - case TextDirection.rtl: - x = size.width - position.right - childSize.width; - break; - case TextDirection.ltr: - x = position.left; - break; - } - } - - // Avoid going outside an area defined as the rectangle 8.0 pixels from the - // edge of the screen in every direction. - if (x < _kMenuScreenPadding) - x = _kMenuScreenPadding; - else if (x + childSize.width > size.width - _kMenuScreenPadding) x = size.width - childSize.width - _kMenuScreenPadding; - if (y < _kMenuScreenPadding) - y = _kMenuScreenPadding; - else if (y + childSize.height > size.height - _kMenuScreenPadding) y = size.height - childSize.height - _kMenuScreenPadding; - return Offset(x, y); - } - - @override - bool shouldRelayout(_PopupMenuRouteLayout oldDelegate) { - // If called when the old and new itemSizes have been initialized then - // we expect them to have the same length because there's no practical - // way to change length of the items list once the menu has been shown. - assert(itemSizes.length == oldDelegate.itemSizes.length); - - return position != oldDelegate.position || - selectedItemIndex != oldDelegate.selectedItemIndex || - textDirection != oldDelegate.textDirection || - !listEquals(itemSizes, oldDelegate.itemSizes); - } -} - -class _PopupMenuRoute extends PopupRoute { - _PopupMenuRoute({ - this.position, - this.items, - this.initialValue, - this.elevation, - this.theme, - this.popupMenuTheme, - this.barrierLabel, - this.semanticLabel, - this.shape, - this.color, - this.showMenuContext, - this.captureInheritedThemes, - this.barrierColor, - }) : itemSizes = List(items.length); - - final RelativeRect position; - final List> items; - final List itemSizes; - final dynamic initialValue; - final double elevation; - final ThemeData theme; - final String semanticLabel; - final ShapeBorder shape; - final Color color; - final PopupMenuThemeData popupMenuTheme; - final BuildContext showMenuContext; - final bool captureInheritedThemes; - final Color barrierColor; - - @override - Animation createAnimation() { - return CurvedAnimation( - parent: super.createAnimation(), - curve: Curves.linear, - reverseCurve: const Interval(0.0, _kMenuCloseIntervalEnd), - ); - } - - @override - Duration get transitionDuration => _kMenuDuration; - - @override - bool get barrierDismissible => true; - - @override - final String barrierLabel; - - @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - int selectedItemIndex; - if (initialValue != null) { - for (int index = 0; selectedItemIndex == null && index < items.length; index += 1) { - if (items[index].represents(initialValue)) selectedItemIndex = index; - } - } - - Widget menu = _PopupMenu(route: this, semanticLabel: semanticLabel); - if (captureInheritedThemes) { - menu = InheritedTheme.captureAll(showMenuContext, menu); - } else { - // For the sake of backwards compatibility. An (unlikely) app that relied - // on having menus only inherit from the material Theme could set - // captureInheritedThemes to false and get the original behavior. - if (theme != null) menu = Theme(data: theme, child: menu); - } - - return MediaQuery.removePadding( - context: context, - removeTop: true, - removeBottom: true, - removeLeft: true, - removeRight: true, - child: Builder( - builder: (BuildContext context) { - return CustomSingleChildLayout( - delegate: _PopupMenuRouteLayout( - position, - itemSizes, - selectedItemIndex, - Directionality.of(context), - ), - child: menu, - ); - }, - ), - ); - } -} - -/// Show a popup menu that contains the `items` at `position`. -/// -/// `items` should be non-null and not empty. -/// -/// If `initialValue` is specified then the first item with a matching value -/// will be highlighted and the value of `position` gives the rectangle whose -/// vertical center will be aligned with the vertical center of the highlighted -/// item (when possible). -/// -/// If `initialValue` is not specified then the top of the menu will be aligned -/// with the top of the `position` rectangle. -/// -/// In both cases, the menu position will be adjusted if necessary to fit on the -/// screen. -/// -/// Horizontally, the menu is positioned so that it grows in the direction that -/// has the most room. For example, if the `position` describes a rectangle on -/// the left edge of the screen, then the left edge of the menu is aligned with -/// the left edge of the `position`, and the menu grows to the right. If both -/// edges of the `position` are equidistant from the opposite edge of the -/// screen, then the ambient [Directionality] is used as a tie-breaker, -/// preferring to grow in the reading direction. -/// -/// The positioning of the `initialValue` at the `position` is implemented by -/// iterating over the `items` to find the first whose -/// [CustomPopupMenuEntry.represents] method returns true for `initialValue`, and then -/// summing the values of [CustomPopupMenuEntry.height] for all the preceding widgets -/// in the list. -/// -/// The `elevation` argument specifies the z-coordinate at which to place the -/// menu. The elevation defaults to 8, the appropriate elevation for popup -/// menus. -/// -/// The `context` argument is used to look up the [Navigator] and [Theme] for -/// the menu. It is only used when the method is called. Its corresponding -/// widget can be safely removed from the tree before the popup menu is closed. -/// -/// The `useRootNavigator` argument is used to determine whether to push the -/// menu to the [Navigator] furthest from or nearest to the given `context`. It -/// is `false` by default. -/// -/// The `semanticLabel` argument is used by accessibility frameworks to -/// announce screen transitions when the menu is opened and closed. If this -/// label is not provided, it will default to -/// [MaterialLocalizations.popupMenuLabel]. -/// -/// See also: -/// -/// * [CustomPopupMenuItem], a popup menu entry for a single value. -/// * [PopupMenuDivider], a popup menu entry that is just a horizontal line. -/// * [CheckedPopupMenuItem], a popup menu item with a checkmark. -/// * [PopupMenuButton], which provides an [IconButton] that shows a menu by -/// calling this method automatically. -/// * [SemanticsConfiguration.namesRoute], for a description of edge triggered -/// semantics. -Future customShowMenu({ - @required BuildContext context, - @required RelativeRect position, - @required List> items, - T initialValue, - double elevation, - String semanticLabel, - Color barrierColor, - ShapeBorder shape, - Color color, - bool captureInheritedThemes = true, - bool useRootNavigator = false, -}) { - assert(context != null); - assert(position != null); - assert(useRootNavigator != null); - assert(items != null && items.isNotEmpty); - assert(captureInheritedThemes != null); - assert(debugCheckHasMaterialLocalizations(context)); - - String label = semanticLabel; - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.macOS: - label = semanticLabel; - break; - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - label = semanticLabel ?? MaterialLocalizations.of(context)?.popupMenuLabel; - } - - return Navigator.of(context, rootNavigator: useRootNavigator).push( - _PopupMenuRoute( - position: position, - items: items, - initialValue: initialValue, - elevation: elevation, - semanticLabel: label, - theme: Theme.of(context), - popupMenuTheme: PopupMenuTheme.of(context), - barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, - barrierColor: barrierColor, - shape: shape, - color: color, - showMenuContext: context, - captureInheritedThemes: captureInheritedThemes, - ), - ); -} diff --git a/lib/library/radar_chart.dart b/lib/library/radar_chart.dart index c4ae56a..780812c 100644 --- a/lib/library/radar_chart.dart +++ b/lib/library/radar_chart.dart @@ -26,10 +26,10 @@ class RadarChart extends StatefulWidget { final int sides; const RadarChart({ - Key key, - @required this.ticks, - @required this.features, - @required this.data, + Key? key, + required this.ticks, + required this.features, + required this.data, this.reverseAxis = false, this.ticksTextStyle = const TextStyle(color: Colors.grey, fontSize: 12), this.featuresTextStyle = const TextStyle(color: Colors.black, fontSize: 16), @@ -40,53 +40,46 @@ class RadarChart extends StatefulWidget { }) : super(key: key); factory RadarChart.light({ - @required List ticks, - @required List features, - @required List> data, + required List ticks, + required List features, + required List> data, bool reverseAxis = false, bool useSides = false, }) { - return RadarChart( - ticks: ticks, - features: features, - data: data, - reverseAxis: reverseAxis, - sides: useSides ? features.length : 0); + return RadarChart(ticks: ticks, features: features, data: data, reverseAxis: reverseAxis, sides: useSides ? features.length : 0); } factory RadarChart.dark({ - @required List ticks, - @required List features, - @required List> data, + required List ticks, + required List features, + required List> data, bool reverseAxis = false, bool useSides = false, }) { return RadarChart( - ticks: ticks, - features: features, - data: data, - featuresTextStyle: const TextStyle(color: Colors.white, fontSize: 16), - outlineColor: Colors.white, - axisColor: Colors.grey, - reverseAxis: reverseAxis, - sides: useSides ? features.length : 0); + ticks: ticks, + features: features, + data: data, + featuresTextStyle: const TextStyle(color: Colors.white, fontSize: 16), + outlineColor: Colors.white, + axisColor: Colors.grey, + reverseAxis: reverseAxis, + sides: useSides ? features.length : 0); } @override _RadarChartState createState() => _RadarChartState(); } -class _RadarChartState extends State - with SingleTickerProviderStateMixin { +class _RadarChartState extends State with SingleTickerProviderStateMixin { double fraction = 0; - Animation animation; - AnimationController animationController; + late Animation animation; + late AnimationController animationController; @override void initState() { super.initState(); - animationController = AnimationController( - duration: Duration(milliseconds: 1000), vsync: this); + animationController = AnimationController(duration: Duration(milliseconds: 1000), vsync: this); animation = Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation( curve: Curves.fastOutSlowIn, @@ -113,18 +106,8 @@ class _RadarChartState extends State Widget build(BuildContext context) { return CustomPaint( size: Size(double.infinity, double.infinity), - painter: RadarChartPainter( - widget.ticks, - widget.features, - widget.data, - widget.reverseAxis, - widget.ticksTextStyle, - widget.featuresTextStyle, - widget.outlineColor, - widget.axisColor, - widget.graphColors, - widget.sides, - this.fraction), + painter: RadarChartPainter(widget.ticks, widget.features, widget.data, widget.reverseAxis, widget.ticksTextStyle, + widget.featuresTextStyle, widget.outlineColor, widget.axisColor, widget.graphColors, widget.sides, this.fraction), ); } @@ -160,7 +143,7 @@ class RadarChartPainter extends CustomPainter { this.graphColors, this.sides, this.fraction, - ); + ); Path variablePath(Size size, double radius, int sides) { var path = Path(); @@ -223,14 +206,10 @@ class RadarChartPainter extends CustomPainter { textDirection: TextDirection.ltr, ) ..layout(minWidth: 0, maxWidth: size.width) - ..paint(canvas, Offset(centerX, centerY - ticksTextStyle.fontSize)); + ..paint(canvas, Offset(centerX, centerY - ticksTextStyle.fontSize!)); } - tickLabels - .sublist( - reverseAxis ? 1 : 0, reverseAxis ? ticks.length : ticks.length - 1) - .asMap() - .forEach((index, tick) { + tickLabels.sublist(reverseAxis ? 1 : 0, reverseAxis ? ticks.length : ticks.length - 1).asMap().forEach((index, tick) { var tickRadius = tickDistance * (index + 1); canvas.drawPath(variablePath(size, tickRadius, this.sides), ticksPaint); @@ -240,8 +219,7 @@ class RadarChartPainter extends CustomPainter { textDirection: TextDirection.ltr, ) ..layout(minWidth: 0, maxWidth: size.width) - ..paint(canvas, - Offset(centerX, centerY - tickRadius - ticksTextStyle.fontSize)); + ..paint(canvas, Offset(centerX, centerY - tickRadius - ticksTextStyle.fontSize!)); }); // Painting the axis for each given feature @@ -251,16 +229,14 @@ class RadarChartPainter extends CustomPainter { var xAngle = cos(angle * index - pi / 2); var yAngle = sin(angle * index - pi / 2); - var featureOffset = - Offset(centerX + radius * xAngle, centerY + radius * yAngle); + var featureOffset = Offset(centerX + radius * xAngle, centerY + radius * yAngle); canvas.drawLine(centerOffset, featureOffset, ticksPaint); var featureLabelFontHeight = featuresTextStyle.fontSize; - var featureLabelFontWidth = featuresTextStyle.fontSize - 5; - var labelYOffset = yAngle < 0 ? -featureLabelFontHeight : 0; - var labelXOffset = - xAngle < 0 ? -featureLabelFontWidth * feature.length : 0; + var featureLabelFontWidth = featuresTextStyle.fontSize! - 5; + var labelYOffset = yAngle < 0 ? -featureLabelFontHeight! : 0; + var labelXOffset = xAngle < 0 ? -featureLabelFontWidth * feature.length : 0; TextPainter( text: TextSpan(text: feature, style: featuresTextStyle), @@ -268,10 +244,7 @@ class RadarChartPainter extends CustomPainter { textDirection: TextDirection.ltr, ) ..layout(minWidth: 0, maxWidth: size.width) - ..paint( - canvas, - Offset(featureOffset.dx + labelXOffset, - featureOffset.dy + labelYOffset)); + ..paint(canvas, Offset(featureOffset.dx + labelXOffset, featureOffset.dy + labelYOffset)); }); // Painting each graph @@ -304,11 +277,9 @@ class RadarChartPainter extends CustomPainter { var scaledPoint = scale * point * fraction; if (reverseAxis) { - path.lineTo(centerX + (radius * fraction - scaledPoint) * xAngle, - centerY + (radius * fraction - scaledPoint) * yAngle); + path.lineTo(centerX + (radius * fraction - scaledPoint) * xAngle, centerY + (radius * fraction - scaledPoint) * yAngle); } else { - path.lineTo( - centerX + scaledPoint * xAngle, centerY + scaledPoint * yAngle); + path.lineTo(centerX + scaledPoint * xAngle, centerY + scaledPoint * yAngle); } }); diff --git a/lib/library/select_dialog.dart b/lib/library/select_dialog.dart deleted file mode 100644 index 0f33172..0000000 --- a/lib/library/select_dialog.dart +++ /dev/null @@ -1,407 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; - -import 'dropdown_search.dart'; - -class SelectDialog extends StatefulWidget { - final T selectedValue; - final List items; - final bool showSearchBox; - final bool isFilteredOnline; - final ValueChanged onChanged; - final DropdownSearchOnFind onFind; - final DropdownSearchPopupItemBuilder itemBuilder; - final InputDecoration searchBoxDecoration; - final DropdownSearchItemAsString itemAsString; - final DropdownSearchFilterFn filterFn; - final String hintText; - final double maxHeight; - final double dialogMaxWidth; - final Widget popupTitle; - final bool showSelectedItem; - final DropdownSearchCompareFn compareFn; - final DropdownSearchPopupItemEnabled itemDisabled; - - ///custom layout for empty results - final EmptyBuilder emptyBuilder; - - ///custom layout for loading items - final LoadingBuilder loadingBuilder; - - ///custom layout for error - final ErrorBuilder errorBuilder; - - ///the search box will be focused if true - final bool autoFocusSearchBox; - - ///text controller to set default search word for example - final TextEditingController searchBoxController; - - ///delay before searching - final Duration searchDelay; - - const SelectDialog({ - Key key, - this.popupTitle, - this.items, - this.maxHeight, - this.showSearchBox = false, - this.isFilteredOnline = false, - this.onChanged, - this.selectedValue, - this.onFind, - this.itemBuilder, - this.searchBoxDecoration, - this.hintText, - this.itemAsString, - this.filterFn, - this.showSelectedItem = false, - this.compareFn, - this.emptyBuilder, - this.loadingBuilder, - this.errorBuilder, - this.autoFocusSearchBox = false, - this.dialogMaxWidth, - this.itemDisabled, - this.searchBoxController, - this.searchDelay, - }) : super(key: key); - - @override - _SelectDialogState createState() => _SelectDialogState(); -} - -class _SelectDialogState extends State> { - final FocusNode focusNode = new FocusNode(); - final StreamController> _itemsStream = StreamController(); - final ValueNotifier _loadingNotifier = ValueNotifier(false); - final List _items = List(); - Debouncer _debouncer; - - @override - void initState() { - super.initState(); - _debouncer = Debouncer(delay: widget.searchDelay); - - Future.delayed( - Duration.zero, - () => manageItemsByFilter(widget.searchBoxController?.text ?? '', isFistLoad: true), - ); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (widget.autoFocusSearchBox) FocusScope.of(context).requestFocus(focusNode); - } - - @override - void dispose() { - _itemsStream.close(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - Size deviceSize = MediaQuery.of(context).size; - bool isTablet = deviceSize.width > deviceSize.height; - double maxHeight = deviceSize.height * (isTablet ? .8 : .6); - double maxWidth = deviceSize.width * (isTablet ? .7 : .9); - - return Container( - width: widget.dialogMaxWidth ?? maxWidth, - constraints: BoxConstraints(maxHeight: widget.maxHeight ?? maxHeight), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - _searchField(), - Expanded( - child: Stack( - children: [ - StreamBuilder>( - stream: _itemsStream.stream, - builder: (context, snapshot) { - if (snapshot.hasError) { - return _errorWidget(snapshot?.error); - } else if (!snapshot.hasData) { - return _loadingWidget(); - } else if (snapshot.data.isEmpty) { - if (widget.emptyBuilder != null) - return widget.emptyBuilder(context, widget.searchBoxController?.text); - else - return const Center( - child: const Text("No data found"), - ); - } - return ListView.builder( - shrinkWrap: true, - padding: EdgeInsets.symmetric(vertical: 0), - itemCount: snapshot.data.length, - itemBuilder: (context, index) { - var item = snapshot.data[index]; - return _itemWidget(item); - }, - ); - }, - ), - _loadingWidget() - ], - ), - ), - ], - ), - ); - } - - void _showErrorDialog(dynamic error) { - showDialog( - context: context, - barrierDismissible: false, - builder: (BuildContext context) { - return AlertDialog( - title: Text("Error while getting online items"), - content: _errorWidget(error), - actions: [ - FlatButton( - child: new Text("OK"), - onPressed: () { - Navigator.of(context).pop(false); - }, - ) - ], - ); - }, - ); - } - - Widget _errorWidget(dynamic error) { - if (widget.errorBuilder != null) - return widget.errorBuilder(context, widget.searchBoxController?.text, error); - else - return Padding( - padding: EdgeInsets.all(8), - child: Text( - error?.toString() ?? 'Error', - ), - ); - } - - Widget _loadingWidget() { - return ValueListenableBuilder( - valueListenable: _loadingNotifier, - builder: (context, bool isLoading, wid) { - if (isLoading) { - if (widget.loadingBuilder != null) - return widget.loadingBuilder(context, widget.searchBoxController?.text); - else - return Padding( - padding: const EdgeInsets.all(24.0), - child: const Center( - child: const CircularProgressIndicator(), - ), - ); - } - return Container(); - }); - } - - void _onTextChanged(String filter) async { - manageItemsByFilter(filter); - } - - ///Function that filter item (online and offline) base on user filter - ///[filter] is the filter keyword - ///[isFirstLoad] true if it's the first time we load data from online, false other wises - void manageItemsByFilter(String filter, {bool isFistLoad = false}) async { - _loadingNotifier.value = true; - - String encoded(String item) { - String encodedItem = ""; - for (int i = 0; i < item.length; i++) { - var char = item[i]; - switch (char) { - case 'Á': - case 'á': - case 'ą': - case 'ä': - char = 'a'; - break; - case 'é': - case 'É': - char = 'e'; - break; - case 'ú': - case 'ű': - case 'ü': - case 'Ú': - case 'Ű': - case 'Ü': - char = 'u'; - break; - case 'ö': - case 'ő': - case 'ó': - case 'Ö': - case 'Ő': - case 'Ó': - char = 'o'; - break; - case 'í': - case 'Í': - char = 'i'; - break; - } - encodedItem += char; - } - return encodedItem; - } - - List applyFilter(String filter) { - return _items.where((i) { - if (widget.filterFn != null) { - return (widget.filterFn(i, filter)); - } else if (i.toString().toLowerCase().contains(filter.toLowerCase()) || - encoded(i.toString()).toLowerCase().contains(encoded(filter.toLowerCase()))) { - return true; - } else if (widget.itemAsString != null) { - bool found = (widget.itemAsString(i))?.toLowerCase()?.contains(filter.toLowerCase()) ?? false; - if (!found) { - found = (encoded(widget.itemAsString(i)))?.toLowerCase()?.contains(encoded(filter.toLowerCase())) ?? false; - } - - return found; - } - return false; - }).toList(); - } - - //load offline data for the first time - if (isFistLoad && widget.items != null) _items.addAll(widget.items); - - //manage offline items - if (widget.onFind != null && (widget.isFilteredOnline || isFistLoad)) { - try { - final List onlineItems = List(); - onlineItems.addAll(await widget.onFind(filter) ?? List()); - - //Remove all old data - _items.clear(); - //add offline items - if (widget.items != null) { - _items.addAll(widget.items); - //if filter online we filter only local list based on entred keyword (filter) - if (widget.isFilteredOnline == true) { - var filteredLocalList = applyFilter(filter); - _items.clear(); - _items.addAll(filteredLocalList); - } - } - //add new online items to list - _items.addAll(onlineItems); - - _addDataToStream(applyFilter(filter)); - } catch (e) { - _addErrorToStream(e); - //if offline items count > 0 , the error will be not visible for the user - //As solution we show it in dialog - if (widget.items != null && widget.items.isNotEmpty) { - _showErrorDialog(e); - _addDataToStream(applyFilter(filter)); - } - } - } else { - _addDataToStream(applyFilter(filter)); - } - - _loadingNotifier.value = false; - } - - void _addDataToStream(List data) { - if (_itemsStream.isClosed) return; - _itemsStream.add(data); - } - - void _addErrorToStream(Object error, [StackTrace stackTrace]) { - if (_itemsStream.isClosed) return; - _itemsStream.addError(error, stackTrace); - } - - Widget _itemWidget(T item) { - if (widget.itemBuilder != null) - return InkWell( - child: widget.itemBuilder( - context, - item, - _manageSelectedItemVisibility(item), - ), - onTap: widget.itemDisabled != null && (widget.itemDisabled(item) ?? false) == true - ? null - : () { - Navigator.pop(context, item); - if (widget.onChanged != null) widget.onChanged(item); - }, - ); - else - return ListTile( - title: Text( - widget.itemAsString != null ? (widget.itemAsString(item) ?? "") : item.toString(), - ), - selected: _manageSelectedItemVisibility(item), - onTap: widget.itemDisabled != null && (widget.itemDisabled(item) ?? false) == true - ? null - : () { - Navigator.pop(context, item); - if (widget.onChanged != null) widget.onChanged(item); - }, - ); - } - - /// selected item will be highlighted only when [widget.showSelectedItem] is true, - /// if our object is String [widget.compareFn] is not required , other wises it's required - bool _manageSelectedItemVisibility(T item) { - if (!widget.showSelectedItem) return false; - - if (T == String) { - return item == widget.selectedValue; - } else { - return widget.compareFn(item, widget.selectedValue); - } - } - - Widget _searchField() { - return Column(crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ - widget.popupTitle ?? const SizedBox.shrink(), - if (widget.showSearchBox) - Padding( - padding: const EdgeInsets.all(8.0), - child: TextField( - controller: widget.searchBoxController, - focusNode: focusNode, - onChanged: (f) => _debouncer(() { - _onTextChanged(f); - }), - decoration: widget.searchBoxDecoration ?? - InputDecoration( - hintText: widget.hintText, - border: const OutlineInputBorder(), - contentPadding: const EdgeInsets.symmetric(horizontal: 16), - ), - ), - ) - ]); - } -} - -class Debouncer { - final Duration delay; - Timer _timer; - - Debouncer({this.delay}); - - call(Function action) { - _timer?.cancel(); - _timer = Timer(delay ?? const Duration(milliseconds: 500), action); - } -} diff --git a/lib/library/transparent_image.dart b/lib/library/transparent_image.dart new file mode 100644 index 0000000..38f0e4a --- /dev/null +++ b/lib/library/transparent_image.dart @@ -0,0 +1,70 @@ +library transparent_image; + +import 'dart:typed_data'; + +final Uint8List kTransparentImage = new Uint8List.fromList([ + 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/lib/library/tree_view.dart b/lib/library/tree_view.dart index ecac80d..057c9fc 100644 --- a/lib/library/tree_view.dart +++ b/lib/library/tree_view.dart @@ -30,8 +30,8 @@ class TreeView extends InheritedWidget { final bool startExpanded; TreeView({ - Key key, - @required List children, + Key? key, + required List children, bool startExpanded = false, }) : this.children = children, this.startExpanded = startExpanded, @@ -42,7 +42,7 @@ class TreeView extends InheritedWidget { ), ); - static TreeView of(BuildContext context) { + static TreeView? of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType(aspect: TreeView); } @@ -59,7 +59,7 @@ class _TreeViewData extends StatefulWidget { final List children; _TreeViewData({ - this.children, + required this.children, }); @override @@ -69,14 +69,14 @@ class _TreeViewData extends StatefulWidget { class __TreeViewDataState extends State<_TreeViewData> { final ScrollController _controller = ScrollController(); final Stream stream = TreeViewStream().stream; - var subscription; + late var subscription; @override void initState() { super.initState(); /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { final double cHeight = MediaQuery.of(context).size.height; subscription = stream.listen((value) { if (value) { @@ -120,43 +120,41 @@ class __TreeViewDataState extends State<_TreeViewData> { } class TreeViewChild extends StatefulWidget { - final bool startExpanded; + final bool? startExpanded; final Widget parent; final List children; - final VoidCallback onTap; + final VoidCallback? onTap; TreeViewChild({ - @required this.parent, - @required this.children, + required this.parent, + required this.children, this.startExpanded, this.onTap, - Key key, - }) : super(key: key) { - assert(parent != null); - assert(children != null); - } + Key? key, + }) : super(key: key); @override TreeViewChildState createState() => TreeViewChildState(); TreeViewChild copyWith( TreeViewChild source, { - bool startExpanded, - Widget parent, - List children, - VoidCallback onTap, + bool? startExpanded, + Widget? parent, + List? children, + VoidCallback? onTap, }) { return TreeViewChild( parent: parent ?? source.parent, children: children ?? source.children, startExpanded: startExpanded ?? source.startExpanded, onTap: onTap ?? source.onTap, + key: key, ); } } class TreeViewChildState extends State with Common { - bool isExpanded; + late bool? isExpanded; final GlobalKey listKey = GlobalKey(); @override @@ -167,7 +165,7 @@ class TreeViewChildState extends State with Common { @override void didChangeDependencies() { - isExpanded = widget.startExpanded ?? TreeView.of(context).startExpanded; + isExpanded = widget.startExpanded ?? TreeView.of(context)!.startExpanded; super.didChangeDependencies(); } @@ -177,17 +175,14 @@ class TreeViewChildState extends State with Common { key: listKey, mainAxisSize: MainAxisSize.min, children: [ - GestureDetector( - child: widget.parent, - onTap: widget.onTap ?? () => toggleExpanded(), - ), + GestureDetector(child: widget.parent, onTap: widget.onTap ?? () => toggleExpanded()), Flexible( child: Container( child: AnimatedSwitcher( duration: Duration(milliseconds: 200), reverseDuration: Duration(milliseconds: 200), switchInCurve: Curves.easeIn, - child: isExpanded + child: isExpanded! ? Column( mainAxisSize: MainAxisSize.min, children: widget.children, @@ -202,14 +197,14 @@ class TreeViewChildState extends State with Common { void toggleExpanded() { setState(() { - this.isExpanded = !this.isExpanded; + this.isExpanded = !this.isExpanded!; TreeViewStream().positionY = getPosition(); TreeViewStream().getStreamController().add(this.isExpanded); }); } double getPosition() { - RenderBox box = listKey.currentContext.findRenderObject(); + RenderBox? box = listKey.currentContext!.findRenderObject() as RenderBox; Offset position = box.localToGlobal(Offset.zero); //this is global position double y = position.dy; return y; diff --git a/lib/main.dart b/lib/main.dart index b2e2cf9..46a13b1 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,7 +6,6 @@ import 'package:aitrainer_app/repository/workout_tree_repository.dart'; import 'package:aitrainer_app/service/firebase_api.dart'; import 'package:aitrainer_app/util/session.dart'; import 'package:aitrainer_app/view/account.dart'; -import 'package:aitrainer_app/view/custom_exercise_page.dart'; import 'package:aitrainer_app/view/customer_bodytype_animation.dart'; import 'package:aitrainer_app/view/customer_exercise_device.dart'; import 'package:aitrainer_app/view/customer_fitness_page.dart'; @@ -38,7 +37,7 @@ import 'package:aitrainer_app/view/test_set_new.dart'; import 'package:aitrainer_app/widgets/home.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_analytics/observer.dart'; -import 'package:flurry/flurry.dart'; +import 'package:aitrainer_app/library/flurry.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -103,7 +102,7 @@ Future main() async { } else { // In production mode report to the application zone to report to // Sentry. - Zone.current.handleUncaughtError(details.exception, details.stack); + Zone.current.handleUncaughtError(details.exception, details.stack!); } }; @@ -134,7 +133,7 @@ Future main() async { create: (BuildContext context) => MenuBloc(menuTreeRepository: menuTreeRepository), ), BlocProvider( - create: (BuildContext context) => SettingsBloc(), + create: (BuildContext context) => SettingsBloc(context: context), ), BlocProvider( create: (BuildContext context) => AccountBloc(customerRepository: CustomerRepository()), @@ -199,13 +198,13 @@ class WorkoutTestApp extends StatelessWidget { const Locale('hu', "HU"), // Hungarian // ... other locales the app supports ], - localeResolutionCallback: (Locale locale, Iterable supportedLocales) { + localeResolutionCallback: (Locale? locale, Iterable supportedLocales) { //myLocale = deviceLocale ; // here you make your app language similar to device language , // but you should check whether the localization is supported by your app Locale realSupportedLocale = Locale('en', "US"); supportedLocales.forEach((supportedLocale) { - if (locale != null && supportedLocale != null && supportedLocale.countryCode == locale.countryCode) { + if (locale != null && supportedLocale.countryCode == locale.countryCode) { realSupportedLocale = supportedLocale; } }); @@ -223,7 +222,6 @@ class WorkoutTestApp extends StatelessWidget { 'customerWelcomePage': (context) => CustomerWelcomePage(), 'customerExerciseDevicePage': (context) => CustomerExerciseDevicePage(), 'exerciseNewPage': (context) => ExerciseNewPage(), - 'exerciseCustomPage': (context) => CustomExercisePage(), 'exerciseControlPage': (context) => ExerciseControlPage(), 'login': (context) => LoginPage(), 'resetPassword': (context) => ResetPasswordPage(), diff --git a/lib/model/cache.dart b/lib/model/cache.dart index 602daa8..a9a90fa 100644 --- a/lib/model/cache.dart +++ b/lib/model/cache.dart @@ -8,6 +8,7 @@ import 'package:aitrainer_app/model/exercise_tree.dart'; import 'package:aitrainer_app/model/exercise.dart'; import 'package:aitrainer_app/model/model_change.dart'; import 'package:aitrainer_app/model/product.dart' as wt_product; +import 'package:aitrainer_app/model/product.dart'; import 'package:aitrainer_app/model/product_test.dart'; import 'package:aitrainer_app/model/property.dart'; import 'package:aitrainer_app/model/purchase.dart'; @@ -20,7 +21,7 @@ import 'package:aitrainer_app/main.dart'; import 'package:aitrainer_app/util/enums.dart'; import 'package:aitrainer_app/util/env.dart'; import 'package:aitrainer_app/util/track.dart'; -import 'package:flurry/flurry.dart'; +import 'package:aitrainer_app/library/flurry.dart'; import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'; import 'package:package_info/package_info.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -57,22 +58,22 @@ class Cache with Logging { static final Cache _singleton = Cache._internal(); // Keys to store and fetch data from SharedPreferences - static final String authTokenKey = 'auth_token'; - static final String customerIdKey = 'customer_id'; - static final String firebaseUidKey = 'firebase_uid'; - static final String lastStoreDateKey = 'last_date'; - static final String isRegisteredKey = 'is_registered'; - static final String isLoggedInKey = 'is_logged_in'; - static final String langKey = 'lang'; - static final String serverKey = 'live'; - static final String hardwareKey = 'hardware'; - static final String loginTypeKey = 'login_type'; - static final String timerDisplayKey = 'timer_display'; - static final String activeExercisePlanKey = 'active_exercise_plan'; - static final String activeExercisePlanDateKey = 'active_exercise_plan_date'; - static final String activeExercisePlanDetailsKey = 'active_exercise_details_plan'; - static final String exerciseLogSeenKey = 'exercise_log_seen'; - static final String muscleDevelopmentSeenKey = 'muscle_development_seen_key'; + static final String authTokenKey = "auth_token"; + static final String customerIdKey = "customer_id"; + static final String firebaseUidKey = "firebase_uid"; + static final String lastStoreDateKey = "last_date"; + static final String isRegisteredKey = "is_registered"; + static final String isLoggedInKey = "is_logged_in"; + static final String langKey = "lang"; + static final String serverKey = "live"; + static final String hardwareKey = "hardware"; + static final String loginTypeKey = "login_type"; + static final String timerDisplayKey = "timer_display"; + static final String activeExercisePlanKey = "active_exercise_plan"; + static final String activeExercisePlanDateKey = "active_exercise_plan_date"; + static final String activeExercisePlanDetailsKey = "active_exercise_details_plan"; + static final String exerciseLogSeenKey = "exercise_log_seen"; + static final String muscleDevelopmentSeenKey = "muscle_development_seen_key"; static String baseUrl = 'http://aitrainer.info:8888/api/'; static final String mediaUrl = 'https://aitrainer.info:4343/media/'; @@ -80,51 +81,51 @@ class Cache with Logging { static final String password = 'andio2009'; String authToken = ""; - AccessToken accessTokenFacebook; - Customer userLoggedIn; - String firebaseUid; - LoginType loginType; - PackageInfo packageInfo; + AccessToken? accessTokenFacebook; + Customer? userLoggedIn; + String? firebaseUid; + late LoginType loginType; + late PackageInfo packageInfo; bool hasPurchased = false; bool firstLoad = true; - List _exerciseTypes; - List _exerciseTree; + List? _exerciseTypes; + List? _exerciseTree; - List _exercises; - ExercisePlan _myExercisePlan; - List _properties; - List _products; - List _purchases = List(); - List _productTests; - List _exercisePlanTemplates = List(); + List? _exercises; + ExercisePlan? _myExercisePlan; + List? _properties; + List? _products; + List _purchases = []; + List? _productTests; + List _exercisePlanTemplates = []; - ExercisePlan activeExercisePlan; - List activeExercisePlanDetails; + ExercisePlan? activeExercisePlan; + List? activeExercisePlanDetails; - List _devices; - List _customerDevices; + List? _devices; + List? _customerDevices; LinkedHashMap _myExercisesPlanDetails = LinkedHashMap(); - LinkedHashMap _tree = LinkedHashMap(); + LinkedHashMap _tree = LinkedHashMap(); double _percentExercises = -1; - Customer _trainee; - List _exercisesTrainee; - ExercisePlan _traineeExercisePlan; + Customer? _trainee; + List? _exercisesTrainee; + ExercisePlan? _traineeExercisePlan; LinkedHashMap _badges = LinkedHashMap(); - List deviceLanguages; + List? deviceLanguages; String startPage = "home"; - String testEnvironment; + late String testEnvironment; bool liveServer = true; - bool hasHardware = false; - bool isExerciseLogSeen = false; - bool isMuscleDevelopmentSeen = false; + bool? hasHardware = false; + bool? isExerciseLogSeen = false; + bool? isMuscleDevelopmentSeen = false; factory Cache() { return _singleton; @@ -186,11 +187,8 @@ class Cache with Logging { DateFormat format = DateFormat("yyyy-MM-dd HH:mm:ss"); DateTime savedPlanDate; - try { - savedPlanDate = format.parse(savedPlanDateString); - } on Exception catch (e) { - return; - } + + savedPlanDate = format.parse(savedPlanDateString); final DateTime now = DateTime.now(); final DateTime added = savedPlanDate.add(Duration(days: 1)); @@ -198,13 +196,13 @@ class Cache with Logging { return; } - String exercisePlanJson = sharedPreferences.getString(Cache.activeExercisePlanKey); + String? exercisePlanJson = sharedPreferences.getString(Cache.activeExercisePlanKey); if (exercisePlanJson != null) { final Map map = JsonDecoder().convert(exercisePlanJson); this.activeExercisePlan = ExercisePlan.fromJson(map); } - String detailsJson = sharedPreferences.getString(Cache.activeExercisePlanDetailsKey); + String? detailsJson = sharedPreferences.getString(Cache.activeExercisePlanDetailsKey); if (detailsJson != null) { print("Details $detailsJson"); Iterable json = jsonDecode(detailsJson); @@ -225,7 +223,7 @@ class Cache with Logging { } void getHardware(SharedPreferences prefs) { - final bool hasHardware = prefs.getBool(Cache.hardwareKey); + final bool? hasHardware = prefs.getBool(Cache.hardwareKey); this.hasHardware = hasHardware; if (hasHardware == null) { this.hasHardware = false; @@ -236,7 +234,7 @@ class Cache with Logging { Future prefs = SharedPreferences.getInstance(); SharedPreferences sharedPreferences = await prefs; - final bool selectedHardware = sharedPreferences.getBool(Cache.hardwareKey); + final bool? selectedHardware = sharedPreferences.getBool(Cache.hardwareKey); return selectedHardware == null; } @@ -254,7 +252,7 @@ class Cache with Logging { print("TestEnv $baseUrl"); return; } - final bool live = prefs.getBool(Cache.serverKey); + final bool? live = prefs.getBool(Cache.serverKey); if (live == null) { baseUrl = 'http://aitrainer.app:8888/api/'; print("Live Env $baseUrl"); @@ -274,7 +272,7 @@ class Cache with Logging { Future setLoginTypeFromPrefs() async { Future prefs = SharedPreferences.getInstance(); SharedPreferences sharedPreferences = await prefs; - final String loginType = sharedPreferences.getString(Cache.loginTypeKey); + final String? loginType = sharedPreferences.getString(Cache.loginTypeKey); LoginType type = LoginType.email; if (loginType == LoginType.apple.toString()) { type = LoginType.apple; @@ -289,7 +287,7 @@ class Cache with Logging { Cache().setLoginType(type); } - static String getToken(SharedPreferences prefs) { + static String? getToken(SharedPreferences prefs) { return prefs.getString(authTokenKey); } @@ -305,10 +303,10 @@ class Cache with Logging { Future prefs = SharedPreferences.getInstance(); userLoggedIn = customer; - final String uid = Cache().firebaseUid; + final String uid = Cache().firebaseUid!; SharedPreferences sharedPreferences = await prefs; sharedPreferences.setString(Cache.loginTypeKey, Cache().getLoginType().toString()); - await setPreferences(prefs, SharePrefsChange.registration, customer.customerId, uid); + await setPreferences(prefs, SharePrefsChange.registration, customer.customerId!, uid); } afterLogin(Customer customer) async { @@ -317,21 +315,21 @@ class Cache with Logging { userLoggedIn = customer; SharedPreferences sharedPreferences = await prefs; sharedPreferences.setString(Cache.loginTypeKey, Cache().getLoginType().toString()); - await setPreferences(prefs, SharePrefsChange.login, customer.customerId, Cache().firebaseUid); + await setPreferences(prefs, SharePrefsChange.login, customer.customerId!, Cache().firebaseUid!); } afterFirebaseLogin() async { Future prefs = SharedPreferences.getInstance(); SharedPreferences sharedPreferences = await prefs; sharedPreferences.setString(Cache.loginTypeKey, Cache().getLoginType().toString()); - await setPreferences(prefs, SharePrefsChange.login, userLoggedIn.customerId, Cache().firebaseUid); + await setPreferences(prefs, SharePrefsChange.login, userLoggedIn!.customerId!, Cache().firebaseUid!); } afterFacebookLogin() async { Future prefs = SharedPreferences.getInstance(); SharedPreferences sharedPreferences = await prefs; sharedPreferences.setString(Cache.loginTypeKey, Cache().getLoginType().toString()); - await setPreferences(prefs, SharePrefsChange.login, userLoggedIn.customerId, Cache().firebaseUid); + await setPreferences(prefs, SharePrefsChange.login, userLoggedIn!.customerId!, Cache().firebaseUid!); } logout() async { @@ -345,7 +343,7 @@ class Cache with Logging { _percentExercises = -1; _exercisesTrainee = null; _traineeExercisePlan = null; - _exercises = List(); + _exercises = []; _myExercisesPlanDetails = LinkedHashMap(); log("Trainees is null? " + (_trainee == null).toString()); Future prefs = SharedPreferences.getInstance(); @@ -372,7 +370,7 @@ class Cache with Logging { } else if (type == SharePrefsChange.logout) { sharedPreferences.setBool(Cache.isLoggedInKey, false); sharedPreferences.setInt(Cache.customerIdKey, 0); - sharedPreferences.setString(Cache.firebaseUidKey, null); + sharedPreferences.setString(Cache.firebaseUidKey, ""); sharedPreferences.setString(authTokenKey, ""); } initBadges(); @@ -396,23 +394,25 @@ class Cache with Logging { this._tree = tree; } - List getExerciseTypes() => this._exerciseTypes; + List? getExerciseTypes() => this._exerciseTypes; - ExerciseType getExerciseTypeById(int exerciseTypeId) { - ExerciseType exerciseType; - this._exerciseTypes.forEach((element) { - if (element.exerciseTypeId == exerciseTypeId) { - exerciseType = element; - } - }); + ExerciseType? getExerciseTypeById(int exerciseTypeId) { + ExerciseType? exerciseType; + if (_exerciseTypes != null) { + this._exerciseTypes!.forEach((element) { + if (element.exerciseTypeId == exerciseTypeId) { + exerciseType = element; + } + }); + } return exerciseType; } - List getExerciseTree() => this._exerciseTree; + List? getExerciseTree() => this._exerciseTree; - List getExercises() => this._exercises; + List? getExercises() => this._exercises; - List getExercisesTrainee() => this._exercisesTrainee; + List? getExercisesTrainee() => this._exercisesTrainee; LinkedHashMap getWorkoutMenuTree() => this._tree; @@ -420,21 +420,21 @@ class Cache with Logging { double getPercentExercises() => this._percentExercises; - void addExercise(Exercise exercise) => _exercises.add(exercise); + void addExercise(Exercise exercise) => _exercises!.add(exercise); - void addExerciseTrainee(Exercise exercise) => _exercisesTrainee.add(exercise); + void addExerciseTrainee(Exercise exercise) => _exercisesTrainee!.add(exercise); - Customer getTrainee() => this._trainee; + Customer? getTrainee() => this._trainee; void setTrainee(Customer trainee) => _trainee = trainee; void setTraineeExercisePlan(ExercisePlan exercisePlan) => this._traineeExercisePlan = exercisePlan; - ExercisePlan getTraineesExercisePlan() => this._traineeExercisePlan; + ExercisePlan? getTraineesExercisePlan() => this._traineeExercisePlan; void setMyExercisePlan(ExercisePlan exercisePlan) => _myExercisePlan = exercisePlan; - ExercisePlan getMyExercisePlan() => _myExercisePlan; + ExercisePlan? getMyExercisePlan() => _myExercisePlan; void setMyExercisePlanDetails(LinkedHashMap listExercisePlanDetail) => _myExercisesPlanDetails = listExercisePlanDetail; @@ -452,30 +452,30 @@ class Cache with Logging { void deleteMyExercisePlanDetail(ExercisePlanDetail detail) => this.deleteMyExercisePlanDetailByExerciseTypeId(detail.exerciseTypeId); void deletedMyExercisePlanDetail(ExercisePlanDetail detail) => - this._myExercisesPlanDetails[detail.exerciseTypeId].change = ModelChange.deleted; + this._myExercisesPlanDetails[detail.exerciseTypeId]!.change = ModelChange.deleted; void deleteMyExercisePlanDetailByExerciseTypeId(int exerciseTypeId) { - this._myExercisesPlanDetails[exerciseTypeId].change = ModelChange.delete; + this._myExercisesPlanDetails[exerciseTypeId]!.change = ModelChange.delete; } void setProperties(List properties) => this._properties = properties; - List getProperties() => _properties; + List? getProperties() => _properties; void setDevices(List devices) => this._devices = devices; - List getDevices() => this._devices; + List? getDevices() => this._devices; void setCustomerDevices(List devices) => this._customerDevices = devices; - List getCustomerDevices() => this._customerDevices; + List? getCustomerDevices() => this._customerDevices; LinkedHashMap getBadges() => _badges; void setBadge(String key, bool inc) { if (inc) { if (_badges[key] != null) { - _badges[key]++; + _badges[key] = _badges[key]! + 1; } else { _badges[key] = 1; } @@ -484,7 +484,7 @@ class Cache with Logging { if (_badges[key] == 1) { _badges.remove(key); } else { - _badges[key]--; + _badges[key] = _badges[key]! - 1; } } } @@ -492,31 +492,34 @@ class Cache with Logging { void setBadgeNr(String key, int counter) { if (_badges[key] != null) { - _badges[key] += counter; + _badges[key] = _badges[key]! + counter; } else { _badges[key] = counter; } } - void initBadges() async { + void initBadges() { CustomerRepository customerRepository = CustomerRepository(); _badges = LinkedHashMap(); - customerRepository.setCustomer(userLoggedIn); + if (userLoggedIn == null) { + return; + } + customerRepository.setCustomer(userLoggedIn!); int _ecto = customerRepository.getCustomerPropertyValue(PropertyEnum.Ectomorph.toStr()).toInt(); int _mezo = customerRepository.getCustomerPropertyValue(PropertyEnum.Mesomorph.toStr()).toInt(); int _endo = customerRepository.getCustomerPropertyValue(PropertyEnum.Endomorph.toStr()).toInt(); //print("endo " + _endo.toString() + " mezo " + _mezo.toString()); if (this.userLoggedIn != null) { - if (this.userLoggedIn.birthYear == null || this.userLoggedIn.birthYear == 0) { + if (this.userLoggedIn!.birthYear == null || this.userLoggedIn!.birthYear == 0) { setBadge("personalData", true); setBadge("account", true); } - if (this._customerDevices == null || this._customerDevices.isEmpty) { + if (this._customerDevices == null || this._customerDevices!.isEmpty) { setBadge("customerDevice", true); setBadge("account", true); } - if (userLoggedIn.properties == null || userLoggedIn.properties.isEmpty) { + if (userLoggedIn!.properties.isEmpty) { setBadge("personalData", true); setBadge("bodyType", true); setBadge("Sizes", true); @@ -534,7 +537,7 @@ class Cache with Logging { setBadge("account", true); setBadge("bodyType", true); } - if (this._exercises == null || this._exercises.length == 0) { + if (this._exercises == null || this._exercises!.isEmpty) { setBadge("home", true); setBadge("Muscle Build / Shape Toning", true); setBadge("Cardio", true); @@ -545,20 +548,20 @@ class Cache with Logging { setBadge("My Body", true); setBadgeNr("home", 1); } - if (userLoggedIn.goal == null) { + if (userLoggedIn!.goal == null) { setBadge("Goal", true); setBadge("account", true); } - if (userLoggedIn.fitnessLevel == null) { + if (userLoggedIn!.fitnessLevel == null) { setBadge("FitnessLevel", true); setBadge("account", true); } - if (this._exercises != null && this._exercises.isNotEmpty) { - if (!isExerciseLogSeen) { + if (this._exercises != null && this._exercises!.isNotEmpty) { + if (!isExerciseLogSeen!) { setBadge("exerciseLog", true); setBadge("development", true); } - if (!isMuscleDevelopmentSeen) { + if (!isMuscleDevelopmentSeen!) { setBadge("muscleDevelopment", true); setBadge("development", true); } @@ -567,14 +570,16 @@ class Cache with Logging { log("Badges: " + _badges.toString()); } - List get products => _products; - void setProducts(List value) => _products = value; + List? get products => _products; + void setProducts(List value) => _products = value; - List get purchases => _purchases; - setPurchases(List value) => _purchases = value; + List get purchases => _purchases; + setPurchases(List value) => _purchases = value; - List get productTests => _productTests; - set productTests(List value) => _productTests = value; + // ignore: unnecessary_getters_setters + List? get productTests => _productTests; + // ignore: unnecessary_getters_setters + set productTests(List? value) => _productTests = value; Future initCustomer(int customerId) async { log(" *** initCustomer"); @@ -593,10 +598,10 @@ class Cache with Logging { Cache().startPage = "home"; } - AccessToken get getAccessTokenFacebook => accessTokenFacebook; + AccessToken? get getAccessTokenFacebook => accessTokenFacebook; set setAccessTokenFacebook(AccessToken accessTokenFacebook) => this.accessTokenFacebook = accessTokenFacebook; - LoginType getLoginType() => loginType; + LoginType? getLoginType() => loginType; void setLoginType(LoginType type) => this.loginType = type; List get exercisePlanTemplates => this._exercisePlanTemplates; @@ -617,7 +622,7 @@ class Cache with Logging { isExerciseLogSeen = false; } //print("ExerciseLogSeen $isExerciseLogSeen"); - return isExerciseLogSeen; + return isExerciseLogSeen!; } setMuscleDevelopmentSeen() async { @@ -634,6 +639,6 @@ class Cache with Logging { if (isMuscleDevelopmentSeen == null) { isMuscleDevelopmentSeen = false; } - return isMuscleDevelopmentSeen; + return isMuscleDevelopmentSeen!; } } diff --git a/lib/model/customer.dart b/lib/model/customer.dart index 29bb142..16a0eae 100644 --- a/lib/model/customer.dart +++ b/lib/model/customer.dart @@ -1,27 +1,27 @@ import 'dart:collection'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:intl/intl.dart'; import 'customer_property.dart'; class Customer { - String name; - String email; - String firstname; - String sex; - int age; - String active; - int customerId; - String password; - int birthYear; - String goal; - String fitnessLevel; - String bodyType; - int admin; - int trainer; - int dataPolicyAllowed; - String firebaseUid; - DateTime dateAdd; - DateTime dateChange; + String? name; + late String? email; + String? firstname; + String? sex; + int? age; + String? active; + int? customerId; + String? password; + int? birthYear; + String? goal; + String? fitnessLevel; + String? bodyType; + int? admin; + int? trainer; + int? dataPolicyAllowed; + String? firebaseUid; + DateTime? dateAdd; + DateTime? dateChange; LinkedHashMap properties = LinkedHashMap(); @@ -43,7 +43,10 @@ class Customer { this.dataPolicyAllowed, this.firebaseUid, this.dateAdd, - this.dateChange}); + this.dateChange}) { + dateAdd = DateTime.now(); + dateChange = DateTime.now(); + } Customer.fromJson(Map json) { this.customerId = json['customerId']; @@ -81,19 +84,19 @@ class Customer { "admin": admin, "trainer": trainer, "dataPolicyAllowed": dataPolicyAllowed, - "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd), - "dateChange": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateChange), + "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), + "dateChange": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateChange!), }; double getProperty(String propertyName) { if (this.properties[propertyName] == null) { return 0; } else { - return this.properties[propertyName].propertyValue; + return this.properties[propertyName]!.propertyValue; } } setProperty(String propertyName, double value) { - this.properties[propertyName].propertyValue = value; + this.properties[propertyName]!.propertyValue = value; } } diff --git a/lib/model/customer_exercise_device.dart b/lib/model/customer_exercise_device.dart index e5163e8..0477b47 100644 --- a/lib/model/customer_exercise_device.dart +++ b/lib/model/customer_exercise_device.dart @@ -1,15 +1,15 @@ -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:intl/intl.dart'; class CustomerExerciseDevice { - int customerExerciseDeviceId; - int exerciseDeviceId; - int customerId; - bool favourite; - DateTime dateAdd; + int? customerExerciseDeviceId; + late int exerciseDeviceId; + late int customerId; + late bool favourite; + late DateTime dateAdd; - String change; + late String change; - CustomerExerciseDevice({this.exerciseDeviceId, this.customerId, this.favourite}) { + CustomerExerciseDevice({required this.exerciseDeviceId, required this.customerId, required this.favourite}) { dateAdd = DateTime.now(); } diff --git a/lib/model/customer_property.dart b/lib/model/customer_property.dart index 038b17b..ca246e6 100644 --- a/lib/model/customer_property.dart +++ b/lib/model/customer_property.dart @@ -1,14 +1,14 @@ -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:intl/intl.dart'; class CustomerProperty { - int customerPropertyId; - int propertyId; - int customerId; - DateTime dateAdd; - double propertyValue; + int? customerPropertyId; + late int propertyId; + late int customerId; + late DateTime dateAdd; + late double propertyValue; bool newData = false; - CustomerProperty({this.propertyId, this.customerId, this.dateAdd, this.propertyValue}); + CustomerProperty({required this.propertyId, required this.customerId, required this.dateAdd, required this.propertyValue}); CustomerProperty.fromJson(Map json) { this.customerPropertyId = json['customerPropertyId']; diff --git a/lib/model/exercise.dart b/lib/model/exercise.dart index 8f8b193..0a0301e 100644 --- a/lib/model/exercise.dart +++ b/lib/model/exercise.dart @@ -1,18 +1,18 @@ import 'package:intl/intl.dart'; class Exercise { - int exerciseId; - int exerciseTypeId; - int customerId; - double quantity; - String unit; - double unitQuantity; - DateTime dateAdd; - int exercisePlanDetailId; + int? exerciseId; + int? exerciseTypeId; + int? customerId; + double? quantity; + String? unit; + double? unitQuantity; + DateTime? dateAdd; + int? exercisePlanDetailId; - String datePart; - double calculated; - String summary; + String? datePart; + double? calculated; + String? summary; Exercise({this.exerciseTypeId, this.customerId, this.quantity, this.dateAdd}); @@ -24,7 +24,7 @@ class Exercise { this.unit = json['unit']; this.unitQuantity = json['unitQuantity']; this.dateAdd = DateTime.parse(json['dateAdd']); - this.datePart = DateFormat('yyyy-MM-dd').format(this.dateAdd); + this.datePart = DateFormat('yyyy-MM-dd').format(this.dateAdd!); this.calculated = quantity; } @@ -34,7 +34,7 @@ class Exercise { "quantity": quantity, "unit": unit, "unitQuantity": unitQuantity, - "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd), + "dateAdd": DateFormat('yyyy-MM-dd HH:mm:ss').format(this.dateAdd!), "exercisePlanDetailId": exercisePlanDetailId, }; @@ -49,13 +49,10 @@ class Exercise { }; Exercise copy() { - Exercise newExercise = Exercise(); - newExercise.exerciseTypeId = this.exerciseTypeId; - newExercise.customerId = this.customerId; - newExercise.quantity = this.quantity; + Exercise newExercise = + Exercise(exerciseTypeId: this.exerciseTypeId, customerId: this.customerId, quantity: this.quantity, dateAdd: this.dateAdd); newExercise.unit = this.unit; newExercise.unitQuantity = this.unitQuantity; - newExercise.dateAdd = this.dateAdd; newExercise.exercisePlanDetailId = this.exercisePlanDetailId; return newExercise; } diff --git a/lib/model/exercise_device.dart b/lib/model/exercise_device.dart index f8317a1..68cc5e2 100644 --- a/lib/model/exercise_device.dart +++ b/lib/model/exercise_device.dart @@ -1,13 +1,13 @@ class ExerciseDevice { - int exerciseDeviceId; - String name; - String description; - String imageUrl; - String nameTranslation; - int sort; - bool place; + late int exerciseDeviceId; + late String name; + late String description; + late String imageUrl; + late String nameTranslation; + late int sort; + late bool place; - bool isGym; + bool? isGym; ExerciseDevice.fromJson(Map json) { this.exerciseDeviceId = json['exerciseDeviceId']; diff --git a/lib/model/exercise_plan.dart b/lib/model/exercise_plan.dart index 04b08f1..f74dd23 100644 --- a/lib/model/exercise_plan.dart +++ b/lib/model/exercise_plan.dart @@ -1,15 +1,15 @@ import 'package:intl/intl.dart'; class ExercisePlan { - int exercisePlanId; - int customerId; - String name; - String description; - bool private; - DateTime dateAdd; - DateTime dateUpd; - String type; - int exercisePlanTemplateId; + int? exercisePlanId; + late int customerId; + late String name; + String? description; + late bool private; + late DateTime? dateAdd; + late DateTime dateUpd; + String? type; + int? exercisePlanTemplateId; ExercisePlan(String name, int customerId) { this.customerId = customerId; @@ -23,16 +23,16 @@ class ExercisePlan { this.name = json['name']; this.private = json['private']; this.description = json['description']; - this.dateAdd = json['dateAdd'] == null ? null : DateTime.parse(json['dateAdd']); - this.dateUpd = json['dateUpd'] == null ? null : DateTime.parse(json['dateUpd']); + this.dateAdd = (json['dateAdd'] == null ? null : DateTime.parse(json['dateAdd']))!; + this.dateUpd = (json['dateUpd'] == null ? null : DateTime.parse(json['dateUpd']))!; this.type = json['type']; this.exercisePlanTemplateId = json['exercisePlanTemplateId']; } Map toJson() { - String formattedDateAdd; + String? formattedDateAdd; if (dateAdd != null) { - formattedDateAdd = DateFormat('yyyy-MM-dd HH:mm').format(dateAdd); + formattedDateAdd = DateFormat('yyyy-MM-dd HH:mm').format(dateAdd!); } String formattedDateUpd = DateFormat('yyyy-MM-dd HH:mm').format(dateUpd); diff --git a/lib/model/exercise_plan_detail.dart b/lib/model/exercise_plan_detail.dart index ba8ffbe..e502098 100644 --- a/lib/model/exercise_plan_detail.dart +++ b/lib/model/exercise_plan_detail.dart @@ -11,19 +11,20 @@ extension ExericisePlanDetailStateExt on ExercisePlanDetailState { } class ExercisePlanDetail { - int exercisePlanDetailId; - int exercisePlanId; - int exerciseTypeId; - int serie; - int repeats; - String weightEquation; + int? exercisePlanDetailId; + late int exercisePlanId; + late int exerciseTypeId; + int? serie; + int? repeats; + String? weightEquation; - List exercises; - bool finished; + List? exercises; + bool? finished; ExercisePlanDetailState state = ExercisePlanDetailState.start; - ExerciseType exerciseType; - String change; // 1: update -1:delete 0: new + ExerciseType? exerciseType; + + String? change; // 1: update -1:delete 0: new ExercisePlanDetail(int exerciseTypeId) { this.exerciseTypeId = exerciseTypeId; @@ -75,6 +76,6 @@ class ExercisePlanDetail { "serie": serie, "repeats": repeats, "weightEquation": weightEquation, - 'exercises': exercises.map((exercise) => exercise.toJson()).toList().toString(), + 'exercises': exercises!.map((exercise) => exercise.toJson()).toList().toString(), }; } diff --git a/lib/model/exercise_plan_template.dart b/lib/model/exercise_plan_template.dart index b4ed2fc..96ab286 100644 --- a/lib/model/exercise_plan_template.dart +++ b/lib/model/exercise_plan_template.dart @@ -3,13 +3,13 @@ import 'dart:ui'; import 'package:aitrainer_app/util/app_language.dart'; class ExercisePlanTemplate { - int exercisePlanTemplateId; - String name; - String description; - String templateType; - String nameTranslation; - String descriptionTranslation; - List exerciseTypes = List(); + late int? exercisePlanTemplateId; + late String name; + late String description; + late String templateType; + late String nameTranslation; + late String descriptionTranslation; + List exerciseTypes = []; ExercisePlanTemplate.fromJson(Map json) { this.exercisePlanTemplateId = json['exercisePlanId']; diff --git a/lib/model/exercise_result.dart b/lib/model/exercise_result.dart index bca666e..a2df063 100644 --- a/lib/model/exercise_result.dart +++ b/lib/model/exercise_result.dart @@ -1,24 +1,24 @@ import 'package:aitrainer_app/model/result.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:intl/intl.dart'; class ExerciseResult { - int exerciseResultId; - int customerId; - int exerciseId; - int exercisePlanId; - String resultType; - double value; - DateTime dateFrom; - DateTime dateTo; + late int? exerciseResultId; + late int customerId; + late int exerciseId; + late int exercisePlanId; + late String resultType; + late double value; + late DateTime dateFrom; + late DateTime? dateTo; - ResultExt resultExtension; + ResultExt? resultExtension; ExerciseResult(); Map toJson() { - String formattedDateTo; + String? formattedDateTo; if (dateTo != null) { - formattedDateTo = DateFormat('yyyy-MM-dd HH:mm').format(dateTo); + formattedDateTo = DateFormat('yyyy-MM-dd HH:mm').format(dateTo!); } return { diff --git a/lib/model/exercise_tree.dart b/lib/model/exercise_tree.dart index 465d959..5f8e91f 100644 --- a/lib/model/exercise_tree.dart +++ b/lib/model/exercise_tree.dart @@ -1,24 +1,24 @@ class ExerciseTree { /// treeId - int treeId; + late int treeId; /// parentId - int parentId; + late int parentId; /// name - String name; + late String name; /// imageUrl - String imageUrl; + late String imageUrl; /// active - bool active; + late bool active; /// nameTranslation - String nameTranslation; + late String nameTranslation; /// sort - int sort; + late int? sort; ExerciseTree(); @@ -29,6 +29,7 @@ class ExerciseTree { this.imageUrl = json['imageUrl']; this.active = json['active']; this.nameTranslation = json['translations'] != null && (json['translations']).length > 0 ? json['translations'][0]['name'] : this.name; + this.sort = 99; } Map toJson() { @@ -53,7 +54,7 @@ class ExerciseTree { newTree.parentId = parentId; } newTree.active = this.active; - newTree.sort = this.sort; + newTree.sort = this.sort == null ? 99 : this.sort; return newTree; } diff --git a/lib/model/exercise_tree_parents.dart b/lib/model/exercise_tree_parents.dart index 73e6980..829e894 100644 --- a/lib/model/exercise_tree_parents.dart +++ b/lib/model/exercise_tree_parents.dart @@ -1,8 +1,8 @@ class ExerciseTreeParents { - int exerciseTreeParentsId; - int exerciseTreeParentId; - int exerciseTreeChildId; - int sort; + late int exerciseTreeParentsId; + late int exerciseTreeParentId; + late int exerciseTreeChildId; + late int sort; ExerciseTreeParents.fromJson(Map json) { this.exerciseTreeParentsId = json['exerciseTreeParentsId']; diff --git a/lib/model/exercise_type.dart b/lib/model/exercise_type.dart index 9e1bd17..d17079d 100644 --- a/lib/model/exercise_type.dart +++ b/lib/model/exercise_type.dart @@ -4,28 +4,28 @@ import 'package:flutter/material.dart'; class ExerciseType { ///exerciseTypeId - int exerciseTypeId; + late int exerciseTypeId; /// name - String name; + late String name; /// description - String description; + late String description; /// unit - String unit; + late String unit; /// unitQuantity - String unitQuantity; + late String unitQuantity; /// unitQuantityUnit - String unitQuantityUnit; + String? unitQuantityUnit; ///active - bool active; + late bool active; /// base - bool base; + late bool base; /// imageUrl String imageUrl = ""; @@ -37,18 +37,18 @@ class ExerciseType { String descriptionTranslation = ""; /// devices[] - List devices = List(); + List devices = []; /// parents[] - List parents = List(); + List parents = []; /// alternatives [] - List alternatives = List(); + List alternatives = []; /// ability - ExerciseAbility ability; + ExerciseAbility? ability; - ExerciseType({this.name, this.description}); + ExerciseType({required this.name, required this.description}); ExerciseType.fromJson(Map json) { this.exerciseTypeId = json['exerciseTypeId']; @@ -110,11 +110,11 @@ class ExerciseType { } ExerciseAbility getAbility() { - return this.ability; + return this.ability!; } bool is1RM() { - return this.ability.equalsTo(ExerciseAbility.oneRepMax); + return this.ability!.equalsTo(ExerciseAbility.oneRepMax); } @override diff --git a/lib/model/exercise_type_device.dart b/lib/model/exercise_type_device.dart index d616819..c0e8c3b 100644 --- a/lib/model/exercise_type_device.dart +++ b/lib/model/exercise_type_device.dart @@ -1,6 +1,6 @@ class ExerciseTypeDevice { - int exerciseTypeDeviceId; - int exerciseDeviceId; + late int exerciseTypeDeviceId; + late int exerciseDeviceId; ExerciseTypeDevice(); diff --git a/lib/model/fitness_state.dart b/lib/model/fitness_state.dart index 2c6394d..e24c109 100644 --- a/lib/model/fitness_state.dart +++ b/lib/model/fitness_state.dart @@ -1,16 +1,16 @@ class FitnessState { - final String value; - final String stateText; - final String explanation; + late final String value; + late final String stateText; + late final String explanation; static String beginner = "beginner"; static String intermediate = "intermediate"; static String advanced = "advanced"; static String professional = "professional"; - FitnessState({this.value, this.stateText, this.explanation}); + FitnessState({required this.value, required this.stateText, required this.explanation}); - bool isEqual(FitnessState state) { + bool isEqual(FitnessState? state) { if (state == null) { return false; } @@ -25,7 +25,7 @@ class FitnessState { class FitnessItem { static final FitnessItem _singleton = FitnessItem._internal(); - List elements = List(); + List elements = []; factory FitnessItem() { return _singleton; @@ -52,11 +52,11 @@ class FitnessItem { List toList() => elements; - FitnessState getItem(String value) { + FitnessState? getItem(String? value) { if (value == null || value.length == 0) { return elements[0]; } - FitnessState selected; + FitnessState? selected; elements.forEach((element) { if (element.value == value) { selected = element; diff --git a/lib/model/product.dart b/lib/model/product.dart index 5acba9a..3cbbfb3 100644 --- a/lib/model/product.dart +++ b/lib/model/product.dart @@ -1,18 +1,18 @@ class Product { - int productId; - String name; - String description; - String type; - String appVersion; - int sort; - int productSet; - DateTime validFrom; - DateTime validTo; - String productIdIos; - String productIdAndroid; - double priceIos; - double priceAndroid; - String localizedPrice; + late int productId; + late String name; + late String description; + late String type; + late String appVersion; + late int sort; + late int productSet; + late DateTime validFrom; + late DateTime? validTo; + late String? productIdIos; + late String? productIdAndroid; + late double? priceIos; + late double? priceAndroid; + String? localizedPrice; Product.fromJson(Map json) { this.productId = json['productId']; @@ -22,7 +22,7 @@ class Product { this.appVersion = json['appVersion']; this.sort = json['sort']; this.productSet = json['productSet']; - this.validFrom = json['validFrom'] == null ? null : DateTime.parse(json['validFrom']); + this.validFrom = (json['validFrom'] == null ? null : DateTime.parse(json['validFrom']))!; this.validTo = json['validTo'] == null ? null : DateTime.parse(json['validTo']); this.productIdIos = json['productIdIos']; this.productIdAndroid = json['productIdAndroid']; diff --git a/lib/model/product_test.dart b/lib/model/product_test.dart index 8853821..ce1de3b 100644 --- a/lib/model/product_test.dart +++ b/lib/model/product_test.dart @@ -1,12 +1,12 @@ import 'package:intl/intl.dart'; class ProductTest { - int productTestId; - int customerId; - int productId; + late int? productTestId; + late int customerId; + late int productId; - DateTime dateView; - bool purchaseClick; + late DateTime dateView; + late bool purchaseClick; ProductTest(); diff --git a/lib/model/property.dart b/lib/model/property.dart index 3e63225..24e145d 100644 --- a/lib/model/property.dart +++ b/lib/model/property.dart @@ -1,11 +1,11 @@ class Property { - int propertyId; - String propertyName; - String propertyUnit; - String propertyNameTranslation; - int top; - int left; - double value; + late int propertyId; + late String propertyName; + late String propertyUnit; + late String propertyNameTranslation; + int? top; + int? left; + double? value; Property.fromJson(Map json) { this.propertyId = json['propertyId']; diff --git a/lib/model/purchase.dart b/lib/model/purchase.dart index 8307d72..2e436ff 100644 --- a/lib/model/purchase.dart +++ b/lib/model/purchase.dart @@ -1,15 +1,15 @@ import 'package:intl/intl.dart'; class Purchase { - int purchaseId; - int customerId; - int productId; + int? purchaseId; + late int customerId; + late int productId; - DateTime dateAdd; - double purchaseSum; - String currency; + late DateTime dateAdd; + late double purchaseSum; + late String currency; - Purchase({this.customerId, this.productId}); + Purchase({required this.customerId, required this.productId}); Purchase.fromJson(Map json) { this.purchaseId = json['purchaseId']; diff --git a/lib/model/result.dart b/lib/model/result.dart index 576fb47..9fabf3c 100644 --- a/lib/model/result.dart +++ b/lib/model/result.dart @@ -62,23 +62,23 @@ extension ResultItemExt on ResultItem { bool equals(ResultItem item) => this.toString() == item.toString(); bool equalsString(String item) => this.description == item; - String get description => ResultItemDesc[this]; - String get image => ResultItemImg[this]; - bool get isHardware => HardwareData[this]; + String? get description => ResultItemDesc[this]; + String? get image => ResultItemImg[this]; + bool? get isHardware => HardwareData[this]; - String displayString() => description; + String? displayString() => description; } class ResultExt { - final String itemString; - ResultItem item; + late final String itemString; + late ResultItem item; double data = 0; - int exerciseId; - DateTime dateFrom; + int? exerciseId; + DateTime? dateFrom; - DateTime dateTo; + DateTime? dateTo; - ResultExt({this.itemString}) { + ResultExt({required this.itemString}) { ResultItem.values.forEach((element) { if (element.equalsString(itemString)) { item = element; @@ -86,15 +86,15 @@ class ResultExt { }); } - String getDescription() => item.description; - String getImage() => "asset/image/" + item.image; - bool isHardware() => item.isHardware; - int get getExerciseId => exerciseId; + String? getDescription() => item.description; + String getImage() => "asset/image/" + item.image!; + bool? isHardware() => item.isHardware; + int? get getExerciseId => exerciseId; set setExerciseId(int exerciseId) => this.exerciseId = exerciseId; set setDateFrom(DateTime dateFrom) => this.dateFrom = dateFrom; - DateTime get getDateFrom => dateFrom; + DateTime? get getDateFrom => dateFrom; set setDateTo(DateTime dateTo) => this.dateTo = dateTo; - DateTime get getDateTo => dateTo; + DateTime? get getDateTo => dateTo; bool equals(ResultItem item) => this.item.equals(item); bool equalsString(String item) => this.item.equalsString(item); diff --git a/lib/model/tracking.dart b/lib/model/tracking.dart index d728574..5fe9d23 100644 --- a/lib/model/tracking.dart +++ b/lib/model/tracking.dart @@ -4,13 +4,13 @@ import 'package:aitrainer_app/model/cache.dart'; import 'package:intl/intl.dart'; class Tracking { - int customerId; - DateTime dateAdd; - String event; - String eventValue; - String area; - String platform; - String version; + late int customerId; + late DateTime dateAdd; + late String event; + late String eventValue; + late String area; + late String platform; + late String version; Map toJson() => { "customerId": customerId, diff --git a/lib/model/user.dart b/lib/model/user.dart index 495dfc6..2b4dedd 100644 --- a/lib/model/user.dart +++ b/lib/model/user.dart @@ -1,17 +1,14 @@ - class User { - String email; - String password; - int customerId; - String firebaseUid; +class User { + String? email; + String? password; + int? customerId; + String? firebaseUid; + User(); - User({this.customerId, this.email, this.password}); - - - Map toJson() => - { - "username": email, - "password": password, - "firebaseUid": firebaseUid, - }; + Map toJson() => { + "username": email, + "password": password, + "firebaseUid": firebaseUid, + }; } diff --git a/lib/model/workout_menu_tree.dart b/lib/model/workout_menu_tree.dart index a468f5c..55a93e0 100644 --- a/lib/model/workout_menu_tree.dart +++ b/lib/model/workout_menu_tree.dart @@ -15,31 +15,31 @@ extension WorkoutTypeExt on WorkoutType { bool equals(WorkoutType type) => this.toString() == type.toString(); bool equalsString(String type) => this.toString() == type; - String get menu => WorkoutTypeMenu[this]; + String? get menu => WorkoutTypeMenu[this]; } class WorkoutMenuTree { - int id; - int parent; - String name; - String imageName; - Color color; - double fontSize; - bool child; - int exerciseTypeId; - ExerciseType exerciseType; - bool base; + late int id; + late int parent; + late String name; + late String imageName; + late Color color; + late double fontSize; + late bool child; + late int exerciseTypeId; + ExerciseType? exerciseType; + late bool base; - bool is1RM; - bool isRunning; - List workoutTypes = List(); + late bool is1RM; + late bool isRunning; + List workoutTypes = []; bool selected = false; bool executed = false; - String exerciseDetail; - String nameEnglish; - String parentName; - String parentNameEnglish; - int sort; + late String exerciseDetail; + late String nameEnglish; + late String parentName; + late String parentNameEnglish; + late int sort; WorkoutMenuTree(this.id, this.parent, this.name, this.imageName, this.color, this.fontSize, this.child, this.exerciseTypeId, this.exerciseType, this.base, this.is1RM, this.isRunning, this.nameEnglish, this.parentName, this.parentNameEnglish, this.sort); diff --git a/lib/push_notifications.dart b/lib/push_notifications.dart index c2fb5a9..cdf31b6 100644 --- a/lib/push_notifications.dart +++ b/lib/push_notifications.dart @@ -1,5 +1,6 @@ import 'package:aitrainer_app/service/logging.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; class PushNotificationsManager with Logging { PushNotificationsManager._(); @@ -8,20 +9,23 @@ class PushNotificationsManager with Logging { static final PushNotificationsManager _instance = PushNotificationsManager._(); - final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); - bool _initialized = false; - Future init() async { - if (!_initialized) { - // For iOS request permission first. - _firebaseMessaging.requestNotificationPermissions(); - _firebaseMessaging.configure(); + const AndroidNotificationChannel channel = AndroidNotificationChannel( + 'high_importance_channel', // id + 'High Importance Notifications', // title + 'This channel is used for important notifications.', // description + importance: Importance.max, + ); + final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); - // For testing purposes log the Firebase Messaging token - String token = await _firebaseMessaging.getToken(); - log("FirebaseMessaging token: $token"); + await flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation() + ?.createNotificationChannel(channel); - _initialized = true; - } + await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( + alert: true, // Required to display a heads up notification + badge: true, + sound: true, + ); } } diff --git a/lib/repository/customer_exercise_device_repository.dart b/lib/repository/customer_exercise_device_repository.dart index 8c9610e..070080a 100644 --- a/lib/repository/customer_exercise_device_repository.dart +++ b/lib/repository/customer_exercise_device_repository.dart @@ -5,38 +5,36 @@ import 'package:aitrainer_app/model/model_change.dart'; import 'package:aitrainer_app/service/customer_exercise_device_service.dart'; class CustomerExerciseDeviceRepository { - List _devices = List(); + List _devices = []; List getDevices() => this._devices; void setDevices(List devices) => this._devices = devices; - Future> getDBDevices() async { + Future?> getDBDevices() async { if (Cache().userLoggedIn != null) { - final int customerId = Cache().userLoggedIn.customerId; + final int customerId = Cache().userLoggedIn!.customerId!; this._devices = await CustomerExerciseDeviceApi().getDevices(customerId); } return this._devices; } Future addDevice(ExerciseDevice device) async { - CustomerExerciseDevice found; - if (_devices != null) { - this._devices.forEach((element) { - if (element.exerciseDeviceId == device.exerciseDeviceId) { - found = element; - } - }); - } else { - _devices = List(); - } + CustomerExerciseDevice? found; + + this._devices.forEach((element) { + if (element.exerciseDeviceId == device.exerciseDeviceId) { + found = element; + } + }); + if (found == null) { - int customerId; + int? customerId; if (Cache().userLoggedIn != null) { - customerId = Cache().userLoggedIn.customerId; + customerId = Cache().userLoggedIn!.customerId!; } CustomerExerciseDevice newDevice = - CustomerExerciseDevice(customerId: customerId, exerciseDeviceId: device.exerciseDeviceId, favourite: false); + CustomerExerciseDevice(customerId: customerId!, exerciseDeviceId: device.exerciseDeviceId, favourite: false); newDevice.change = ModelChange.add; CustomerExerciseDevice saved = await CustomerExerciseDeviceApi().addDevice(newDevice); this._devices.add(saved); @@ -45,18 +43,18 @@ class CustomerExerciseDeviceRepository { } Future removeDevice(ExerciseDevice device) async { - CustomerExerciseDevice found; - if (_devices != null) { - this._devices.forEach((element) { - if (element.exerciseDeviceId == device.exerciseDeviceId) { - found = element; - } - }); - } + CustomerExerciseDevice? found; + + this._devices.forEach((element) { + if (element.exerciseDeviceId == device.exerciseDeviceId) { + found = element; + } + }); + if (found != null) { this._devices.remove(found); //if (found.change != ModelChange.add) { - await CustomerExerciseDeviceApi().removeDevice(found.customerExerciseDeviceId); + await CustomerExerciseDeviceApi().removeDevice(found!.customerExerciseDeviceId!); //} Cache().setCustomerDevices(_devices); } @@ -64,13 +62,13 @@ class CustomerExerciseDeviceRepository { bool hasDevice(int exerciseDeviceId) { bool found = false; - if (_devices != null) { - this._devices.forEach((element) { - if (element.exerciseDeviceId == exerciseDeviceId) { - found = true; - } - }); - } + + this._devices.forEach((element) { + if (element.exerciseDeviceId == exerciseDeviceId) { + found = true; + } + }); + return found; } } diff --git a/lib/repository/customer_repository.dart b/lib/repository/customer_repository.dart index 5444a80..33affc6 100644 --- a/lib/repository/customer_repository.dart +++ b/lib/repository/customer_repository.dart @@ -21,13 +21,13 @@ class GenderItem { } class CustomerRepository with Logging { - Customer customer; - Customer _trainee; - List _trainees; - List _allProperties; + late Customer customer; + late Customer? _trainee; + List? _trainees; + List? _allProperties; final PropertyRepository propertyRepository = PropertyRepository(); - final List womanSizes = List(); - final List manSizes = List(); + final List womanSizes = []; + final List manSizes = []; final double baseWidth = 312; final double baseHeight = 675.2; @@ -37,18 +37,18 @@ class CustomerRepository with Logging { //List customerList = List(); bool visibleDetails = false; - List genders; + late List genders; - CustomerRepository({this.customer}) { + CustomerRepository() { customer = Customer(); if (Cache().userLoggedIn != null) { - isMan = (Cache().userLoggedIn.sex == "m"); + isMan = (Cache().userLoggedIn!.sex == "m"); } } - String getGenderByName(String name) { - String dbValue; + String? getGenderByName(String name) { + String? dbValue; genders.forEach((element) { if (element.name == name) { dbValue = element.dbValue; @@ -57,8 +57,8 @@ class CustomerRepository with Logging { return dbValue; } - String getGenderByDBValue(String dbValue) { - String name; + String? getGenderByDBValue(String dbValue) { + String? name; genders.forEach((element) { if (element.dbValue == dbValue) { name = element.name; @@ -67,11 +67,11 @@ class CustomerRepository with Logging { return name; } - String get name { + String? get name { return this.customer.name != null ? this.customer.name : ""; } - String get firstName { + String? get firstName { return this.customer.firstname != null ? this.customer.firstname : ""; } @@ -79,19 +79,19 @@ class CustomerRepository with Logging { return this.customer.sex == "m" ? "Man" : "Woman"; } - int get birthYear { + int? get birthYear { return this.customer.birthYear; } - String get goal { + String? get goal { return this.customer.goal; } - String get fitnessLevel { + String? get fitnessLevel { return this.customer.fitnessLevel; } - String get bodyType { + String? get bodyType { return this.customer.bodyType; } @@ -128,16 +128,17 @@ class CustomerRepository with Logging { setCustomerProperty(String propertyName, double value, {id = 0}) { if (this.customer.properties[propertyName] == null) { this.customer.properties[propertyName] = CustomerProperty( - propertyId: propertyRepository.getPropertyByName("Height").propertyId, - customerId: this.customer.customerId, - propertyValue: value); + propertyId: propertyRepository.getPropertyByName("Height")!.propertyId, + customerId: this.customer.customerId!, + propertyValue: value, + dateAdd: DateTime.now()); } else { - this.customer.properties[propertyName].propertyValue = value; + this.customer.properties[propertyName]!.propertyValue = value; } - this.customer.properties[propertyName].dateAdd = DateTime.now(); - this.customer.properties[propertyName].newData = true; + this.customer.properties[propertyName]!.dateAdd = DateTime.now(); + this.customer.properties[propertyName]!.newData = true; if (id > 0) { - this.customer.properties[propertyName].customerPropertyId = id; + this.customer.properties[propertyName]!.customerPropertyId = id; } } @@ -150,14 +151,14 @@ class CustomerRepository with Logging { } double getCustomerPropertyValue(String propertyName) { - if (this.customer == null || this.customer.properties == null || this.customer.properties[propertyName] == null) { + if (this.customer.properties[propertyName] == null) { return 0.0; } else { - return this.customer.properties[propertyName].propertyValue; + return this.customer.properties[propertyName]!.propertyValue; } } - CustomerProperty getCustomerProperty(String propertyName) { + CustomerProperty? getCustomerProperty(String propertyName) { return this.customer.properties[propertyName]; } @@ -210,39 +211,41 @@ class CustomerRepository with Logging { } Future savePropertyByName(String name) async { - await Future.forEach(this._allProperties, (element) async { - final CustomerProperty customerProperty = element; - final Property property = propertyRepository.getPropertyByName(name); - if (property.propertyId == customerProperty.propertyId) { - await CustomerApi().updateProperty(customerProperty); + await Future.forEach(this._allProperties!, (element) async { + final CustomerProperty customerProperty = element as CustomerProperty; + final Property? property = propertyRepository.getPropertyByName(name); + if (property != null) { + if (property.propertyId == customerProperty.propertyId) { + await CustomerApi().updateProperty(customerProperty); + } } }); } - Future getTraineeAsCustomer() async { - this._trainee = await CustomerApi().getTrainee(Cache().userLoggedIn.customerId); + Future getTraineeAsCustomer() async { + this._trainee = await CustomerApi().getTrainee(Cache().userLoggedIn!.customerId!); return _trainee; } - Future> getTrainees() async { - int trainerId = Cache().userLoggedIn.customerId; + Future?> getTrainees() async { + int trainerId = Cache().userLoggedIn!.customerId!; final results = await CustomerApi().getTrainees(trainerId); this._trainees = results; return results; } Future> getAllCustomerProperties() async { - int customerId = Cache().userLoggedIn.customerId; + int customerId = Cache().userLoggedIn!.customerId!; final results = await CustomerApi().getAllProperties(customerId); this._allProperties = results; return results; } - List getAllProperties() { + List? getAllProperties() { return this._allProperties; } - List getTraineesList() { + List? getTraineesList() { return _trainees; } @@ -250,7 +253,7 @@ class CustomerRepository with Logging { if (_trainees == null) { return; } - _trainees.forEach((element) { + _trainees!.forEach((element) { if (traineeId == element.customerId) { this._trainee = element; } @@ -262,15 +265,15 @@ class CustomerRepository with Logging { _trainee = null; } - Customer getTrainee() { + Customer? getTrainee() { return this._trainee; } - Customer getTraineeById(int customerId) { + Customer? getTraineeById(int customerId) { if (_trainees == null) { return null; } - _trainees.forEach((element) { + _trainees!.forEach((element) { if (customerId == element.customerId) { this._trainee = element; } @@ -279,7 +282,7 @@ class CustomerRepository with Logging { } Future> getPurchase() async { - int customerId = Cache().userLoggedIn.customerId; + int customerId = Cache().userLoggedIn!.customerId!; List purchases = await PurchaseApi().getPurchasesByCustomer(customerId); return purchases; } @@ -289,9 +292,9 @@ class CustomerRepository with Logging { } Future> getProductTests() async { - List tests = List(); + List tests = []; try { - int customerId = Cache().userLoggedIn.customerId; + int customerId = Cache().userLoggedIn!.customerId!; tests = await ProductTestApi().getProductTestByCustomer(customerId); } on NotFoundException catch (_) { log("Product Tests not found"); @@ -314,7 +317,7 @@ class CustomerRepository with Logging { } void addSizes(String sex) { - List properties = Cache().getProperties(); + List? properties = Cache().getProperties(); if (properties == null) { return; } @@ -451,8 +454,8 @@ class CustomerRepository with Logging { } } - int getWeightCoordinate(isMan, {isTop = false, isLeft = false}) { - int value = 0; + int? getWeightCoordinate(isMan, {isTop = false, isLeft = false}) { + int? value = 0; this.manSizes.forEach((element) { if (element.propertyName == SizesEnum.Weight.toStr()) { if (isTop == true) { @@ -465,8 +468,8 @@ class CustomerRepository with Logging { return value; } - Property getPropertyByName(String propertyName) { - Property property; + Property? getPropertyByName(String propertyName) { + Property? property; List sizes; if (this.sex == "m") { sizes = this.manSizes; diff --git a/lib/repository/exercise_device_repository.dart b/lib/repository/exercise_device_repository.dart index 601f545..e14fa5b 100644 --- a/lib/repository/exercise_device_repository.dart +++ b/lib/repository/exercise_device_repository.dart @@ -3,7 +3,7 @@ import 'package:aitrainer_app/model/exercise_device.dart'; import 'package:aitrainer_app/service/exercise_device_service.dart'; class ExerciseDeviceRepository { - List _devices = List(); + List _devices = []; List getDevices() { return this._devices; @@ -37,9 +37,9 @@ class ExerciseDeviceRepository { } List getGymDevices() { - final List gymDevices = List(); - if (_devices == null || _devices.isEmpty) { - _devices = Cache().getDevices(); + final List gymDevices = []; + if (_devices.isEmpty) { + _devices = Cache().getDevices()!; } _devices.forEach((element) { if (isGymElement(element.name)) { diff --git a/lib/repository/exercise_plan_repository.dart b/lib/repository/exercise_plan_repository.dart index ca2eba7..dd3d05e 100644 --- a/lib/repository/exercise_plan_repository.dart +++ b/lib/repository/exercise_plan_repository.dart @@ -9,10 +9,10 @@ import 'package:aitrainer_app/service/exercise_plan_service.dart'; class ExercisePlanRepository { bool newPlan = true; - ExercisePlan exercisePlan; + ExercisePlan? exercisePlan; LinkedHashMap exercisePlanDetails = LinkedHashMap(); int customerId = 0; - ExercisePlanDetail actualPlanDetail; + ExercisePlanDetail? actualPlanDetail; void setCustomerId(int customerId) { this.customerId = customerId; @@ -24,41 +24,41 @@ class ExercisePlanRepository { this.exercisePlan = plan; } - ExercisePlan getExercisePlan() => exercisePlan; + ExercisePlan? getExercisePlan() => exercisePlan; void addDetailToPlan() { - if (exercisePlan != null) { - actualPlanDetail.exercisePlanId = exercisePlan.exercisePlanId; + if (exercisePlan != null && actualPlanDetail != null) { + actualPlanDetail!.exercisePlanId = exercisePlan!.exercisePlanId!; + exercisePlanDetails[actualPlanDetail!.exerciseTypeId] = actualPlanDetail!; + Cache().addToMyExercisePlanDetails(actualPlanDetail!); } - exercisePlanDetails[actualPlanDetail.exerciseTypeId] = actualPlanDetail; - Cache().addToMyExercisePlanDetails(actualPlanDetail); } - ExercisePlanDetail getExercisePlanDetailByExerciseId(int exerciseTypeId) => exercisePlanDetails[exerciseTypeId]; + ExercisePlanDetail? getExercisePlanDetailByExerciseId(int exerciseTypeId) => exercisePlanDetails[exerciseTypeId]; void setActualPlanDetailByExerciseType(ExerciseType exerciseType) { - ExercisePlanDetail detail = exercisePlanDetails[exerciseType.exerciseTypeId]; + ExercisePlanDetail? detail = exercisePlanDetails[exerciseType.exerciseTypeId]; if (detail != null) { actualPlanDetail = detail; } else { actualPlanDetail = ExercisePlanDetail(exerciseType.exerciseTypeId); } - actualPlanDetail.exerciseType = exerciseType; + actualPlanDetail!.exerciseType = exerciseType; } - ExercisePlanDetail getActualPlanDetail() => actualPlanDetail; + ExercisePlanDetail? getActualPlanDetail() => actualPlanDetail; void setActualPlanDetail(ExercisePlanDetail detail) { this.actualPlanDetail = detail; } - int getPlanDetailId(int exerciseTypeId) => exercisePlanDetails[exerciseTypeId].exercisePlanDetailId; + int getPlanDetailId(int exerciseTypeId) => exercisePlanDetails[exerciseTypeId]!.exercisePlanDetailId!; String getPlanDetail(int exerciseTypeId) { - ExercisePlanDetail detail = exercisePlanDetails[exerciseTypeId]; + ExercisePlanDetail? detail = exercisePlanDetails[exerciseTypeId]; String detailString = ""; if (detail != null) { - detailString = detail.serie.toString() + "x" + detail.repeats.toString() + " " + detail.weightEquation + "kg"; + detailString = detail.serie.toString() + "x" + detail.repeats.toString() + " " + detail.weightEquation! + "kg"; } return detailString; } @@ -71,8 +71,8 @@ class ExercisePlanRepository { if (exercisePlanDetails[exerciseType.exerciseTypeId] == null) { return; } - ExercisePlanDetail exercisePlanDetail = exercisePlanDetails[exerciseType.exerciseTypeId]; - exercisePlanDetail.serie = serie; + ExercisePlanDetail? exercisePlanDetail = exercisePlanDetails[exerciseType.exerciseTypeId]; + exercisePlanDetail!.serie = serie; exercisePlanDetail.repeats = repeat; exercisePlanDetail.weightEquation = weight; exercisePlanDetail.change = ModelChange.update; @@ -85,7 +85,7 @@ class ExercisePlanRepository { } void removeExerciseTypeFromPlanByExerciseTypeId(int exerciseTypeId) { - exercisePlanDetails[exerciseTypeId].change = ModelChange.delete; + exercisePlanDetails[exerciseTypeId]!.change = ModelChange.delete; Cache().deleteMyExercisePlanDetailByExerciseTypeId(exerciseTypeId); } @@ -96,22 +96,22 @@ class ExercisePlanRepository { } String exercisePlanName; - if (this.customerId == Cache().userLoggedIn.customerId) { - exercisePlanName = Cache().userLoggedIn.name + " private"; + if (this.customerId == Cache().userLoggedIn!.customerId) { + exercisePlanName = Cache().userLoggedIn!.name! + " private"; } else { - exercisePlanName = Cache().getTrainee().name + " " + Cache().getTrainee().firstname + " private"; + exercisePlanName = Cache().getTrainee()!.name! + " " + Cache().getTrainee()!.firstname! + " private"; } exercisePlan = ExercisePlan(exercisePlanName, this.customerId); } if (newPlan) { - exercisePlan.dateAdd = DateTime.now(); - exercisePlan.private = true; - ExercisePlan savedExercisePlan = await ExercisePlanApi().saveExercisePlan(exercisePlan); + exercisePlan!.dateAdd = DateTime.now(); + exercisePlan!.private = true; + ExercisePlan savedExercisePlan = await ExercisePlanApi().saveExercisePlan(exercisePlan!); LinkedHashMap savedExercisePlanDetails = LinkedHashMap(); exercisePlanDetails.forEach((exerciseTypeId, exercisePlanDetail) async { - exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId; + exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId!; ExercisePlanDetail savedDetail = await ExercisePlanApi().saveExercisePlanDetail(exercisePlanDetail); savedExercisePlanDetails[savedDetail.exerciseTypeId] = savedDetail; }); @@ -123,11 +123,11 @@ class ExercisePlanRepository { exercisePlanDetails.forEach((exerciseTypeId, exercisePlanDetail) async { if (exercisePlanDetail.change == ModelChange.delete) { - await ExercisePlanApi().deleteExercisePlanDetail(exercisePlanDetail.exercisePlanDetailId); + await ExercisePlanApi().deleteExercisePlanDetail(exercisePlanDetail.exercisePlanDetailId!); exercisePlanDetail.change = ModelChange.deleted; Cache().deletedMyExercisePlanDetail(exercisePlanDetail); } else if (exercisePlanDetail.change == ModelChange.update) { - await ExercisePlanApi().updateExercisePlanDetail(exercisePlanDetail, exercisePlanDetail.exercisePlanDetailId); + await ExercisePlanApi().updateExercisePlanDetail(exercisePlanDetail, exercisePlanDetail.exercisePlanDetailId!); Cache().updateMyExercisePlanDetail(exercisePlanDetail); exercisePlanDetail.change = ModelChange.saved; } else if (exercisePlanDetail.change == ModelChange.add) { @@ -139,11 +139,11 @@ class ExercisePlanRepository { } } - Future getLastExercisePlan() async { + Future getLastExercisePlan() async { if (customerId == 0) { return null; } - ExercisePlan myExercisePlan = Cache().getMyExercisePlan(); + ExercisePlan? myExercisePlan = Cache().getMyExercisePlan(); if (myExercisePlan != null) { exercisePlan = myExercisePlan; return myExercisePlan; @@ -151,26 +151,26 @@ class ExercisePlanRepository { exercisePlan = await ExercisePlanApi().getLastExercisePlan(customerId); newPlan = (exercisePlan == null); - Cache().setMyExercisePlan(exercisePlan); + Cache().setMyExercisePlan(exercisePlan!); return exercisePlan; } Future getExercisePlanDetails() async { if (exercisePlan == null) { - ExercisePlan exercisePlan = await this.getLastExercisePlan(); + ExercisePlan? exercisePlan = await this.getLastExercisePlan(); if (exercisePlan == null) { exercisePlanDetails = LinkedHashMap(); return; } } - List list = List(); + List list = []; LinkedHashMap listCache = Cache().getMyExercisePlanDetails(); if (listCache.length > 0) { exercisePlanDetails = listCache; return; } else { - list = await ExercisePlanApi().getExercisePlanDetail(exercisePlan.exercisePlanId); + list = await ExercisePlanApi().getExercisePlanDetail(exercisePlan!.exercisePlanId!); } exercisePlanDetails = LinkedHashMap(); diff --git a/lib/repository/exercise_repository.dart b/lib/repository/exercise_repository.dart index 2d2ab84..09af0d0 100644 --- a/lib/repository/exercise_repository.dart +++ b/lib/repository/exercise_repository.dart @@ -7,15 +7,15 @@ import 'package:aitrainer_app/model/exercise.dart'; import 'package:aitrainer_app/model/exercise_type.dart'; import 'package:aitrainer_app/model/workout_menu_tree.dart'; import 'package:aitrainer_app/service/exercise_service.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:intl/intl.dart'; class ExerciseRepository { - Exercise exercise; - Customer customer; - ExerciseType exerciseType; - List exerciseList; - List exerciseLogList = List(); - List actualExerciseList = List(); + Exercise? exercise; + Customer? customer; + ExerciseType? exerciseType; + List? exerciseList; + List? exerciseLogList = []; + List? actualExerciseList = []; double rmWendler = 0; double rmMcglothlin = 0; @@ -24,8 +24,8 @@ class ExerciseRepository { double rmOconner = 0; double rmWathen = 0; - DateTime start; - DateTime end; + DateTime? start; + DateTime? end; ExerciseRepository() { this.createNew(); @@ -33,14 +33,14 @@ class ExerciseRepository { createNew() { this.exercise = Exercise(); - exercise.dateAdd = DateTime.now(); + exercise!.dateAdd = DateTime.now(); } setQuantity(double quantity) { if (this.exercise == null) { this.createNew(); } - this.exercise.quantity = quantity; + this.exercise!.quantity = quantity; } setUnitQuantity(double unitQuantity) { @@ -48,7 +48,7 @@ class ExerciseRepository { this.createNew(); } - this.exercise.unitQuantity = unitQuantity; + this.exercise!.unitQuantity = unitQuantity; } setUnit(String unit) { @@ -56,7 +56,7 @@ class ExerciseRepository { this.createNew(); } - this.exercise.unit = unit; + this.exercise!.unit = unit; } setDatetimeExercise(DateTime datetimeExercise) { @@ -64,33 +64,33 @@ class ExerciseRepository { this.createNew(); } - this.exercise.dateAdd = datetimeExercise; + this.exercise!.dateAdd = datetimeExercise; } - double get unitQuantity => this.exercise.unitQuantity; + double? get unitQuantity => this.exercise!.unitQuantity; - double get quantity => this.exercise.quantity; + double? get quantity => this.exercise!.quantity; - Exercise getExercise() => this.exercise; + Exercise? getExercise() => this.exercise; Future addExercise() async { - final Exercise modelExercise = this.exercise; - modelExercise.customerId = this.customer.customerId; - modelExercise.exerciseTypeId = this.exerciseType.exerciseTypeId; - if (exerciseType.unitQuantity != "1") { + final Exercise modelExercise = this.exercise!; + modelExercise.customerId = this.customer!.customerId; + modelExercise.exerciseTypeId = this.exerciseType!.exerciseTypeId; + if (exerciseType!.unitQuantity != "1") { modelExercise.unitQuantity = null; } Exercise copy = modelExercise.copy(); - this.actualExerciseList.add(copy); + this.actualExerciseList!.add(copy); //final int index = this.actualExerciseList.length - 1; //print("$index. actual exercise " + this.actualExerciseList[index].toJson().toString()); Exercise savedExercise = await ExerciseApi().addExercise(modelExercise); //this.actualExerciseList[index].exerciseId = savedExercise.exerciseId; - if (customer.customerId == Cache().userLoggedIn.customerId) { + if (customer!.customerId == Cache().userLoggedIn!.customerId) { Cache().addExercise(savedExercise); - } else if (Cache().getTrainee() != null && customer.customerId == Cache().getTrainee().customerId) { + } else if (Cache().getTrainee() != null && customer!.customerId == Cache().getTrainee()!.customerId) { Cache().addExerciseTrainee(savedExercise); } @@ -100,12 +100,12 @@ class ExerciseRepository { void initExercise() { this.createNew(); this.exerciseType = exerciseType; - this.setUnit(exerciseType.unit); - exercise.exerciseTypeId = this.exerciseType.exerciseTypeId; + this.setUnit(exerciseType!.unit); + exercise!.exerciseTypeId = this.exerciseType!.exerciseTypeId; this.setQuantity(12); this.setUnitQuantity(30); - this.exercise.exercisePlanDetailId = 0; - exercise.exerciseId = 0; + this.exercise!.exercisePlanDetailId = 0; + exercise!.exerciseId = 0; this.start = DateTime.now(); } @@ -121,35 +121,35 @@ class ExerciseRepository { final results = await ExerciseApi().getExercisesByCustomer(customerId); this.exerciseList = results; if (Cache().userLoggedIn != null) { - if (customerId == Cache().userLoggedIn.customerId) { - Cache().setExercises(exerciseList); - } else if (Cache().getTrainee() != null && customerId == Cache().getTrainee().customerId) { - Cache().setExercisesTrainee(exerciseList); + if (customerId == Cache().userLoggedIn!.customerId) { + Cache().setExercises(exerciseList!); + } else if (Cache().getTrainee() != null && customerId == Cache().getTrainee()!.customerId) { + Cache().setExercisesTrainee(exerciseList!); } } - return this.exerciseList; + return this.exerciseList!; } - List getExerciseList() { + List? getExerciseList() { this.exerciseList = Cache().getExercises(); return this.exerciseList; } - List getExerciseListTrainee() { + List? getExerciseListTrainee() { this.exerciseList = Cache().getExercisesTrainee(); return this.exerciseList; } - String nextMissingBaseExercise(SplayTreeMap sortedTree) { + String? nextMissingBaseExercise(SplayTreeMap sortedTree) { if (exerciseList == null) { exerciseList = Cache().getExercises(); } if (exerciseList == null) { - return ""; + return null; } - String missingTreeName; - String foundTreeName; + String? missingTreeName; + String? foundTreeName; bool isBreak = false; sortedTree.forEach((key, list) { @@ -162,13 +162,15 @@ class ExerciseRepository { missingTreeName = treeName; } if (exercise.base) { - exerciseList.forEach((element) { - if (element.exerciseTypeId == exercise.exerciseTypeId) { - foundTreeName = treeName; - //print("Found " + foundTreeName + " Missing actual: " + missingTreeName); - isBreak = true; - } - }); + if (exerciseList != null) { + exerciseList!.forEach((element) { + if (element.exerciseTypeId == exercise.exerciseTypeId) { + foundTreeName = treeName; + //print("Found " + foundTreeName + " Missing actual: " + missingTreeName); + isBreak = true; + } + }); + } } }); if (foundTreeName == null && !isBreak) { @@ -181,19 +183,19 @@ class ExerciseRepository { } void getBaseExerciseFinishedPercent() { - List checkedExerciseTypeId = List(); - List baseTreeItem = List(); - List checkedBaseTreeItem = List(); + List checkedExerciseTypeId = []; + List baseTreeItem = []; + List checkedBaseTreeItem = []; int count1RMExercises = 0; LinkedHashMap tree = Cache().getWorkoutMenuTree(); - if (tree == null) { + if (tree.isEmpty) { return; } tree.forEach((key, value) { WorkoutMenuTree treeItem = value; - if (treeItem.exerciseType != null && treeItem.exerciseType.base == true && !baseTreeItem.contains(treeItem.parent)) { + if (treeItem.exerciseType != null && treeItem.exerciseType!.base == true && !baseTreeItem.contains(treeItem.parent)) { baseTreeItem.add(treeItem.parent); } }); @@ -206,15 +208,15 @@ class ExerciseRepository { return; } - exerciseList.forEach((element) { + exerciseList!.forEach((element) { Exercise exercise = element; if (!checkedExerciseTypeId.contains(exercise.exerciseTypeId)) { - checkedExerciseTypeId.add(exercise.exerciseTypeId); + checkedExerciseTypeId.add(exercise.exerciseTypeId!); tree.forEach((key, value) { WorkoutMenuTree treeItem = value; if (treeItem.exerciseType != null && - treeItem.exerciseType.base == true && - exercise.exerciseTypeId == treeItem.exerciseType.exerciseTypeId && + treeItem.exerciseType!.base == true && + exercise.exerciseTypeId == treeItem.exerciseType!.exerciseTypeId && !checkedBaseTreeItem.contains(treeItem.parent)) { //print ("id: " + exercise.exerciseTypeId.toString()); checkedBaseTreeItem.add(treeItem.parent); @@ -232,28 +234,33 @@ class ExerciseRepository { } void getLastExercise() { - List exercises = this.getExerciseList(); - Exercise lastExercise = exercises[0]; - exercises.forEach((element) { - Exercise actualExercise = element; - if (actualExercise.dateAdd.compareTo(lastExercise.dateAdd) > 0) { - lastExercise = actualExercise; - } - }); + List? exercises = this.getExerciseList(); + Exercise? lastExercise = exercises == null ? null : exercises[0]; + if (exercises != null) { + exercises.forEach((element) { + Exercise actualExercise = element; + if (actualExercise.dateAdd!.compareTo(lastExercise!.dateAdd!) > 0) { + lastExercise = actualExercise; + } + }); + } this.exercise = lastExercise; - this.customer = Cache().userLoggedIn; - this.exerciseType = getExerciseTypeById(exercise.exerciseTypeId); + this.customer = Cache().userLoggedIn!; + this.exerciseType = getExerciseTypeById(exercise!.exerciseTypeId!); return; } - ExerciseType getExerciseTypeById(int exerciseTypeId) { - ExerciseType actualExerciseType; - Cache().getExerciseTypes().forEach((element) { - ExerciseType exerciseType = element; - if (exerciseType.exerciseTypeId == exerciseTypeId) { - actualExerciseType = exerciseType; - } - }); + ExerciseType? getExerciseTypeById(int exerciseTypeId) { + ExerciseType? actualExerciseType; + List? exercises = Cache().getExerciseTypes(); + if (exercises != null) { + exercises.forEach((element) { + ExerciseType exerciseType = element; + if (exerciseType.exerciseTypeId == exerciseTypeId) { + actualExerciseType = exerciseType; + } + }); + } if (actualExerciseType == null) { throw Exception("Data error, no ExerciseType for exerciseTypeId $exerciseTypeId"); } @@ -261,60 +268,64 @@ class ExerciseRepository { } void getSameExercise(int exerciseTypeId, String day) { - this.actualExerciseList = List(); - for (int i = 0; i < this.exerciseList.length; i++) { - Exercise exercise = exerciseList[i]; - String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd); - if (exerciseTypeId == exercise.exerciseTypeId && exerciseDate == day) { - this.actualExerciseList.add(exercise); + this.actualExerciseList = []; + if (exerciseList != null) { + for (int i = 0; i < this.exerciseList!.length; i++) { + Exercise exercise = exerciseList![i]; + String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); + if (exerciseTypeId == exercise.exerciseTypeId && exerciseDate == day) { + this.actualExerciseList!.add(exercise); + } } } } void sortByDate() { - if (exerciseList.isEmpty) { + if (exerciseList == null || exerciseList!.isEmpty) { return; } - exerciseList.sort((a, b) { - final String datePartA = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(a.dateAdd); - String aId = a.exerciseTypeId.toString() + "_" + datePartA; - final String datePartB = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(b.dateAdd); - String bId = b.exerciseTypeId.toString() + "_" + datePartB; - return aId.compareTo(bId); + exerciseList!.sort((a, b) { + final String datePartA = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(a.dateAdd!); + String aId = datePartA + "_" + a.exerciseTypeId.toString(); + final String datePartB = DateFormat('yyyyMMdd', AppLanguage().appLocal.toString()).format(b.dateAdd!); + String bId = datePartB + "_" + b.exerciseTypeId.toString(); + return bId.compareTo(aId); }); - this.exerciseLogList = List(); + this.exerciseLogList = []; String summary = ""; - String prevDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exerciseList[0].dateAdd); - int prevExerciseTypeId = exerciseList[0].exerciseTypeId; - Exercise prevExercise = exerciseList[0]; + String prevDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exerciseList![0].dateAdd!); + int prevExerciseTypeId = exerciseList![0].exerciseTypeId!; + Exercise prevExercise = exerciseList![0]; int prevCount = 0; - for (int i = 0; i < this.exerciseList.length; i++) { - Exercise exercise = exerciseList[i]; - int exerciseTypeId = exercise.exerciseTypeId; - String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd); - print(" -- $prevExerciseTypeId - '$prevDate' against $exerciseTypeId - '$exerciseDate'"); + for (int i = 0; i < this.exerciseList!.length; i++) { + Exercise exercise = exerciseList![i]; + int exerciseTypeId = exercise.exerciseTypeId!; + String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); + //print(" -- $prevExerciseTypeId - '$prevDate' against $exerciseTypeId - '$exerciseDate'"); if (exerciseTypeId != prevExerciseTypeId || prevDate != exerciseDate) { - ExerciseType exerciseType = Cache().getExerciseTypeById(prevExercise.exerciseTypeId); - String unit = exerciseType.unitQuantityUnit != null ? exerciseType.unitQuantityUnit : prevExercise.unit; + ExerciseType? exerciseType = Cache().getExerciseTypeById(prevExercise.exerciseTypeId!); + String unit = exerciseType != null && exerciseType.unitQuantityUnit != null ? exerciseType.unitQuantityUnit! : prevExercise.unit!; prevExercise.summary = summary + " " + unit; - exerciseLogList.add(prevExercise); + exerciseLogList!.add(prevExercise); //print("Log add " + exercise.toJson().toString()); summary = ""; prevCount = 0; } String delimiter = ""; if (prevCount > 0) delimiter = ", "; - double quantity = exercise.quantity == null ? 0 : exercise.quantity; + double quantity = exercise.quantity == null ? 0 : exercise.quantity!; summary += delimiter + quantity.toStringAsFixed(0); - ExerciseType exerciseType = Cache().getExerciseTypeById(exercise.exerciseTypeId); - print("exerciseType " + (exerciseType == null ? "NULL" : exerciseType.name) + " ID " + exercise.exerciseTypeId.toString()); - if (exerciseType.unitQuantity == "1") { - summary += "x" + exercise.unitQuantity.toStringAsFixed(0); + ExerciseType? exerciseType = Cache().getExerciseTypeById(exercise.exerciseTypeId!); + //print("exerciseType " + (exerciseType == null ? "NULL" : exerciseType.name) + " ID " + exercise.exerciseTypeId.toString()); + if (exerciseType != null) { + if (exerciseType.unitQuantity == "1") { + summary += "x" + exercise.unitQuantity!.toStringAsFixed(0); + } + //print(" --- sum " + exerciseType.name + " $summary"); } - print(" --- sum " + exerciseType.name + " $summary"); prevExerciseTypeId = exerciseTypeId; prevDate = exerciseDate; @@ -322,6 +333,6 @@ class ExerciseRepository { prevCount++; } prevExercise.summary = summary; - exerciseLogList.add(prevExercise); + exerciseLogList!.add(prevExercise); } } diff --git a/lib/repository/exercise_result_repository.dart b/lib/repository/exercise_result_repository.dart index 648189b..3e86016 100644 --- a/lib/repository/exercise_result_repository.dart +++ b/lib/repository/exercise_result_repository.dart @@ -9,49 +9,44 @@ extension ResultTypeExt on ResultType { } class ExerciseResultRepository { - final List _results = List(); + final List _results = []; ResultType resultType; - ExerciseResultRepository({this.resultType}) { - if (resultType == null) { - resultType = ResultType.man; - } + ExerciseResultRepository({required this.resultType}) { if (resultType.equals(ResultType.man) || resultType.equals(ResultType.woman)) { //_results.add(ResultExt(itemString: ResultItem.time.description)); - _results.add(ResultExt(itemString: ResultItem.reps_volume.description)); - _results.add(ResultExt(itemString: ResultItem.weight_volume.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_max.description)); - _results.add(ResultExt(itemString: ResultItem.calorie.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_avg.description)); - _results.add(ResultExt(itemString: ResultItem.fatburn_percent.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_min.description)); + _results.add(ResultExt(itemString: ResultItem.reps_volume.description.toString())); + _results.add(ResultExt(itemString: ResultItem.weight_volume.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_max.description.toString())); + _results.add(ResultExt(itemString: ResultItem.calorie.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_avg.description.toString())); + _results.add(ResultExt(itemString: ResultItem.fatburn_percent.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_min.description.toString())); } else { //_results.add(ResultExt(itemString: ResultItem.time.description)); - _results.add(ResultExt(itemString: ResultItem.distance.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_max.description)); - _results.add(ResultExt(itemString: ResultItem.calorie.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_avg.description)); - _results.add(ResultExt(itemString: ResultItem.fatburn_percent.description)); - _results.add(ResultExt(itemString: ResultItem.bpm_min.description)); - _results.add(ResultExt(itemString: ResultItem.steps.description)); - _results.add(ResultExt(itemString: ResultItem.speed_max.description)); + _results.add(ResultExt(itemString: ResultItem.distance.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_max.description.toString())); + _results.add(ResultExt(itemString: ResultItem.calorie.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_avg.description.toString())); + _results.add(ResultExt(itemString: ResultItem.fatburn_percent.description.toString())); + _results.add(ResultExt(itemString: ResultItem.bpm_min.description.toString())); + _results.add(ResultExt(itemString: ResultItem.steps.description.toString())); + _results.add(ResultExt(itemString: ResultItem.speed_max.description.toString())); } } List getResults() => this._results; Future saveExerciseResults() async { - if (this._results != null) { - this._results.forEach((result) async { - ExerciseResult exerciseResult = ExerciseResult(); - exerciseResult.customerId = Cache().userLoggedIn.customerId; - exerciseResult.exerciseId = result.exerciseId; - exerciseResult.dateFrom = result.dateFrom; - exerciseResult.dateTo = result.dateTo; - exerciseResult.resultType = result.itemString; - exerciseResult.value = result.data; - //await ExerciseResultApi().saveExerciseResult(exerciseResult); - }); - } + this._results.forEach((result) async { + ExerciseResult exerciseResult = ExerciseResult(); + exerciseResult.customerId = Cache().userLoggedIn!.customerId!; + exerciseResult.exerciseId = result.exerciseId!; + exerciseResult.dateFrom = result.dateFrom!; + exerciseResult.dateTo = result.dateTo; + exerciseResult.resultType = result.itemString; + exerciseResult.value = result.data; + //await ExerciseResultApi().saveExerciseResult(exerciseResult); + }); } } diff --git a/lib/repository/property_repository.dart b/lib/repository/property_repository.dart index 1960c26..2c23594 100644 --- a/lib/repository/property_repository.dart +++ b/lib/repository/property_repository.dart @@ -3,27 +3,29 @@ import 'package:aitrainer_app/model/property.dart'; import 'package:aitrainer_app/service/property_service.dart'; class PropertyRepository { - List _properties; + late List? _properties; - Future> getDBProperties() async { + Future?> getDBProperties() async { this._properties = await PropertyApi().getProperties(); return this._properties; } - List getProperties() { + List? getProperties() { return this._properties; } - Property getPropertyByName(String name) { - Property property; + Property? getPropertyByName(String name) { + Property? property; if (_properties == null) { _properties = Cache().getProperties(); } - this._properties.forEach((element) { - if (name == element.propertyName) { - property = element; - } - }); + if (_properties != null) { + this._properties!.forEach((element) { + if (name == element.propertyName) { + property = element; + } + }); + } return property; } } diff --git a/lib/repository/user_repository.dart b/lib/repository/user_repository.dart index 1b28015..8531450 100644 --- a/lib/repository/user_repository.dart +++ b/lib/repository/user_repository.dart @@ -5,10 +5,9 @@ import 'package:aitrainer_app/service/firebase_api.dart'; import 'package:aitrainer_app/service/logging.dart'; import 'package:aitrainer_app/util/not_found_exception.dart'; import 'package:firebase_auth/firebase_auth.dart' as auth; -import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'; class UserRepository with Logging { - User user; + late User user; UserRepository() { this.createNewUser(); @@ -29,7 +28,7 @@ class UserRepository with Logging { Future addUser() async { final User modelUser = this.user; try { - String rc = await FirebaseApi().registerEmail(modelUser.email, modelUser.password); + String rc = await FirebaseApi().registerEmail(modelUser.email!, modelUser.password!); if (rc == FirebaseApi.SIGN_IN_OK) { modelUser.firebaseUid = Cache().firebaseUid; await CustomerApi().addUser(modelUser); @@ -44,17 +43,14 @@ class UserRepository with Logging { final User modelUser = this.user; try { Map userData = await FirebaseApi().registerWithFacebook(); - if (userData != null) { - modelUser.email = userData['email']; - if (modelUser.email == null) { - throw new Exception("Facebook signup was not successful. Please try another method"); - } - modelUser.password = Cache().firebaseUid; - modelUser.firebaseUid = Cache().firebaseUid; - await CustomerApi().addUser(modelUser); - } else { + + modelUser.email = userData['email']; + if (modelUser.email == null) { throw new Exception("Facebook signup was not successful. Please try another method"); } + modelUser.password = Cache().firebaseUid; + modelUser.firebaseUid = Cache().firebaseUid; + await CustomerApi().addUser(modelUser); } on auth.FirebaseAuthException catch (e) { if (e.code == 'email-already-in-use') { log('The account already exists for that email.'); @@ -84,17 +80,14 @@ class UserRepository with Logging { final User modelUser = this.user; try { Map userData = await FirebaseApi().registerWithGoogle(); - if (userData != null) { - modelUser.email = userData['email']; - if (modelUser.email == null) { - throw new Exception("Google signup was not successful. Please try another method"); - } - modelUser.password = Cache().firebaseUid; - modelUser.firebaseUid = Cache().firebaseUid; - await CustomerApi().addUser(modelUser); - } else { + + modelUser.email = userData['email']; + if (modelUser.email == null) { throw new Exception("Google signup was not successful. Please try another method"); } + modelUser.password = Cache().firebaseUid; + modelUser.firebaseUid = Cache().firebaseUid; + await CustomerApi().addUser(modelUser); } on auth.FirebaseAuthException catch (e) { if (e.code == 'email-already-in-use') { log('The account already exists for that email.'); @@ -117,17 +110,14 @@ class UserRepository with Logging { final User modelUser = this.user; try { Map userData = await FirebaseApi().registerWithApple(); - if (userData != null) { - modelUser.email = userData['email']; - if (modelUser.email == null) { - throw new Exception("Apple signup was not successful. Please try another method"); - } - modelUser.password = Cache().firebaseUid; - modelUser.firebaseUid = Cache().firebaseUid; - await CustomerApi().addUser(modelUser); - } else { + + modelUser.email = userData['email']; + if (modelUser.email == null) { throw new Exception("Apple signup was not successful. Please try another method"); } + modelUser.password = Cache().firebaseUid; + modelUser.firebaseUid = Cache().firebaseUid; + await CustomerApi().addUser(modelUser); } on auth.FirebaseAuthException catch (e) { if (e.code == 'email-already-in-use') { log('The account already exists for that email.'); @@ -148,14 +138,11 @@ class UserRepository with Logging { final User modelUser = this.user; try { Map userData = await FirebaseApi().signInWithFacebook(); - if (userData == null) { - throw new Exception("Facebook login was not successful"); - } modelUser.email = userData['email']; - await CustomerApi().getUserByEmail(modelUser.email); + await CustomerApi().getUserByEmail(modelUser.email!); await Cache().afterFirebaseLogin(); - } on FacebookAuthException catch (e) { + } /* on FacebookAuthException catch (e) { switch (e.errorCode) { case FacebookAuthErrorCode.OPERATION_IN_PROGRESS: throw Exception("You have a previous Facebook login operation in progress"); @@ -167,7 +154,8 @@ class UserRepository with Logging { throw Exception("Facebook login failed"); break; } - } on NotFoundException catch (ex) { + } */ + on NotFoundException catch (ex) { log("FB exception: " + ex.toString()); throw Exception("Customer does not exist or the password is wrong"); } on Exception catch (e) { @@ -180,12 +168,12 @@ class UserRepository with Logging { final User modelUser = this.user; try { Map userData = await FirebaseApi().signInWithGoogle(); - if (userData == null || userData['email'] == null) { + if (userData['email'] == null) { throw new Exception("Google login was not successful"); } modelUser.email = userData['email']; - await CustomerApi().getUserByEmail(modelUser.email); + await CustomerApi().getUserByEmail(modelUser.email!); await Cache().afterFirebaseLogin(); } on Exception catch (ex) { log("Google exception: " + ex.toString()); @@ -196,12 +184,12 @@ class UserRepository with Logging { Future getUserByApple() async { final User modelUser = this.user; Map userData = await FirebaseApi().signInWithApple(); - if (userData == null || userData['email'] == null) { + if (userData['email'] == null) { throw new Exception("Apple login was not successful"); } modelUser.email = userData['email']; try { - await CustomerApi().getUserByEmail(modelUser.email); + await CustomerApi().getUserByEmail(modelUser.email!); await Cache().afterFirebaseLogin(); } on Exception catch (ex) { log("Apple exception: " + ex.toString()); @@ -214,7 +202,7 @@ class UserRepository with Logging { String rc = await FirebaseApi().signInEmail(modelUser.email, modelUser.password); if (rc == FirebaseApi.SIGN_IN_OK) { - await CustomerApi().getUserByEmail(modelUser.email); + await CustomerApi().getUserByEmail(modelUser.email!); await Cache().afterFirebaseLogin(); } else { log("Exception: user not found or password is wrong"); @@ -224,6 +212,6 @@ class UserRepository with Logging { Future resetPassword() async { final User modelUser = this.user; - await FirebaseApi().resetPassword(modelUser.email); + await FirebaseApi().resetPassword(modelUser.email!); } } diff --git a/lib/repository/workout_tree_repository.dart b/lib/repository/workout_tree_repository.dart index e90830f..a7cbab5 100644 --- a/lib/repository/workout_tree_repository.dart +++ b/lib/repository/workout_tree_repository.dart @@ -6,8 +6,6 @@ import 'package:aitrainer_app/model/exercise_tree.dart'; import 'package:aitrainer_app/model/exercise_type.dart'; import 'package:aitrainer_app/model/workout_menu_tree.dart'; import 'package:aitrainer_app/repository/exercise_repository.dart'; -import 'package:aitrainer_app/service/exercise_tree_service.dart'; -import 'package:aitrainer_app/service/exercise_type_service.dart'; import 'package:aitrainer_app/service/logging.dart'; import 'package:flutter/material.dart'; @@ -20,29 +18,29 @@ extension AntagonistExt on Antagonist { } class WorkoutTreeRepository with Logging { - final LinkedHashMap tree = LinkedHashMap(); + final LinkedHashMap tree = LinkedHashMap(); SplayTreeMap sortedTree = SplayTreeMap>(); - bool isEnglish; - WorkoutType workoutType; - final List menuAsExercise = List(); + bool? isEnglish; + WorkoutType? workoutType; + final List menuAsExercise = []; void createTree() { //if (Cache().getExerciseTree().length > 0 || Cache().getWorkoutMenuTree().length > 0) return; isEnglish = AppLanguage().appLocal == Locale('en'); - log("** Start creating tree on lang: " + - AppLanguage().appLocal.languageCode + - " tree length: " + - Cache().getExerciseTree().length.toString()); + List? exerciseTree = Cache().getExerciseTree(); + List? exerciseTypes = Cache().getExerciseTypes(); + if (exerciseTree == null || exerciseTypes == null) { + return; + } - List exerciseTree = Cache().getExerciseTree(); - List exerciseTypes = Cache().getExerciseTypes(); + log("** Start creating tree on lang: ${AppLanguage().appLocal.languageCode}"); - exerciseTree.sort((a, b) => a.sort.compareTo(b.sort)); + exerciseTree.sort((a, b) => a.sort!.compareTo(b.sort!)); exerciseTree.forEach((treeItem) async { //log(" -- TreeItem " + treeItem.toJson().toString() + " active " + treeItem.active.toString()); if (treeItem.active == true) { - String treeName = isEnglish ? treeItem.name : treeItem.nameTranslation; + String treeName = isEnglish! ? treeItem.name : treeItem.nameTranslation; bool is1RM = treeItem.name.contains("Muscle") || treeItem.name.contains("Shape") || treeItem.name.contains("Strength") ? true : false; @@ -54,7 +52,7 @@ class WorkoutTreeRepository with Logging { if (isRunning == false && treeItem.parentId != 0) { isRunning = isParentRunning(treeItem.parentId); } - WorkoutMenuTree parent = getParentItem(treeItem.parentId); + WorkoutMenuTree? parent = getParentItem(treeItem.parentId); WorkoutMenuTree menuItem = WorkoutMenuTree( treeItem.treeId, treeItem.parentId, @@ -71,7 +69,7 @@ class WorkoutTreeRepository with Logging { treeItem.name, parent != null ? parent.name : "", parent != null ? parent.nameEnglish : "", - treeItem.sort); + treeItem.sort!); menuItem = this.setWorkoutTypes(menuItem, treeItem); this.tree[treeItem.name + "_" + treeItem.parentId.toString()] = menuItem; //log("WorkoutMenuTree item ${menuItem.toJson()}"); @@ -81,7 +79,7 @@ class WorkoutTreeRepository with Logging { exerciseTypes.forEach((exerciseType) async { if (!(exerciseType.imageUrl.isEmpty || exerciseType.name.isEmpty || exerciseType.nameTranslation.isEmpty) && exerciseType.active == true) { - String exerciseTypeName = isEnglish ? exerciseType.name : exerciseType.nameTranslation; + String exerciseTypeName = isEnglish! ? exerciseType.name : exerciseType.nameTranslation; //String assetImage = await _buildImage(exerciseType.imageUrl); //'asset/menu/' + exerciseType.imageUrl.substring(7); if (exerciseType.parents.isNotEmpty) { @@ -95,7 +93,7 @@ class WorkoutTreeRepository with Logging { is1RM = false; exerciseType.setAbility(ExerciseAbility.running); } - WorkoutMenuTree parent = getParentItem(parentId); + WorkoutMenuTree? parent = getParentItem(parentId); WorkoutMenuTree menuItem = WorkoutMenuTree( exerciseType.exerciseTypeId, parentId, @@ -154,7 +152,7 @@ class WorkoutTreeRepository with Logging { bool isTreeItemRunning = false; this.tree.forEach((key, value) { - WorkoutMenuTree treeItem = value as WorkoutMenuTree; + WorkoutMenuTree treeItem = value; if (treeItem.id == treeId) { isTreeItemRunning = isTreeItemRunning || treeItem.isRunning; //log (treeItem.name + " 1RM " + treeItem.is1RM.toString() ); @@ -168,7 +166,7 @@ class WorkoutTreeRepository with Logging { bool isTreeItem1RM = false; this.tree.forEach((key, value) { - WorkoutMenuTree treeItem = value as WorkoutMenuTree; + WorkoutMenuTree treeItem = value; if (treeItem.id == treeId) { isTreeItem1RM = isTreeItem1RM || treeItem.is1RM; //log(treeItem.name + " 1RM " + treeItem.is1RM.toString()); @@ -204,7 +202,7 @@ class WorkoutTreeRepository with Logging { LinkedHashMap getBranch(int parent, {bool filtering = false}) { LinkedHashMap branch = LinkedHashMap(); tree.forEach((key, value) { - WorkoutMenuTree workoutTree = value as WorkoutMenuTree; + WorkoutMenuTree workoutTree = value; if (parent == workoutTree.parent) { branch[key] = value; } @@ -213,9 +211,9 @@ class WorkoutTreeRepository with Logging { } List getBranchList(int parent) { - List branch = List(); + List branch = []; tree.forEach((key, value) { - WorkoutMenuTree workoutTree = value as WorkoutMenuTree; + WorkoutMenuTree workoutTree = value; if (parent == workoutTree.parent) { branch.add(workoutTree); } @@ -223,10 +221,10 @@ class WorkoutTreeRepository with Logging { return branch; } - WorkoutMenuTree getParentItem(int parent) { - WorkoutMenuTree parentItem; + WorkoutMenuTree? getParentItem(int parent) { + WorkoutMenuTree? parentItem; tree.forEach((key, value) { - WorkoutMenuTree workoutTree = value as WorkoutMenuTree; + WorkoutMenuTree workoutTree = value; if (parent == workoutTree.id) { parentItem = workoutTree; } @@ -234,8 +232,8 @@ class WorkoutTreeRepository with Logging { return parentItem; } - WorkoutMenuTree getMenuItemByExerciseTypeId(int exerciseTypeId) { - WorkoutMenuTree menuItem; + WorkoutMenuTree? getMenuItemByExerciseTypeId(int exerciseTypeId) { + WorkoutMenuTree? menuItem; this.menuAsExercise.forEach((element) { if (element.exerciseTypeId == exerciseTypeId) { menuItem = element; @@ -244,41 +242,43 @@ class WorkoutTreeRepository with Logging { return menuItem; } - List getWorkoutTreeAlternatives(WorkoutMenuTree workoutMenuTree) { + List? getWorkoutTreeAlternatives(WorkoutMenuTree? workoutMenuTree) { if (workoutMenuTree == null) { return null; } - if (workoutMenuTree.exerciseType == null) { - return null; - } - final List alternatives = this.getExerciseTypeAlternatives(workoutMenuTree.exerciseTypeId); + final List? alternatives = this.getExerciseTypeAlternatives(workoutMenuTree.exerciseTypeId); if (alternatives == null) { return null; } - List list = List(); + List list = []; alternatives.forEach((element) { - final WorkoutMenuTree alternativeMenuItem = this.getMenuItemByExerciseTypeId(element.exerciseTypeId); - list.add(alternativeMenuItem); + final WorkoutMenuTree? alternativeMenuItem = this.getMenuItemByExerciseTypeId(element.exerciseTypeId); + if (alternativeMenuItem != null) { + list.add(alternativeMenuItem); + } }); return list; } - List getExerciseTypeAlternatives(int exerciseTypeId) { + List getExerciseTypeAlternatives(int? exerciseTypeId) { if (exerciseTypeId == null || exerciseTypeId <= 0) { - return null; + return []; + } + List list = []; + List? exerciseTypes = Cache().getExerciseTypes(); + if (exerciseTypes != null) { + exerciseTypes.forEach((exerciseType) { + if (exerciseType.alternatives.isNotEmpty) { + exerciseType.alternatives.forEach((childId) { + if (childId == exerciseTypeId) { + list.add(exerciseType); + } + }); + } + }); } - List list = List(); - Cache().getExerciseTypes().forEach((exerciseType) { - if (exerciseType.alternatives.isNotEmpty) { - exerciseType.alternatives.forEach((childId) { - if (childId == exerciseTypeId) { - list.add(exerciseType); - } - }); - } - }); return list; } @@ -296,7 +296,7 @@ class WorkoutTreeRepository with Logging { void sortByMuscleType() { sortedTree = SplayTreeMap>(); tree.forEach((key, value) { - WorkoutMenuTree workoutTree = value as WorkoutMenuTree; + WorkoutMenuTree workoutTree = value; if (!workoutTree.nameEnglish.contains('Muscle Build') && !workoutTree.nameEnglish.contains('Strength') && workoutTree.is1RM && @@ -313,7 +313,7 @@ class WorkoutTreeRepository with Logging { int getMissingTreeIdByName(String name) { int missingId = 0; tree.forEach((key, value) { - WorkoutMenuTree item = value as WorkoutMenuTree; + WorkoutMenuTree item = value; if (item.name == name || name == item.nameEnglish) { missingId = item.id; } diff --git a/lib/service/api.dart b/lib/service/api.dart index 79f3433..d94b765 100644 --- a/lib/service/api.dart +++ b/lib/service/api.dart @@ -15,7 +15,8 @@ class APIClient with Common, Logging { authToken = responseJson['token']; Cache().authToken = authToken; } - final response = await http.get(url, headers: {'Content-Type': 'application/json', 'Authorization': "Bearer " + authToken}); + var uri = Uri.parse(url); + final response = await http.get(uri, headers: {'Content-Type': 'application/json', 'Authorization': "Bearer " + authToken}); trace(" ------------get response code: " + response.statusCode.toString()); if (response.statusCode == 200) { return utf8.decode(response.bodyBytes); @@ -34,9 +35,9 @@ class APIClient with Common, Logging { var responseJson = await this.authenticateUser(Cache.username, Cache.password); authToken = responseJson['token']; } - + var uri = Uri.parse(url); final response = await http.post( - url, + uri, headers: {'Content-Type': 'application/json; charset=UTF-8', 'Authorization': "Bearer " + authToken}, body: body, ); @@ -47,11 +48,12 @@ class APIClient with Common, Logging { } dynamic authenticateUser(String email, String password) async { - var uri = Cache.getBaseUrl() + "authenticate"; + var url = Cache.getBaseUrl() + "authenticate"; try { final body = '{"username":"$email", "password":"$password"}'; trace("authentication with $email"); + var uri = Uri.parse(url); final response = await http.post(uri, headers: {'Authorization': '1', 'Content-Type': 'application/json'}, body: body); final responseCode = response.statusCode; if (responseCode != 200) { @@ -67,10 +69,11 @@ class APIClient with Common, Logging { } } - Future fetch(var authToken, var endPoint) async { - var uri = Cache.getBaseUrl() + endPoint; + Future fetch(var authToken, var endPoint) async { + var url = Cache.getBaseUrl() + endPoint; try { + var uri = Uri.parse(url); final response = await http.get( uri, headers: {'Authorization': authToken}, @@ -79,7 +82,7 @@ class APIClient with Common, Logging { final responseJson = json.decode(response.body); return responseJson; } catch (exception) { - log(exception); + log(exception.toString()); if (exception.toString().contains('SocketException')) { return 'NetworkError'; } else { diff --git a/lib/service/customer_exercise_device_service.dart b/lib/service/customer_exercise_device_service.dart index 8e9f61b..14327d2 100644 --- a/lib/service/customer_exercise_device_service.dart +++ b/lib/service/customer_exercise_device_service.dart @@ -9,7 +9,7 @@ class CustomerExerciseDeviceApi with Logging { final APIClient _client = new APIClient(); Future> getDevices(int customerId) async { - List devices; + List devices = []; try { log(" --- get customer_exercise_devices: "); final body = await _client.get("customer_exercise_device/customer/" + customerId.toString(), ""); @@ -17,6 +17,7 @@ class CustomerExerciseDeviceApi with Logging { devices = json.map((device) => CustomerExerciseDevice.fromJson(device)).toList(); } on NotFoundException catch (_) { log("No devices found"); + devices = []; } return devices; } diff --git a/lib/service/customer_service.dart b/lib/service/customer_service.dart index 9bc13b4..cd69cad 100644 --- a/lib/service/customer_service.dart +++ b/lib/service/customer_service.dart @@ -46,7 +46,7 @@ class CustomerApi with Logging { final String responseBody = await _client.post("registration", body); Customer customer; try { - int status = jsonDecode(responseBody)['status']; + int? status = jsonDecode(responseBody)['status']; if (status != null) { String error = jsonDecode(responseBody)['error']; throw new Exception(error); @@ -82,10 +82,10 @@ class CustomerApi with Logging { try { customer = Customer.fromJson(jsonDecode(responseBody)); if (customer.firebaseUid == null) { - await this.updateFirebaseUid(customer.customerId, Cache().firebaseUid); + await this.updateFirebaseUid(customer.customerId!, Cache().firebaseUid!); } Cache().userLoggedIn = customer; - final List properties = await this.getActualProperties(customer.customerId); + final List? properties = await this.getActualProperties(customer.customerId!); if (properties != null) { this.initProperties(properties); } @@ -102,7 +102,7 @@ class CustomerApi with Logging { Customer customer = Customer.fromJson(jsonDecode(responseBody)); log(" --- Customer: " + customer.toJson().toString()); Cache().userLoggedIn = customer; - final List properties = await this.getActualProperties(customerId); + final List? properties = await this.getActualProperties(customerId); //log(" ---- Props: " + properties.toJson().toString()); //await Cache().initCustomer(customerId); if (properties != null) { @@ -116,25 +116,27 @@ class CustomerApi with Logging { } } - void initProperties(final List customerProperties) { - List properties = Cache().getProperties(); - Customer customer = Cache().userLoggedIn; + void initProperties(final List? customerProperties) { + List? properties = Cache().getProperties(); + Customer customer = Cache().userLoggedIn!; customer.properties = LinkedHashMap(); - // reset Properties - properties.forEach((property) { - CustomerProperty customerProperty = - CustomerProperty(propertyId: property.propertyId, customerId: customer.customerId, dateAdd: null, propertyValue: 0); - customer.properties[property.propertyName] = customerProperty; - }); - - customerProperties.forEach((customerProperty) { + if (properties != null) { + // reset Properties properties.forEach((property) { - if (customerProperty.propertyId == property.propertyId) { - customer.properties[property.propertyName] = customerProperty; - } + CustomerProperty customerProperty = + CustomerProperty(propertyId: property.propertyId, customerId: customer.customerId!, dateAdd: DateTime.now(), propertyValue: 0); + customer.properties[property.propertyName] = customerProperty; }); - }); + + customerProperties!.forEach((customerProperty) { + properties.forEach((property) { + if (customerProperty.propertyId == property.propertyId) { + customer.properties[property.propertyName] = customerProperty; + } + }); + }); + } } Future getTrainee(int customerId) async { @@ -153,7 +155,7 @@ class CustomerApi with Logging { } Future> getTrainees(int trainerId) async { - List trainees = List(); + List trainees = []; log("Get trainees list"); try { String body = ""; @@ -175,18 +177,12 @@ class CustomerApi with Logging { return properties; } - Future> getActualProperties(int customerId) async { - List properties; + Future?> getActualProperties(int customerId) async { + List? properties; try { final body = await _client.get("customer_property/last/", customerId.toString()); final Iterable json = jsonDecode(body); properties = json.map((property) => CustomerProperty.fromJson(property)).toList(); - - if (properties != null) { - properties.forEach((element) { - //log("Property " + element.toString()); - }); - } } on Exception catch (ex) { log(ex.toString()); } @@ -197,18 +193,15 @@ class CustomerApi with Logging { String body = JsonEncoder().convert(property.toJson()); log(" ===== add new customer property: " + body); CustomerProperty customerProperty; - String responseBody; + String? responseBody; try { responseBody = await _client.post("customer_property", body); log(" responseBody: " + responseBody); - int status = jsonDecode(responseBody)['status']; + int? status = jsonDecode(responseBody)['status']; if (status != null) { throw new Exception(jsonDecode(responseBody)['error']); } else { customerProperty = CustomerProperty.fromJson(jsonDecode(responseBody)); - if (customerProperty == null) { - throw new Exception("Property Insert was not successful"); - } } } on FormatException { throw new Exception(responseBody); @@ -220,20 +213,17 @@ class CustomerApi with Logging { Future updateProperty(CustomerProperty property) async { String body = JsonEncoder().convert(property.toJson()); - CustomerProperty customerProperty; + CustomerProperty? customerProperty; log(" ===== update customer property: " + body); - String responseBody; + String? responseBody; try { responseBody = await _client.post("customer_property/update/" + property.customerPropertyId.toString(), body); log(" responseBody: " + responseBody); - int status = jsonDecode(responseBody)['status']; + int? status = jsonDecode(responseBody)['status']; if (status != null) { throw new Exception(jsonDecode(responseBody)['error']); } else { customerProperty = CustomerProperty.fromJson(jsonDecode(responseBody)); - if (customerProperty == null) { - throw new Exception("Property Update was not successful"); - } } } on FormatException { throw new Exception(responseBody); diff --git a/lib/service/exercise_plan_service.dart b/lib/service/exercise_plan_service.dart index 4d891b7..7b9d678 100644 --- a/lib/service/exercise_plan_service.dart +++ b/lib/service/exercise_plan_service.dart @@ -83,10 +83,10 @@ class ExercisePlanApi with Logging { return; } - Future getLastExercisePlan(int customerId) async { + Future getLastExercisePlan(int customerId) async { String body = ""; log(" ===== get last exercisePlan $customerId"); - ExercisePlan exercisePlan; + ExercisePlan? exercisePlan; try { final String responseBody = await _client.get("exercise_plan/last/" + customerId.toString(), body); exercisePlan = ExercisePlan.fromJson(jsonDecode(responseBody)); diff --git a/lib/service/exercise_service.dart b/lib/service/exercise_service.dart index 2a50c6b..28542c7 100644 --- a/lib/service/exercise_service.dart +++ b/lib/service/exercise_service.dart @@ -33,7 +33,7 @@ class ExerciseApi with Logging { } Future deleteExercise(Exercise exercise) async { - int exerciseId = exercise.exerciseId; + int exerciseId = exercise.exerciseId!; log(" ===== delete exercise: " + exerciseId.toString()); await _client.post("exercises/" + exerciseId.toString(), ""); return; diff --git a/lib/service/exercise_tree_service.dart b/lib/service/exercise_tree_service.dart index 6d1b69f..406e35a 100644 --- a/lib/service/exercise_tree_service.dart +++ b/lib/service/exercise_tree_service.dart @@ -13,18 +13,17 @@ class ExerciseTreeApi with Logging { Future> getExerciseTree() async { final String body = await _client.get("exercise_tree", ""); Iterable json = jsonDecode(body); - List exerciseTree = json.map((exerciseTree) => ExerciseTree.fromJson(exerciseTree)).toList(); + List? exerciseTree = json.map((exerciseTree) => ExerciseTree.fromJson(exerciseTree)).toList(); exerciseTree = await getExerciseTreeParents(exerciseTree); - if (exerciseTree != null) { - await Future.forEach(exerciseTree, (element) async { - element.imageUrl = await buildImage(element.imageUrl, element.treeId); - }); - exerciseTree = await getExerciseTreeParents(exerciseTree); - log("ExerciseTree downloaded"); - Cache().setExerciseTree(exerciseTree); - } + await Future.forEach(exerciseTree, (element) async { + ExerciseTree exerciseTree = element as ExerciseTree; + exerciseTree.imageUrl = await buildImage(exerciseTree.imageUrl, exerciseTree.treeId); + }); + exerciseTree = await getExerciseTreeParents(exerciseTree); + log("ExerciseTree downloaded"); + Cache().setExerciseTree(exerciseTree); return exerciseTree; } @@ -55,11 +54,11 @@ class ExerciseTreeApi with Logging { if (parent.exerciseTreeChildId == element.treeId) { if (index > 0) { ExerciseTree newElement = element.copy(parent.exerciseTreeParentId); - newElement.sort = parent.sort ?? 0; + newElement.sort = parent.sort; exerciseTree.add(newElement); } else { element.parentId = parent.exerciseTreeParentId; - element.sort = parent.sort ?? 0; + element.sort = parent.sort; exerciseTree[treeIndex].parentId = parent.exerciseTreeParentId; } index++; @@ -71,7 +70,7 @@ class ExerciseTreeApi with Logging { } List copyList(List tree) { - final List copyList = List(); + final List copyList = []; tree.forEach((element) { final ExerciseTree copy = element.copy(-1); copyList.add(copy); diff --git a/lib/service/exercise_type_service.dart b/lib/service/exercise_type_service.dart index 7bac308..2688516 100644 --- a/lib/service/exercise_type_service.dart +++ b/lib/service/exercise_type_service.dart @@ -12,13 +12,13 @@ class ExerciseTypeApi with Logging { final body = await _client.get("exercise_type", ""); final Iterable json = jsonDecode(body); final List exerciseTypes = json.map((exerciseType) => ExerciseType.fromJson(exerciseType)).toList(); - if (exerciseTypes != null) { - await Future.forEach(exerciseTypes, (element) async { - element.imageUrl = await buildImage(element.imageUrl, element.exerciseTypeId); - }); - log("ExerciseTypes downloaded"); - Cache().setExerciseTypes(exerciseTypes); - } + + await Future.forEach(exerciseTypes, (element) async { + ExerciseType exerciseType = element as ExerciseType; + exerciseType.imageUrl = await buildImage(exerciseType.imageUrl, exerciseType.exerciseTypeId); + }); + log("ExerciseTypes downloaded"); + Cache().setExerciseTypes(exerciseTypes); return exerciseTypes; } diff --git a/lib/service/firebase_api.dart b/lib/service/firebase_api.dart index 53b6243..3e3e225 100644 --- a/lib/service/firebase_api.dart +++ b/lib/service/firebase_api.dart @@ -8,7 +8,7 @@ import 'package:google_sign_in/google_sign_in.dart'; class FirebaseApi with logging.Logging { bool appleSignInAvailable = false; - static FirebaseApi _instance; + //late FirebaseApi _instance; static final FirebaseAuth auth = FirebaseAuth.instance; @@ -18,13 +18,11 @@ class FirebaseApi with logging.Logging { static const String REGISTER_WEAK_PWD = "weak-password"; static const String REGISTER_EMAIL_IN_USE = "email-already-in-use"; - UserCredential userCredential; + late UserCredential userCredential; - factory FirebaseApi() => _instance ?? FirebaseApi._internal(); + factory FirebaseApi() => FirebaseApi._internal(); - FirebaseApi._internal() { - _instance = this; - } + FirebaseApi._internal(); // Define an async function to initialize FlutterFire Future initializeFlutterFire() async { @@ -38,7 +36,7 @@ class FirebaseApi with logging.Logging { } } - Future signInEmail(String email, String password) async { + Future signInEmail(String? email, String? password) async { if (email == null) { throw Exception("Please type an email address"); } @@ -48,7 +46,7 @@ class FirebaseApi with logging.Logging { String rc = SIGN_IN_OK; try { userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password); - Cache().firebaseUid = userCredential.user.uid; + Cache().firebaseUid = userCredential.user!.uid; } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { log('No user found for that email.'); @@ -67,7 +65,7 @@ class FirebaseApi with logging.Logging { String rc = SIGN_IN_OK; try { userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password); - Cache().firebaseUid = userCredential.user.uid; + Cache().firebaseUid = userCredential.user!.uid; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { log('The password provided is too weak.'); @@ -79,7 +77,7 @@ class FirebaseApi with logging.Logging { throw Exception("The email address has been registered already"); } } catch (e) { - log(e); + log(e.toString()); throw Exception(e.toString()); } return rc; @@ -98,11 +96,9 @@ class FirebaseApi with logging.Logging { case AuthorizationStatus.error: print('User error'); throw Exception("Apple Sign-In failed"); - break; case AuthorizationStatus.cancelled: print('User cancelled'); throw Exception("Apple Sign-In cancelled"); - break; } // Create an `OAuthCredential` from the credential returned by Apple. @@ -121,8 +117,8 @@ class FirebaseApi with logging.Logging { " state " + result.credential.state.toString() + " email " + - userCredential.user.email); - userData['email'] = userCredential.user.email; + userCredential.user!.email!); + userData['email'] = userCredential.user!.email; return userData; } @@ -139,11 +135,9 @@ class FirebaseApi with logging.Logging { case AuthorizationStatus.error: print('Apple User error'); throw Exception("Apple Sign-In failed"); - break; case AuthorizationStatus.cancelled: print('User cancelled'); throw Exception("Apple Sign-In cancelled"); - break; } // Create an `OAuthCredential` from the credential returned by Apple. @@ -155,9 +149,9 @@ class FirebaseApi with logging.Logging { // not match the nonce in `appleCredential.identityToken`, sign in will fail. UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(oauthCredential); - Cache().firebaseUid = userCredential.user.uid; + Cache().firebaseUid = userCredential.user!.uid; - userData['email'] = userCredential.user.email; + userData['email'] = userCredential.user!.email; return userData; } @@ -172,7 +166,7 @@ class FirebaseApi with logging.Logging { 'https://www.googleapis.com/auth/contacts.readonly', ], ); - final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); + final GoogleSignInAccount? googleUser = await _googleSignIn.signIn(); if (googleUser == null) { throw Exception("Google Sign In failed"); @@ -182,19 +176,17 @@ class FirebaseApi with logging.Logging { final GoogleSignInAuthentication googleAuth = await googleUser.authentication; // Create a new credential - final GoogleAuthCredential credential = GoogleAuthProvider.credential( + final OAuthCredential credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); await FirebaseAuth.instance.signInWithCredential(credential); - if (googleUser != null) { - log("GoogleUser: " + googleUser.toString()); - userData['email'] = googleUser.email; - userData['id'] = googleUser.id; - userData['name'] = googleUser.displayName; - } + log("GoogleUser: " + googleUser.toString()); + userData['email'] = googleUser.email; + userData['id'] = googleUser.id; + userData['name'] = googleUser.displayName; return userData; } @@ -209,7 +201,7 @@ class FirebaseApi with logging.Logging { 'https://www.googleapis.com/auth/contacts.readonly', ], ); - final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); + final GoogleSignInAccount? googleUser = await _googleSignIn.signIn(); if (googleUser == null) { throw Exception("Google Sign In failed"); @@ -219,7 +211,7 @@ class FirebaseApi with logging.Logging { final GoogleSignInAuthentication googleAuth = await googleUser.authentication; // Create a new credential - final GoogleAuthCredential credential = GoogleAuthProvider.credential( + final OAuthCredential credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); @@ -227,7 +219,7 @@ class FirebaseApi with logging.Logging { final userCredential = await FirebaseAuth.instance.signInWithCredential(credential); log("Google credentials: " + credential.toString() + " GoogleUser: " + googleUser.toString()); - Cache().firebaseUid = userCredential.user.uid; + Cache().firebaseUid = userCredential.user!.uid; userData['email'] = googleUser.email; @@ -238,7 +230,7 @@ class FirebaseApi with logging.Logging { Map userData; // by default the login method has the next permissions ['email','public_profile'] - AccessToken accessToken = await FacebookAuth.instance.login(); + AccessToken? accessToken = await FacebookAuth.instance.accessToken; if (accessToken != null) { log(accessToken.toJson().toString()); Cache().accessTokenFacebook = accessToken; @@ -257,7 +249,7 @@ class FirebaseApi with logging.Logging { Map userData; // by default the login method has the next permissions ['email','public_profile'] - AccessToken accessToken = await FacebookAuth.instance.login(); + AccessToken? accessToken = await FacebookAuth.instance.accessToken; if (accessToken != null) { Cache().accessTokenFacebook = accessToken; // get the user data @@ -265,13 +257,13 @@ class FirebaseApi with logging.Logging { log("FB user data: " + userData.toString()); // Create a credential from the access token - final FacebookAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(accessToken.token); + final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(accessToken.token); // Once signed in, return the UserCredential final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential); log("Email by FB: " + userData['email'] + " FB credential: " + userCredential.toString()); - Cache().firebaseUid = userCredential.user.uid; + Cache().firebaseUid = userCredential.user!.uid; } else { throw Exception("Facebook login was not successful"); } diff --git a/lib/service/package_service.dart b/lib/service/package_service.dart index d2cd43e..3864fb8 100644 --- a/lib/service/package_service.dart +++ b/lib/service/package_service.dart @@ -7,7 +7,6 @@ import 'package:aitrainer_app/model/customer_property.dart'; import 'package:aitrainer_app/model/exercise.dart'; import 'package:aitrainer_app/model/exercise_device.dart'; import 'package:aitrainer_app/model/exercise_plan_template.dart'; -import 'package:aitrainer_app/model/exercise_result.dart'; import 'package:aitrainer_app/model/exercise_tree.dart'; import 'package:aitrainer_app/model/exercise_tree_parents.dart'; import 'package:aitrainer_app/model/exercise_type.dart'; @@ -26,12 +25,13 @@ class PackageApi { final APIClient _client = new APIClient(); Future getPackage() async { - List exerciseTree; - List exerciseTreeParents; + late List exerciseTree; + late List exerciseTreeParents; final body = await _client.get("app_package/", ""); final List models = body.split("|||"); - await Future.forEach(models, (element) async { + await Future.forEach(models, (elem) async { + final String element = elem as String; final List headRecord = element.split("***"); final Iterable json = jsonDecode(headRecord[1]); if (headRecord[0] == "ExerciseDevice") { @@ -47,12 +47,11 @@ class PackageApi { exerciseTree = json.map((exerciseTree) => ExerciseTree.fromJson(exerciseTree)).toList(); } else if (headRecord[0] == "ExerciseType") { final List exerciseTypes = json.map((exerciseType) => ExerciseType.fromJson(exerciseType)).toList(); - if (exerciseTypes != null) { - await Future.forEach(exerciseTypes, (element) async { - element.imageUrl = await ExerciseTypeApi().buildImage(element.imageUrl, element.exerciseTypeId); - }); - Cache().setExerciseTypes(exerciseTypes); - } + await Future.forEach(exerciseTypes, (elem) async { + final ExerciseType exerciseType = elem as ExerciseType; + exerciseType.imageUrl = await ExerciseTypeApi().buildImage(exerciseType.imageUrl, exerciseType.exerciseTypeId); + }); + Cache().setExerciseTypes(exerciseTypes); } else if (headRecord[0] == "ExerciseAbility") { } else if (headRecord[0] == "ExercisePlanTemplate") { final List exercisePlanTemplates = @@ -64,12 +63,12 @@ class PackageApi { }); exerciseTree = this.getExerciseTreeParents(exerciseTree, exerciseTreeParents); - if (exerciseTree != null) { - await Future.forEach(exerciseTree, (element) async { - element.imageUrl = await ExerciseTreeApi().buildImage(element.imageUrl, element.treeId); - }); - Cache().setExerciseTree(exerciseTree); - } + + await Future.forEach(exerciseTree, (element) async { + ExerciseTree tree = element as ExerciseTree; + tree.imageUrl = await ExerciseTreeApi().buildImage(tree.imageUrl, tree.treeId); + }); + Cache().setExerciseTree(exerciseTree); return; } @@ -107,7 +106,8 @@ class PackageApi { final body = await _client.get("app_customer_package/" + customerId.toString(), ""); final List models = body.split("|||"); - await Future.forEach(models, (element) async { + await Future.forEach(models, (elem) async { + final String element = elem as String; final List headRecord = element.split("***"); //print("Class " + headRecord[0]); if (headRecord[0] == "Customer") { @@ -135,12 +135,12 @@ class PackageApi { final List customerProperties = json.map((property) => CustomerProperty.fromJson(property)).toList(); CustomerApi().initProperties(customerProperties); } else if (headRecord[0] == "ExerciseResult") { - final Iterable json = jsonDecode(headRecord[1]); - final List exerciseResults = json.map((exerciseResult) { + /*final Iterable json = jsonDecode(headRecord[1]); + final List exerciseResults = json.map((exerciseResult) { ExerciseResult item = ExerciseResult.fromJson(exerciseResult); return item; }).toList(); - // ToDo + // ToDo */ } }); } on NotFoundException catch (_) { diff --git a/lib/service/purchase_service.dart b/lib/service/purchase_service.dart index ecb1953..f93980b 100644 --- a/lib/service/purchase_service.dart +++ b/lib/service/purchase_service.dart @@ -9,7 +9,7 @@ class PurchaseApi with Logging { final APIClient _client = new APIClient(); Future> getPurchasesByCustomer(int customerId) async { - List purchases = List(); + List purchases = []; try { final body = await _client.get("purchase/customer/" + customerId.toString(), ""); final Iterable json = jsonDecode(body); diff --git a/lib/util/app_language.dart b/lib/util/app_language.dart index 5ede331..e9eb159 100644 --- a/lib/util/app_language.dart +++ b/lib/util/app_language.dart @@ -7,7 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart'; class AppLanguage with Logging { static final AppLanguage _singleton = AppLanguage._internal(); - Locale _appLocale = Locale('en'); + Locale? _appLocale = Locale('en'); factory AppLanguage() { return _singleton; @@ -23,7 +23,7 @@ class AppLanguage with Logging { Future fetchLocale() async { var prefs = await SharedPreferences.getInstance(); - String langCode = prefs.getString('language_code'); + String? langCode = prefs.getString('language_code'); log(" ---- lang code $langCode"); if (langCode == null) { _appLocale = Locale('en'); @@ -34,7 +34,7 @@ class AppLanguage with Logging { } getLocale(SharedPreferences prefs) { - String langCode = prefs.getString('language_code'); + String? langCode = prefs.getString('language_code'); if (langCode == null) { final String localName = Platform.localeName; if (localName.endsWith("HU")) { diff --git a/lib/util/app_localization.dart b/lib/util/app_localization.dart index 8cd5866..8e2486d 100644 --- a/lib/util/app_localization.dart +++ b/lib/util/app_localization.dart @@ -6,22 +6,21 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; class AppLocalizations with Logging { - Locale locale; + late Locale locale; bool isTest; + late Map _localizedStrings; AppLocalizations(this.locale, {this.isTest = false}); // Helper method to keep the code in the widgets concise // Localizations are accessed using an InheritedWidget "of" syntax - static AppLocalizations of(BuildContext context) { + static AppLocalizations? of(BuildContext context) { return Localizations.of(context, AppLocalizations); } // Static member to have a simple access to the delegate from the MaterialApp static const LocalizationsDelegate delegate = AppLocalizationsDelegate(); - Map _localizedStrings; - setLocale(Locale locale) { this.locale = locale; } @@ -46,7 +45,7 @@ class AppLocalizations with Logging { // This method will be called from every widget which needs a localized text String translate(String key) { if (isTest) return key; - String translated = _localizedStrings[key]; + String? translated = _localizedStrings[key]; return translated != null ? translated : key; } } diff --git a/lib/util/common.dart b/lib/util/common.dart index 7646013..8b3d17b 100644 --- a/lib/util/common.dart +++ b/lib/util/common.dart @@ -8,7 +8,6 @@ import 'package:badges/badges.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import 'package:sentry/sentry.dart'; class DateRate { static String daily = "daily"; @@ -18,8 +17,8 @@ class DateRate { } mixin Common { - final EMAIL_ERROR = "Please type a right email address here."; - final PASSWORD_ERROR = "The password must have at least 8 characters."; + final emailError = "Please type a right email address here."; + final passwordError = "The password must have at least 8 characters."; String toJson(Map map) { String rc = "{"; @@ -30,9 +29,9 @@ mixin Common { return rc; } - ExerciseType getExerciseType(int exerciseTypeId) { - ExerciseType returnElement; - List listExerciseType = Cache().getExerciseTypes(); + ExerciseType? getExerciseType(int exerciseTypeId) { + ExerciseType? returnElement; + List? listExerciseType = Cache().getExerciseTypes(); if (listExerciseType != null) { for (var element in listExerciseType) { if (exerciseTypeId == element.exerciseTypeId) { @@ -65,7 +64,7 @@ mixin Common { } bool validateEmail(UserRepository userRepository) { - final String email = userRepository.user.email; + final String email = userRepository.user.email!; final RegExp _emailRegExp = RegExp( r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', ); @@ -73,7 +72,7 @@ mixin Common { } bool validatePassword(UserRepository userRepository) { - final password = userRepository.user.password; + final password = userRepository.user.password!; final RegExp _passwordRegExp = RegExp(r'^(?=.*[A-Za-z0-9])(?=.*\d)[A-Za-z\d]{7,}$'); return _passwordRegExp.hasMatch(password); @@ -99,12 +98,12 @@ mixin Common { return datePart; } - static String emailValidation(String email) { + static String? emailValidation(String email) { bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(email); return emailValid ? null : "Please type an email address"; } - static String passwordValidation(String value) { + static String? passwordValidation(String? value) { if (value == null || value.length == 0) { return null; } @@ -114,7 +113,7 @@ mixin Common { static Widget badgedIcon(Color color, IconData icon, String badgeKey) { //print("BadgetIcon: " + Cache().getBadges().toString()); - int badgeValue = Cache().getBadges()[badgeKey]; + int? badgeValue = Cache().getBadges()[badgeKey]; bool show = (badgeValue != null); int counter = show ? badgeValue : 0; //print("show $show BadgeKey $badgeKey count $counter"); @@ -134,13 +133,4 @@ mixin Common { ), ); } - - static Future sendMessage(String message) async { - // Sends a full Sentry event payload to show the different parts of the UI. - await Sentry.captureMessage( - message, - level: SentryLevel.info, - template: 'Message: %s, customerId: ' + Cache().userLoggedIn.customerId.toString(), - ); - } } diff --git a/lib/util/enums.dart b/lib/util/enums.dart index d2c9457..f3d16bc 100644 --- a/lib/util/enums.dart +++ b/lib/util/enums.dart @@ -47,7 +47,7 @@ enum TrackingEvent { } T enumFromString(Iterable values, String value) { - return values.firstWhere((type) => type.toString().split(".").last == value, orElse: () => null); + return values.firstWhere((type) => type.toString().split(".").last == value); } extension TrackingEventExt on TrackingEvent { diff --git a/lib/util/not_found_exception.dart b/lib/util/not_found_exception.dart index 6cd97d8..9366aed 100644 --- a/lib/util/not_found_exception.dart +++ b/lib/util/not_found_exception.dart @@ -1,6 +1,6 @@ class NotFoundException implements Exception { final String message; - const NotFoundException({this.message}); + const NotFoundException({required this.message}); } class WorkoutTestException implements Exception { @@ -9,5 +9,5 @@ class WorkoutTestException implements Exception { final String message; final String code; - const WorkoutTestException({this.message, this.code}); + const WorkoutTestException({required this.message, required this.code}); } diff --git a/lib/util/purchases.dart b/lib/util/purchases.dart index 7dcf71d..aac6fae 100644 --- a/lib/util/purchases.dart +++ b/lib/util/purchases.dart @@ -2,15 +2,14 @@ import 'dart:io'; import 'package:aitrainer_app/model/cache.dart'; import 'package:aitrainer_app/service/logging.dart'; -import 'package:aitrainer_app/util/common.dart'; import 'package:flutter/services.dart'; import 'package:purchases_flutter/purchases_flutter.dart'; import 'package:aitrainer_app/model/product.dart' as wtproduct; class RevenueCatPurchases with Logging { static final RevenueCatPurchases _singleton = RevenueCatPurchases._internal(); - Offering _offering; - String appUserId; + Offering? _offering; + String? appUserId; factory RevenueCatPurchases() { return _singleton; @@ -18,14 +17,14 @@ class RevenueCatPurchases with Logging { RevenueCatPurchases._internal(); - Offering get offering => _offering; + Offering? get offering => _offering; Future initPlatform() async { if (Cache().userLoggedIn != null) { await Purchases.setDebugLogsEnabled(true); - await Purchases.setup("yLxGFWaeRtThLImqznvBnUEKjgArSsZE", appUserId: Cache().userLoggedIn.customerId.toString()); + await Purchases.setup("yLxGFWaeRtThLImqznvBnUEKjgArSsZE", appUserId: Cache().userLoggedIn!.customerId.toString()); appUserId = await Purchases.appUserID; - log("AppUserId: " + appUserId); + log("AppUserId: $appUserId"); await Purchases.setAllowSharingStoreAccount(true); await this.restore(); } @@ -36,9 +35,7 @@ class RevenueCatPurchases with Logging { try { //PurchaserInfo purchaserInfo = await Purchases.restoreTransactions(); PurchaserInfo purchaserInfo = await Purchases.getPurchaserInfo(); - if (purchaserInfo != null && - purchaserInfo.entitlements.all["wt_subscription"] != null && - purchaserInfo.entitlements.all["wt_subscription"].isActive) { + if (purchaserInfo.entitlements.all["wt_subscription"] != null && purchaserInfo.entitlements.all["wt_subscription"]!.isActive) { Cache().hasPurchased = true; log(" ******************************************** "); log(" Purchase active ! "); @@ -49,24 +46,23 @@ class RevenueCatPurchases with Logging { log("Purchaserinfo not reachable " + e.toString()); } } - if (Cache().userLoggedIn.admin == 1) { + if (Cache().userLoggedIn!.admin == 1) { Cache().hasPurchased = true; } } - Future getOfferings() async { + Future getOfferings() async { if (appUserId == null) { await initPlatform(); } log(" .. acessing offerings..."); try { Offerings offerings = await Purchases.getOfferings(); - if (offerings.current != null && offerings.current.availablePackages.isNotEmpty) { + if (offerings.current != null && offerings.current!.availablePackages.isNotEmpty) { // Display packages for sale _offering = offerings.current; } else { log("No current offerings"); - Common.sendMessage("No Current offerings"); } } on PlatformException catch (e) { // optional error handling @@ -81,10 +77,10 @@ class RevenueCatPurchases with Logging { _offering = await getOfferings(); } if (_offering != null) { - String productId = Platform.isAndroid ? product.productIdAndroid : product.productIdIos; - Package selectedPackage; - log("Nr of packages: " + _offering.availablePackages.length.toString() + " ProductId: " + productId); - for (var package in _offering.availablePackages) { + String productId = Platform.isAndroid ? product.productIdAndroid! : product.productIdIos!; + Package? selectedPackage; + log("Nr of packages: " + _offering!.availablePackages.length.toString() + " ProductId: " + productId); + for (var package in _offering!.availablePackages) { log("package to check " + package.product.identifier.toString()); if (package.product.identifier == productId) { selectedPackage = package; @@ -94,12 +90,11 @@ class RevenueCatPurchases with Logging { } if (selectedPackage != null) { PurchaserInfo purchaserInfo = await Purchases.purchasePackage(selectedPackage); - if (purchaserInfo.entitlements.all["wt_subscription"].isActive) { + if (purchaserInfo.entitlements.all["wt_subscription"] != null && purchaserInfo.entitlements.all["wt_subscription"]!.isActive) { Cache().hasPurchased = true; } } else { log("!!!! No Selected package to purchase"); - Common.sendMessage("No Selected package to purchase"); throw Exception("Purchase was not successful"); } } else { @@ -114,10 +109,8 @@ class RevenueCatPurchases with Logging { } log(e.toString()); if (errorCode == PurchasesErrorCode.purchaseCancelledError) { - Common.sendMessage("Purchase was cancelled"); throw Exception("Purchase was cancelled"); } else { - Common.sendMessage("Purchase was not successful"); throw Exception("Purchase was not successful"); } } diff --git a/lib/util/session.dart b/lib/util/session.dart index ca5c3d9..a514f22 100644 --- a/lib/util/session.dart +++ b/lib/util/session.dart @@ -15,7 +15,7 @@ import 'package:aitrainer_app/model/cache.dart'; class Session with Logging { Future _prefs = SharedPreferences.getInstance(); - SharedPreferences _sharedPreferences; + late SharedPreferences _sharedPreferences; fetchSessionAndNavigate() async { log(" -- Session: await prefs.."); @@ -35,8 +35,8 @@ class Session with Logging { } Future initDeviceLocale() async { - List languages; - String currentLocale; + List? languages; + String? currentLocale; // Platform messages may fail, so we use a try/catch PlatformException. try { @@ -48,7 +48,7 @@ class Session with Logging { } try { currentLocale = await Devicelocale.currentLocale; - log("Device currentlocale " + currentLocale); + log("Device currentlocale $currentLocale"); } on PlatformException { log("Error obtaining current locale"); } @@ -59,14 +59,14 @@ class Session with Logging { */ _fetchToken(SharedPreferences prefs) async { var responseJson = await APIClient().authenticateUser(Cache.username, Cache.password); - int customerId = 0; + int? customerId = 0; log("--- Lang: " + AppLanguage().appLocal.toString()); if (responseJson['error'] != null) { log("************** Here big error - no authentication"); } else if (responseJson['token'] != null) { prefs.setString(Cache.authTokenKey, responseJson['token']); Cache().authToken = responseJson['token']; - Cache().firebaseUid = prefs.get(Cache.firebaseUidKey); + Cache().firebaseUid = prefs.getString(Cache.firebaseUidKey); await PackageApi().getPackage(); if (prefs.get(Cache.customerIdKey) == null) { @@ -76,25 +76,30 @@ class Session with Logging { Cache().startPage = "registration"; } else { DateTime now = DateTime.now(); - DateTime lastStoreDate = DateTime.parse(prefs.get(Cache.lastStoreDateKey)); - DateTime minStoreDate = now.add(Duration(days: -10)); + String? lastStore = prefs.getString(Cache.lastStoreDateKey); + if (lastStore != null) { + DateTime lastStoreDate = DateTime.parse(lastStore); + DateTime minStoreDate = now.add(Duration(days: -10)); - if (lastStoreDate == null || - lastStoreDate.difference(minStoreDate) > Duration(days: 10) || - prefs.get(Cache.isLoggedInKey) == null || - prefs.get(Cache.isLoggedInKey) == false) { - log("************* Login"); - Cache().startPage = "login"; - } else { - // only - if (Cache().firebaseUid == null) { - log("************* firebaseUid is null, Login"); + if (lastStoreDate.difference(minStoreDate) > Duration(days: 10) || + prefs.get(Cache.isLoggedInKey) == null || + prefs.get(Cache.isLoggedInKey) == false) { + log("************* Login"); Cache().startPage = "login"; } else { - // get API customer - customerId = prefs.getInt(Cache.customerIdKey); - Cache().startPage = "home"; - await Cache().initCustomer(customerId); + if (Cache().firebaseUid == null) { + log("************* firebaseUid is null, Login"); + Cache().startPage = "login"; + } else { + // get API customer + customerId = prefs.getInt(Cache.customerIdKey); + if (customerId == null) { + customerId = 0; + } + Cache().startPage = "home"; + log("Customer in the preferences $customerId"); + await Cache().initCustomer(customerId); + } } } log("--- Session finished"); diff --git a/lib/util/track.dart b/lib/util/track.dart index d0e0aaa..bf40084 100644 --- a/lib/util/track.dart +++ b/lib/util/track.dart @@ -3,7 +3,7 @@ import 'package:aitrainer_app/model/cache.dart'; import 'package:aitrainer_app/service/logging.dart'; import 'package:aitrainer_app/service/tracking_service.dart'; import 'package:aitrainer_app/util/enums.dart'; -import 'package:flurry/flurry.dart'; +import 'package:aitrainer_app/library/flurry.dart'; import 'package:aitrainer_app/model/tracking.dart' as model; import 'package:smartlook/smartlook.dart'; @@ -21,7 +21,7 @@ class Track with Logging { Flurry.logEvent(event.toString()); Smartlook.setGlobalEventProperty(event.toString(), eventValue, false); model.Tracking tracking = model.Tracking(); - tracking.customerId = Cache().userLoggedIn.customerId; + tracking.customerId = Cache().userLoggedIn!.customerId!; tracking.event = event.enumToString(); if (eventValue.isNotEmpty) { tracking.eventValue = eventValue; diff --git a/lib/util/trans.dart b/lib/util/trans.dart index 0ccb9f3..ef4e07d 100644 --- a/lib/util/trans.dart +++ b/lib/util/trans.dart @@ -2,14 +2,12 @@ import 'package:aitrainer_app/util/app_localization.dart'; import 'package:flutter/cupertino.dart'; mixin Trans { - BuildContext context; + late BuildContext context; void setContext(BuildContext context) { this.context = context; } String t(String text) { - return AppLocalizations.of(context).translate(text); + return AppLocalizations.of(context)!.translate(text); } - - -} \ No newline at end of file +} diff --git a/lib/view/account.dart b/lib/view/account.dart index a1d2241..2f0660c 100644 --- a/lib/view/account.dart +++ b/lib/view/account.dart @@ -16,7 +16,7 @@ import 'package:flutter/cupertino.dart'; // ignore: must_be_immutable class AccountPage extends StatelessWidget with Trans { // ignore: close_sinks - AccountBloc accountBloc; + late AccountBloc accountBloc; @override Widget build(BuildContext context) { @@ -34,7 +34,7 @@ class AccountPage extends StatelessWidget with Trans { ), child: BlocConsumer(listener: (context, state) { if (state is AccountError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is AccountLoading) {} }, builder: (context, state) { @@ -49,29 +49,31 @@ class AccountPage extends StatelessWidget with Trans { String goal = t("Set your goal"); String fitnessLevel = t("Set your fitness level"); String bodyType = ""; - if (accountBloc.customerRepository.customer != null) { - customerName = accountBloc.customerRepository.firstName + " " + accountBloc.customerRepository.name; - customerName = customerName.length < 3 ? t("Personal data") : customerName; - goal = accountBloc.customerRepository.customer.goal != null ? t(accountBloc.customerRepository.customer.goal) : goal; - fitnessLevel = accountBloc.customerRepository.customer.fitnessLevel != null - ? t(capitalize(accountBloc.customerRepository.customer.fitnessLevel)) - : fitnessLevel; - bodyType = accountBloc.getAccurateBodyType(); - } + + customerName = accountBloc.customerRepository.firstName! + " " + accountBloc.customerRepository.name!; + customerName = customerName.length < 3 ? t("Personal data") : customerName; + goal = accountBloc.customerRepository.customer.goal != null ? t(accountBloc.customerRepository.customer.goal!) : goal; + fitnessLevel = accountBloc.customerRepository.customer.fitnessLevel != null + ? t(capitalize(accountBloc.customerRepository.customer.fitnessLevel!)) + : fitnessLevel; + bodyType = accountBloc.getAccurateBodyType(); + final HashMap args = HashMap(); return ListView(padding: EdgeInsets.only(top: 35), children: [ ListTile( leading: Common.badgedIcon(Colors.grey, Icons.perm_identity, "personalData"), //Icon(Icons.perm_identity), subtitle: Text(t("Profile")), - title: FlatButton( + title: TextButton( child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(customerName, style: TextStyle(color: Colors.blue)), Icon(Icons.arrow_forward_ios), ]), - textColor: Colors.grey, - color: Colors.white, + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), onPressed: () => { - if (accountBloc.customerRepository.customer != null && Cache().userLoggedIn != null) + if (Cache().userLoggedIn != null) { args['personal_data'] = true, Navigator.of(context).pushNamed('customerModifyPage', arguments: args), @@ -82,15 +84,17 @@ class AccountPage extends StatelessWidget with Trans { ListTile( leading: Common.badgedIcon(Colors.grey, Icons.arrow_forward_sharp, "Goal"), //Icon(Icons.arrow_forward_sharp), subtitle: Text(t("Goal")), - title: FlatButton( + title: TextButton( child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(goal, style: TextStyle(color: Colors.blue)), Icon(Icons.arrow_forward_ios), ]), - textColor: Colors.grey, - color: Colors.white, + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), onPressed: () => { - if (accountBloc.customerRepository.customer != null && Cache().userLoggedIn != null) + if (Cache().userLoggedIn != null) { args['personal_data'] = true, args['bloc'] = accountBloc.customerRepository, @@ -102,15 +106,17 @@ class AccountPage extends StatelessWidget with Trans { ListTile( leading: Common.badgedIcon(Colors.grey, Icons.perm_contact_cal, "FitnessLevel"), //Icon(Icons.perm_contact_cal), subtitle: Text(t("Activity")), - title: FlatButton( + title: TextButton( child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(fitnessLevel, style: TextStyle(color: Colors.blue)), Icon(Icons.arrow_forward_ios), ]), - textColor: Colors.grey, - color: Colors.white, + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), onPressed: () => { - if (accountBloc.customerRepository.customer != null && Cache().userLoggedIn != null) + if (Cache().userLoggedIn != null) { args['personal_data'] = true, args['bloc'] = accountBloc.customerRepository, @@ -122,15 +128,17 @@ class AccountPage extends StatelessWidget with Trans { ListTile( leading: Common.badgedIcon(Colors.grey, CustomIcon.people_arrows, "bodyType"), //Icon(CustomIcon.people_arrows), subtitle: Text(t("Body Type")), - title: FlatButton( + title: TextButton( + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(t(bodyType), style: TextStyle(color: Colors.blue)), Icon(Icons.arrow_forward_ios), ]), - textColor: Colors.grey, - color: Colors.white, onPressed: () => { - if (accountBloc.customerRepository.customer != null && Cache().userLoggedIn != null) + if (Cache().userLoggedIn != null) { args['personal_data'] = true, args['bloc'] = accountBloc.customerRepository, @@ -150,14 +158,18 @@ class AccountPage extends StatelessWidget with Trans { element = ListTile( leading: Common.badgedIcon(Colors.grey, Icons.device_hub, "customerDevice"), subtitle: Text(t("These equipments and devices are available")), - title: FlatButton( + title: TextButton( + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [Text(t("Available Devices"), style: TextStyle(color: Colors.orange)), Icon(Icons.arrow_forward_ios)]), - textColor: Colors.orange, - color: Colors.white, + //textColor: Colors.orange, + //color: Colors.white, onPressed: () => { - if (accountBloc.customerRepository.customer != null && Cache().userLoggedIn != null) + if (Cache().userLoggedIn != null) { Navigator.of(context).pushNamed('customerExerciseDevicePage'), } @@ -173,7 +185,7 @@ class AccountPage extends StatelessWidget with Trans { String text = "Logout"; Color buttonColor = Colors.orange; - if (accountBloc.customerRepository.customer == null || accountBloc.customerRepository.customer.email == null) { + if (accountBloc.customerRepository.customer.email == null) { text = "Login"; buttonColor = Colors.blue; } @@ -181,13 +193,15 @@ class AccountPage extends StatelessWidget with Trans { element = ListTile( enabled: true, leading: Icon(Icons.input), - title: FlatButton( + title: TextButton( + style: TextButton.styleFrom( + backgroundColor: Colors.white, + onSurface: Colors.grey, + ), child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(t(text), style: TextStyle(color: buttonColor)), Icon(Icons.arrow_forward_ios), ]), - textColor: buttonColor, - color: Colors.white, onPressed: () => { if (accountBloc.loggedIn) { @@ -206,9 +220,6 @@ class AccountPage extends StatelessWidget with Trans { } Widget getMyTrainees(BuildContext context, AccountBloc accountBloc) { - if (accountBloc.customerRepository.customer == null) { - return Container(); - } if (accountBloc.customerRepository.customer.trainer == 0) { return ListTile( title: Container(), @@ -218,31 +229,35 @@ class AccountPage extends StatelessWidget with Trans { if (accountBloc.customerRepository.getTraineesList() == null) { return ListTile( leading: Icon(Icons.people), - title: RaisedButton( - color: Colors.white70, + title: ElevatedButton( + style: ElevatedButton.styleFrom( + primary: Colors.white70, + ), onPressed: () => accountBloc.add(AccountGetTrainees()), child: Text("See my trainees"), ), ); } - List elements = List(); - accountBloc.customerRepository.getTraineesList().forEach((element) { + List elements = []; + accountBloc.customerRepository.getTraineesList()!.forEach((element) { Customer trainee = element; - String name = trainee.name; - String firstName = trainee.firstname; + String name = trainee.name!; + String firstName = trainee.firstname!; String nodeName = AppLanguage().appLocal == Locale("en") ? firstName + " " + name : name + " " + firstName; bool selected = accountBloc.traineeId == trainee.customerId; - Widget widget = FlatButton( - padding: EdgeInsets.all(10), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8)), - side: BorderSide(width: 2, color: selected ? Colors.blue : Colors.black26), + Widget widget = TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8)), + side: BorderSide(width: 2, color: selected ? Colors.blue : Colors.black26), + ), ), onPressed: () { - accountBloc.add(AccountSelectTrainee(traineeId: trainee.customerId)); + accountBloc.add(AccountSelectTrainee(traineeId: trainee.customerId!)); //Navigator.of(context).pushNamed('login'); }, child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -270,18 +285,17 @@ class AccountPage extends StatelessWidget with Trans { showCupertinoDialog( useRootNavigator: true, context: context, - //barrierDismissible: false, builder: (_) => CupertinoAlertDialog( title: Text(t("Are you sure to logout?")), content: Column(children: [ Divider(), ]), actions: [ - FlatButton( + TextButton( child: Text(t("No")), onPressed: () => Navigator.pop(context), ), - FlatButton( + TextButton( child: Text(t("Yes")), onPressed: () => { accountBloc.add(AccountLogout()), @@ -292,7 +306,7 @@ class AccountPage extends StatelessWidget with Trans { )); } - String capitalize(String s) { + String capitalize(String? s) { if (s == null || s.isEmpty) { return " "; } diff --git a/lib/view/custom_exercise_page.dart b/lib/view/custom_exercise_page.dart deleted file mode 100644 index 6d8fb31..0000000 --- a/lib/view/custom_exercise_page.dart +++ /dev/null @@ -1,355 +0,0 @@ -import 'dart:collection'; - -import 'package:aitrainer_app/bloc/custom_exercise_form_bloc.dart'; -import 'package:aitrainer_app/util/app_localization.dart'; -import 'package:aitrainer_app/model/exercise_type.dart'; -import 'package:aitrainer_app/repository/exercise_repository.dart'; -import 'package:aitrainer_app/service/logging.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; - -class CustomExercisePage extends StatefulWidget { - _CustomExerciseNewPageState createState() => _CustomExerciseNewPageState(); -} - -class _CustomExerciseNewPageState extends State with Logging { - final GlobalKey _scaffoldKey = new GlobalKey(); - - @override - Widget build(BuildContext context) { - final ExerciseType exerciseType = ModalRoute.of(context).settings.arguments; - - return BlocProvider( - create: (context) => CustomExerciseFormBloc(exerciseRepository: ExerciseRepository()), - child: Builder(builder: (context) { - final exerciseBloc = BlocProvider.of(context); - exerciseBloc.exerciseRepository.setExerciseType(exerciseType); - - return Scaffold( - key: _scaffoldKey, - resizeToAvoidBottomInset: true, - appBar: AppBar( - backgroundColor: Colors.transparent, - title: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - Image.asset( - 'asset/image/WT_long_logo.png', - fit: BoxFit.cover, - height: 65.0, - ), - ], - ), - leading: IconButton( - icon: Icon(Icons.arrow_back, color: Colors.white), - onPressed: () => Navigator.of(context).pop(), - ), - ), - body: FormBlocListener( - /* onSubmitting: (context, state) { - LoadingDialog.show(context); - }, */ - onSuccess: (context, state) {}, - onFailure: (context, state) { - Scaffold.of(context).showSnackBar(SnackBar( - backgroundColor: Colors.orange, content: Text(state.failureResponse, style: TextStyle(color: Colors.white)))); - }, - child: ModalProgressHUD( - child: Container( - width: MediaQuery.of(context).size.width, - height: MediaQuery.of(context).size.height, - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('asset/image/WT_light_background.jpg'), - fit: BoxFit.fill, - alignment: Alignment.center, - ), - ), - child: CustomScrollView(scrollDirection: Axis.vertical, slivers: [ - SliverList( - delegate: SliverChildListDelegate([ - Container( - padding: EdgeInsets.only(top: 20, left: 25, right: 25), - alignment: Alignment.center, - child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ - Text("Custom Exercise", - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.deepOrange)), - columnQuantityUnit(exerciseBloc), - columnQuantity(exerciseBloc), - ])), - ]), - ), - gridCalculation(exerciseBloc) - ])), - inAsyncCall: exerciseBloc.loading == true, - opacity: 0.5, - color: Colors.black54, - progressIndicator: CircularProgressIndicator(), - ), - )); - })); - } - - Column columnQuantityUnit(CustomExerciseFormBloc bloc) { - Column column = Column(); - if (bloc.exerciseRepository.exerciseType != null && bloc.exerciseRepository.exerciseType.unitQuantity == "1") { - column = Column(children: [ - TextFieldBlocBuilder( - textFieldBloc: bloc.unitQuantityField, - textAlign: TextAlign.center, - style: TextStyle(fontSize: 16, color: Colors.lightBlue, fontWeight: FontWeight.bold), - inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"[\d.]"))], - onChanged: (input) => {log("UnitQuantity value $input"), bloc.exerciseRepository.setUnitQuantity(double.parse(input))}, - decoration: InputDecoration( - fillColor: Colors.white, - filled: false, - hintStyle: TextStyle(fontSize: 12, color: Colors.black54, fontWeight: FontWeight.w100), - hintText: AppLocalizations.of(context).translate("The number of the exercise done with"), - labelStyle: TextStyle(fontSize: 12, color: Colors.lightBlue), - labelText: AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unitQuantityUnit), - ), - ), - new InkWell( - child: new Text(AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unitQuantityUnit), - style: TextStyle(fontSize: 12)), - ), - ]); - } - return column; - } - - Column columnQuantity(CustomExerciseFormBloc bloc) { - Column column = Column(children: [ - TextFieldBlocBuilder( - textFieldBloc: bloc.quantityField, - textAlign: TextAlign.center, - style: TextStyle(fontSize: 20, color: Colors.deepOrange, fontWeight: FontWeight.bold), - inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"[\d.]"))], - onChanged: (input) => { - log("Quantity value $input"), - bloc.exerciseRepository.setQuantity(double.parse(input)), - bloc.exerciseRepository.setUnit(bloc.exerciseRepository.exerciseType.unit) - }, - decoration: InputDecoration( - fillColor: Colors.white, - filled: false, - hintStyle: TextStyle(fontSize: 12, color: Colors.black54, fontWeight: FontWeight.w100), - hintText: AppLocalizations.of(context).translate("The number of the exercise"), - labelStyle: TextStyle(fontSize: 12, color: Colors.deepOrange), - labelText: AppLocalizations.of(context).translate(bloc.exerciseRepository.exerciseType.unit), - ), - ), - ]); - - return column; - } - - SliverGrid gridCalculation(CustomExerciseFormBloc bloc) { - LinkedHashMap args = LinkedHashMap(); - return SliverGrid( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - mainAxisSpacing: 10.0, - crossAxisSpacing: 10.0, - childAspectRatio: 2.0, - ), - delegate: SliverChildListDelegate( - [ - TextFieldBlocBuilder( - readOnly: true, - textFieldBloc: bloc.rmWendlerField, - padding: EdgeInsets.only(left: 10), - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM by Wendler: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rmWathenField, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM by Wahten: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rmOconnerField, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM by O'Conner: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rmMayhewField, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM by Mayhew: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rmAverageField, - style: TextStyle(color: Colors.blueAccent, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM Average: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm90Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 90%: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm75Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 75%: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm75OconnorField, - style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 75%: by O'Connor", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm75WendlerField, - style: TextStyle(color: Colors.deepOrange, fontSize: 12, fontWeight: FontWeight.normal), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 75% by Wendler: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm80Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 80%: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm70Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 70%: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm60Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 60%: ", - )), - TextFieldBlocBuilder( - readOnly: true, - padding: EdgeInsets.only(left: 10), - maxLines: 1, - textFieldBloc: bloc.rm50Field, - style: TextStyle(color: Colors.deepOrange, fontSize: 12), - decoration: InputDecoration( - border: InputBorder.none, - fillColor: Colors.white, - filled: false, - labelText: "1RM 50%: ", - )), - RaisedButton( - padding: EdgeInsets.all(0), - textColor: Colors.white, - color: Colors.blue, - focusColor: Colors.blueAccent, - onPressed: () => { - args['exerciseRepository'] = bloc.exerciseRepository, - args['percent'] = 0.75, - args['readonly'] = true, - Navigator.of(context).pushNamed('exerciseControlPage', arguments: args) - }, - child: Text( - "Control with 75%", - style: TextStyle(fontSize: 12), - )), - RaisedButton( - padding: EdgeInsets.all(0), - textColor: Colors.white, - color: Colors.green, - focusColor: Colors.blueAccent, - onPressed: () => { - args['exerciseRepository'] = bloc.exerciseRepository, - args['percent'] = 0.5, - args['readonly'] = true, - Navigator.of(context).pushNamed('exerciseControlPage', arguments: args) - }, - child: Text( - "Control with 50%", - style: TextStyle(fontSize: 12), - )), - ], - )); - } - - @override - void dispose() { - super.dispose(); - } -} diff --git a/lib/view/customer_bodytype_animation.dart b/lib/view/customer_bodytype_animation.dart index b9afbae..10178d2 100644 --- a/lib/view/customer_bodytype_animation.dart +++ b/lib/view/customer_bodytype_animation.dart @@ -10,10 +10,9 @@ import 'package:aitrainer_app/widgets/app_bar.dart'; import 'package:aitrainer_app/widgets/dialog_html.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:liquid_progress_indicator/liquid_progress_indicator.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:rainbow_color/rainbow_color.dart'; class CustomerBodyTypeAnimationPage extends StatefulWidget { @@ -22,17 +21,17 @@ class CustomerBodyTypeAnimationPage extends StatefulWidget { } class _CustomerBodyTypeAnimationPageState extends State with Trans { - bool fulldata; + late bool fulldata; @override Widget build(BuildContext context) { CustomerRepository customerRepository; - dynamic args = ModalRoute.of(context).settings.arguments; + dynamic args = ModalRoute.of(context)!.settings.arguments; if (args is HashMap && args['personal_data'] != null) { fulldata = args['personal_data']; customerRepository = args['bloc']; } else { - customerRepository = ModalRoute.of(context).settings.arguments; + customerRepository = ModalRoute.of(context)!.settings.arguments as CustomerRepository; } setContext(context); @@ -53,7 +52,7 @@ class _CustomerBodyTypeAnimationPageState extends State BodytypeBloc(repository: customerRepository), child: BlocConsumer(listener: (context, state) { if (state is BodytypeError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.error, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -321,14 +320,14 @@ class _CustomerBodyTypeAnimationPageState extends State _BodyTypeResultState(); } class _BodyTypeResultState extends State with TickerProviderStateMixin { - Animation colorAnim; - AnimationController colorController; + late Animation colorAnim; + late AnimationController colorController; @override void initState() { @@ -339,14 +338,14 @@ class _BodyTypeResultState extends State with TickerProviderStat void buildAnimation() { colorController = AnimationController(duration: Duration(seconds: 2), vsync: this); colorAnim = RainbowColorTween([ - Colors.green[800], - Colors.green[700], - Colors.green[600], - Colors.green[500], - Colors.green[400], - Colors.green[300], - Colors.green[200], - Colors.green[100], + Colors.green[800]!, + Colors.green[700]!, + Colors.green[600]!, + Colors.green[500]!, + Colors.green[400]!, + Colors.green[300]!, + Colors.green[200]!, + Colors.green[100]!, Color(0xffb4f500), ]).animate(colorController) ..addListener(() { @@ -384,14 +383,14 @@ class CurvePainter extends CustomPainter { final linePainter = Paint(); final circlePainter = Paint(); final Color color; - final int value; - CurvePainter({this.value, this.color}); + + CurvePainter({required this.value, required this.color}); @override void paint(Canvas canvas, Size size) { var paint = linePainter; - paint.color = Colors.green[800]; + paint.color = Colors.green[800]!; paint.strokeWidth = 5; paint.style = PaintingStyle.fill; @@ -421,15 +420,16 @@ class CurvePainter extends CustomPainter { class Question extends StatefulWidget { final String text; final BodytypeBloc bloc; - const Question({this.text, this.bloc}); + const Question({required this.text, required this.bloc}); @override _QuestionState createState() => _QuestionState(); } class _QuestionState extends State with TickerProviderStateMixin { - AnimationController _controller; - Animation _animation; + late AnimationController _controller; + late Animation _animation; + @override void initState() { super.initState(); @@ -464,7 +464,7 @@ class _QuestionState extends State with TickerProviderStateMixin { child: FadeTransition( key: ValueKey(widget.text), opacity: _animation, - child: Text(AppLocalizations.of(context).translate(widget.bloc.getQuestion()), + child: Text(AppLocalizations.of(context)!.translate(widget.bloc.getQuestion()), textAlign: TextAlign.center, maxLines: 3, style: GoogleFonts.archivoBlack( @@ -491,15 +491,15 @@ class CircleButton extends StatefulWidget { final BodytypeBloc bloc; final int value; - CircleButton({Key key, this.onTap, this.bloc, this.value}) : super(key: key); + CircleButton({Key? key, required this.onTap, required this.bloc, required this.value}) : super(key: key); @override _CircleButtonState createState() => _CircleButtonState(); } class _CircleButtonState extends State with TickerProviderStateMixin { - Animation colorAnim; - AnimationController colorController; + late Animation colorAnim; + late AnimationController colorController; @override void initState() { @@ -530,14 +530,14 @@ class _CircleButtonState extends State with TickerProviderStateMix Color(0xffb4f500), Color(0xffb4f500), Color(0xffb4f500), - Colors.green[100], - Colors.green[200], - Colors.green[300], - Colors.green[400], - Colors.green[500], - Colors.green[600], - Colors.green[700], - Colors.green[800], + Colors.green[100]!, + Colors.green[200]!, + Colors.green[300]!, + Colors.green[400]!, + Colors.green[500]!, + Colors.green[600]!, + Colors.green[700]!, + Colors.green[800]!, ]).animate(colorController) ..addListener(() { setState(() {}); @@ -567,14 +567,14 @@ class _AnimatedLiquidCustomProgressIndicator extends StatefulWidget { final int percentTo; final int percentFrom; - const _AnimatedLiquidCustomProgressIndicator({this.percentTo, this.percentFrom}); + const _AnimatedLiquidCustomProgressIndicator({required this.percentTo, required this.percentFrom}); @override State createState() => _AnimatedLiquidCustomProgressIndicatorState(); } class _AnimatedLiquidCustomProgressIndicatorState extends State<_AnimatedLiquidCustomProgressIndicator> with TickerProviderStateMixin { - AnimationController _animationController; + late AnimationController _animationController; bool switching = false; @override @@ -625,7 +625,7 @@ class _AnimatedLiquidCustomProgressIndicatorState extends State<_AnimatedLiquidC value: _animationController.value, direction: Axis.vertical, backgroundColor: Colors.white, - valueColor: AlwaysStoppedAnimation(Colors.blue[200]), + valueColor: AlwaysStoppedAnimation(Colors.blue[200]!), shapePath: _buildHeartPath(), center: Text( "${percentage.toStringAsFixed(0)}%", @@ -650,26 +650,4 @@ class _AnimatedLiquidCustomProgressIndicatorState extends State<_AnimatedLiquidC ..cubicTo(65, 0, 55, 12, 55, 15) ..close(); } - - Path _buildManPath() { - return Path() - ..moveTo(55, 15) - ..cubicTo(75, 20, 75, 32, 68, 38) - ..lineTo(68, 43) - ..lineTo(116, 43) - ..lineTo(116, 55) - ..lineTo(75, 55) - ..conicTo(68, 80, 80, 120, 20) - ..lineTo(68, 120) - ..lineTo(55, 90) - ..lineTo(42, 120) - ..lineTo(20, 120) - ..conicTo(42, 80, 40, 55, 40) - ..lineTo(0, 55) - ..lineTo(0, 43) - ..lineTo(48, 43) - ..lineTo(48, 38) - ..cubicTo(25, 20, 25, 32, 55, 15) - ..close(); - } } diff --git a/lib/view/customer_exercise_device.dart b/lib/view/customer_exercise_device.dart index 27c3003..cfb9502 100644 --- a/lib/view/customer_exercise_device.dart +++ b/lib/view/customer_exercise_device.dart @@ -10,11 +10,11 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class CustomerExerciseDevicePage extends StatelessWidget with Trans { - List listDevice; + late List listDevice; @override Widget build(BuildContext context) { @@ -34,12 +34,12 @@ class CustomerExerciseDevicePage extends StatelessWidget with Trans { ), child: BlocProvider( create: (context) => - CustomerExerciseDeviceBloc(repository: CustomerExerciseDeviceRepository(), devices: Cache().getDevices()) + CustomerExerciseDeviceBloc(repository: CustomerExerciseDeviceRepository(), devices: Cache().getDevices()!) ..add(CustomerExerciseDeviceLoad()), child: BlocConsumer( listener: (context, state) { if (state is CustomerExerciseDeviceError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, @@ -183,7 +183,7 @@ class CustomerExerciseDevicePage extends StatelessWidget with Trans { List getDevices(CustomerExerciseDeviceBloc bloc, double cWidth, double cHeight) { final bool isEnglish = AppLanguage().appLocal.languageCode == "en"; - this.listDevice = List(); + this.listDevice = []; final devices = bloc.devices; if (devices != null) { devices.sort((a, b) => a.sort.compareTo(b.sort)); @@ -213,7 +213,7 @@ class CustomerExerciseDevicePage extends StatelessWidget with Trans { List getDevicesPlace(CustomerExerciseDeviceBloc bloc, double cWidth, cHeight) { final bool isEnglish = AppLanguage().appLocal.languageCode == "en"; - this.listDevice = List(); + this.listDevice = []; final devices = bloc.devices; if (devices != null) { devices.sort((a, b) => a.sort.compareTo(b.sort)); diff --git a/lib/view/customer_fitness_page.dart b/lib/view/customer_fitness_page.dart index 0629b15..5dc05a9 100644 --- a/lib/view/customer_fitness_page.dart +++ b/lib/view/customer_fitness_page.dart @@ -14,7 +14,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; // ignore: must_be_immutable class CustomerFitnessPage extends StatefulWidget { - _CustomerFitnessPageState _state; + late _CustomerFitnessPageState _state; _CustomerFitnessPageState createState() { _state = _CustomerFitnessPageState(); @@ -22,11 +22,10 @@ class CustomerFitnessPage extends StatefulWidget { } } -//TODO // dropbox for professional sport class _CustomerFitnessPageState extends State with Trans { - String selected; + late String selected; bool fulldata = false; @override @@ -34,21 +33,24 @@ class _CustomerFitnessPageState extends State with Trans { setContext(context); final double cWidth = MediaQuery.of(context).size.width * 0.75; CustomerRepository customerRepository; - dynamic args = ModalRoute.of(context).settings.arguments; + dynamic args = ModalRoute.of(context)!.settings.arguments; if (args is HashMap && args['personal_data'] != null) { fulldata = args['personal_data']; customerRepository = args['bloc']; } else { - customerRepository = ModalRoute.of(context).settings.arguments; + customerRepository = ModalRoute.of(context)!.settings.arguments as CustomerRepository; } - selected = customerRepository.customer.fitnessLevel; + selected = customerRepository.customer.fitnessLevel!; + + PreferredSizeWidget _bar = AppBarMin( + back: true, + ); + if (!fulldata) { + _bar = AppBarProgress(max: 50, min: 26); + } return Scaffold( - appBar: fulldata - ? AppBarMin( - back: true, - ) - : AppBarProgress(max: 75, min: 51), + appBar: _bar, body: BlocProvider( create: (context) => CustomerChangeBloc(customerRepository: customerRepository), child: Builder(builder: (context) { @@ -80,7 +82,11 @@ class _CustomerFitnessPageState extends State with Trans { ) ]), Divider(), - FlatButton( + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(10.0), + shape: getShape(customerRepository, FitnessState.beginner), + ), child: Container( width: cWidth, child: Column( @@ -94,8 +100,6 @@ class _CustomerFitnessPageState extends State with Trans { ), ], )), - padding: EdgeInsets.all(10.0), - shape: getShape(customerRepository, FitnessState.beginner), onPressed: () => { setState(() { selected = FitnessState.beginner; @@ -103,7 +107,11 @@ class _CustomerFitnessPageState extends State with Trans { }), }), Divider(), - FlatButton( + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(10.0), + shape: getShape(customerRepository, FitnessState.intermediate), + ), child: Container( width: cWidth, child: Column( @@ -125,8 +133,6 @@ class _CustomerFitnessPageState extends State with Trans { ], ), ), - padding: EdgeInsets.all(10.0), - shape: getShape(customerRepository, FitnessState.intermediate), onPressed: () => { setState(() { selected = FitnessState.intermediate; @@ -135,7 +141,11 @@ class _CustomerFitnessPageState extends State with Trans { }), }), Divider(), - FlatButton( + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(10.0), + shape: getShape(customerRepository, FitnessState.advanced), + ), child: Container( width: cWidth, child: Column( @@ -157,8 +167,6 @@ class _CustomerFitnessPageState extends State with Trans { ], ), ), - padding: EdgeInsets.all(10.0), - shape: getShape(customerRepository, FitnessState.advanced), onPressed: () => { setState(() { selected = FitnessState.advanced; @@ -167,21 +175,25 @@ class _CustomerFitnessPageState extends State with Trans { }), }), Divider(), - FlatButton( + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(10.0), + shape: getShape(customerRepository, FitnessState.professional), + ), child: Container( width: cWidth, child: Column( children: [ InkWell( child: Text( - AppLocalizations.of(context).translate("Professional"), + AppLocalizations.of(context)!.translate("Professional"), style: TextStyle(color: Colors.blue, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900), ), highlightColor: Colors.white, ), InkWell( child: Text( - AppLocalizations.of(context).translate("I am professional"), + AppLocalizations.of(context)!.translate("I am professional"), style: TextStyle(color: Colors.black, fontSize: 20, fontFamily: 'Arial', fontWeight: FontWeight.w100), ), highlightColor: Colors.white, @@ -189,8 +201,6 @@ class _CustomerFitnessPageState extends State with Trans { ], ), ), - padding: EdgeInsets.all(10.0), - shape: getShape(customerRepository, FitnessState.professional), onPressed: () => { setState(() { selected = FitnessState.professional; @@ -199,9 +209,11 @@ class _CustomerFitnessPageState extends State with Trans { }), }), Divider(), - RaisedButton( - color: Colors.orange, - textColor: Colors.white, + ElevatedButton( + style: ElevatedButton.styleFrom( + onPrimary: Colors.white, + primary: Colors.orange, + ), child: Text(fulldata ? t("Save") : t("Next")), onPressed: () => { changeBloc.add(CustomerSave()), @@ -217,7 +229,7 @@ class _CustomerFitnessPageState extends State with Trans { } dynamic getShape(CustomerRepository customerRepository, String fitnessLevel) { - String selected = customerRepository.fitnessLevel; + String selected = customerRepository.fitnessLevel!; dynamic returnCode = (selected == fitnessLevel) ? RoundedRectangleBorder( side: BorderSide(width: 4, color: Colors.orange), diff --git a/lib/view/customer_goal_page.dart b/lib/view/customer_goal_page.dart index d7a5693..b6d50b0 100644 --- a/lib/view/customer_goal_page.dart +++ b/lib/view/customer_goal_page.dart @@ -8,7 +8,7 @@ import 'package:aitrainer_app/widgets/app_bar_min.dart'; import 'package:aitrainer_app/widgets/app_bar_progress.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; class GoalsItem { static String muscle = "gain_muscle"; @@ -22,7 +22,7 @@ class CustomerGoalPage extends StatefulWidget { } class _CustomerGoalPage extends State with Trans { - String selected; + String? selected; bool fulldata = false; @override @@ -30,20 +30,23 @@ class _CustomerGoalPage extends State with Trans { setContext(context); CustomerRepository customerRepository; - dynamic args = ModalRoute.of(context).settings.arguments; + dynamic args = ModalRoute.of(context)!.settings.arguments; if (args is HashMap && args['personal_data'] != null) { fulldata = args['personal_data']; customerRepository = args['bloc']; } else { - customerRepository = ModalRoute.of(context).settings.arguments; + customerRepository = ModalRoute.of(context)!.settings.arguments as CustomerRepository; + } + + PreferredSizeWidget _bar = AppBarMin( + back: true, + ); + if (!fulldata) { + _bar = AppBarProgress(max: 50, min: 26); } return Scaffold( - appBar: fulldata - ? AppBarMin( - back: true, - ) - : AppBarProgress(max: 50, min: 26), + appBar: _bar, body: Container( decoration: BoxDecoration( image: DecorationImage( @@ -66,19 +69,21 @@ class _CustomerGoalPage extends State with Trans { Divider(), InkWell( child: Text( - AppLocalizations.of(context).translate("Set Your Goals"), + AppLocalizations.of(context)!.translate("Set Your Goals"), style: TextStyle(color: Colors.orange, fontSize: 50, fontFamily: 'Arial', fontWeight: FontWeight.w900), ), highlightColor: Colors.white, ), - Stack(alignment: Alignment.bottomLeft, overflow: Overflow.visible, children: [ - FlatButton( + Stack(alignment: Alignment.bottomLeft, children: [ + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(0.0), + shape: getShape(changeBloc, GoalsItem.muscle), + ), child: Image.asset( "asset/image/Gain_muscle.jpg", height: 180, ), - padding: EdgeInsets.all(0.0), - shape: getShape(changeBloc, GoalsItem.muscle), onPressed: () => { setState(() { selected = GoalsItem.muscle; @@ -87,21 +92,23 @@ class _CustomerGoalPage extends State with Trans { }), InkWell( child: Text( - AppLocalizations.of(context).translate("Gain Muscle"), + AppLocalizations.of(context)!.translate("Gain Muscle"), style: TextStyle(color: Colors.white, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900), ), highlightColor: Colors.white, ) ]), Divider(), - Stack(alignment: Alignment.bottomLeft, overflow: Overflow.visible, children: [ - FlatButton( + Stack(alignment: Alignment.bottomLeft, children: [ + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(0.0), + shape: getShape(changeBloc, GoalsItem.weight), + ), child: Image.asset( "asset/image/WT_weight_loss.jpg", height: 180, ), - padding: EdgeInsets.all(0.0), - shape: getShape(changeBloc, GoalsItem.weight), onPressed: () => { setState(() { selected = GoalsItem.muscle; @@ -110,16 +117,18 @@ class _CustomerGoalPage extends State with Trans { }), InkWell( child: Text( - AppLocalizations.of(context).translate("Loose Weight"), + AppLocalizations.of(context)!.translate("Loose Weight"), style: TextStyle(color: Colors.white, fontSize: 32, fontFamily: 'Arial', fontWeight: FontWeight.w900), ), highlightColor: Colors.white, ) ]), Divider(), - RaisedButton( - color: Colors.orange, - textColor: Colors.white, + ElevatedButton( + style: ElevatedButton.styleFrom( + onPrimary: Colors.white, + primary: Colors.orange, + ), child: Text(fulldata ? t("Save") : t("Next")), onPressed: () => { //changingViewModel.saveCustomer(), @@ -137,7 +146,7 @@ class _CustomerGoalPage extends State with Trans { } dynamic getShape(CustomerChangeBloc customerBloc, String goal) { - String selectedGoal = customerBloc.customerRepository.goal; + String selectedGoal = customerBloc.customerRepository.goal!; dynamic returnCode = (selectedGoal == goal) ? RoundedRectangleBorder( side: BorderSide(width: 4, color: Colors.red), diff --git a/lib/view/customer_modify_page.dart b/lib/view/customer_modify_page.dart index 39e84df..dd43ea1 100644 --- a/lib/view/customer_modify_page.dart +++ b/lib/view/customer_modify_page.dart @@ -13,7 +13,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:toggle_switch/toggle_switch.dart'; @@ -26,7 +26,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { @override Widget build(BuildContext context) { - dynamic arguments = ModalRoute.of(context).settings.arguments; + dynamic arguments = ModalRoute.of(context)!.settings.arguments; if (arguments is HashMap && arguments['personal_data'] != null) { fulldata = arguments['personal_data']; } @@ -36,18 +36,21 @@ class CustomerModifyPage extends StatelessWidget with Trans { final accountBloc = BlocProvider.of(context); return BlocProvider( - create: (context) => CustomerChangeBloc(customerRepository: accountBloc.customerRepository, context: context)..add(CustomerLoad()), + create: (context) => CustomerChangeBloc(customerRepository: accountBloc.customerRepository)..add(CustomerLoad()), child: Builder(builder: (context) { // ignore: close_sinks final customerBloc = BlocProvider.of(context); + PreferredSizeWidget _bar = AppBarMin( + back: true, + ); + if (!fulldata) { + _bar = AppBarProgress(max: 25, min: 0); + } + return Scaffold( resizeToAvoidBottomInset: true, - appBar: fulldata - ? AppBarMin( - back: true, - ) - : AppBarProgress(max: 25, min: 0), + appBar: _bar, body: Container( decoration: BoxDecoration( image: DecorationImage( @@ -59,13 +62,8 @@ class CustomerModifyPage extends StatelessWidget with Trans { child: BlocConsumer( listener: (context, state) { if (state is CustomerSaveError) { - String message = t(state.message); - if (message == null) { - message = ""; - } else { - Scaffold.of(context).showSnackBar( - SnackBar(backgroundColor: Colors.orange, content: Text(message, style: TextStyle(color: Colors.white)))); - } + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white)))); } else if (state is CustomerSaveSuccess) { if (fulldata) { Navigator.of(context).pop(); @@ -113,13 +111,14 @@ class CustomerModifyPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 4.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: customerBloc.customerRepository.customer.email, autovalidateMode: AutovalidateMode.always, validator: (val) { - return customerBloc.emailValidation(val); + String? validator = customerBloc.emailValidation(val!); + return validator == null ? null : t(validator); }, keyboardType: TextInputType.emailAddress, style: new TextStyle(fontSize: 16, color: Colors.indigo), @@ -145,13 +144,14 @@ class CustomerModifyPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 1.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: customerBloc.customerRepository.customer.password, autovalidateMode: AutovalidateMode.always, validator: (val) { - return customerBloc.passwordValidation(val); + String? validator = customerBloc.passwordValidation(val!); + return validator == null ? null : t(validator); }, keyboardType: TextInputType.visiblePassword, style: new TextStyle(fontSize: 16, color: Colors.indigo), @@ -170,7 +170,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 1.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: customerBloc.customerRepository.customer.name, @@ -195,7 +195,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 2.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: customerBloc.customerRepository.customer.firstname, @@ -220,7 +220,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { NumberPickerWidget( minValue: 1930, maxValue: 2100, - initalValue: customerBloc.year.toInt(), + initalValue: customerBloc.year!.toInt(), unit: " ", color: Colors.indigo, onChange: (value) => {customerBloc.add(CustomerBirthYearChange(year: value.toInt()))}), @@ -258,7 +258,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { maxValue: 230, initalValue: customerBloc.height.toInt(), unit: " ", - color: Colors.indigo[300], + color: Colors.indigo[300]!, onChange: (value) => {customerBloc.add(CustomerHeightChange(height: value.toInt()))}), SizedBox(width: 80), ], @@ -279,7 +279,7 @@ class CustomerModifyPage extends StatelessWidget with Trans { }, ), Divider(), - FlatButton( + TextButton( onPressed: () => {customerBloc.add(CustomerSave())}, child: Stack( alignment: Alignment.center, @@ -298,9 +298,4 @@ class CustomerModifyPage extends StatelessWidget with Trans { ), ); } - - void showInSnackBar(String error) { - _scaffoldKey.currentState - .showSnackBar(SnackBar(backgroundColor: Colors.orange, content: Text(error, style: TextStyle(color: Colors.white)))); - } } diff --git a/lib/view/customer_welcome_page.dart b/lib/view/customer_welcome_page.dart index e4386e6..09f1364 100644 --- a/lib/view/customer_welcome_page.dart +++ b/lib/view/customer_welcome_page.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class CustomerWelcomePage extends StatefulWidget { - _CustomerWelcomePageState _state; + late _CustomerWelcomePageState _state; _CustomerWelcomePageState createState() { _state = _CustomerWelcomePageState(); @@ -17,21 +17,6 @@ class _CustomerWelcomePageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBarMin(), -/* - title: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - - Image.asset( - 'asset/image/WT_long_logo.png', - fit: BoxFit.cover, - height: 65.0, - ), - ], - ), -*/ - //backgroundColor: Colors.transparent, - //), body: Container( decoration: BoxDecoration( image: DecorationImage( @@ -48,10 +33,12 @@ class _CustomerWelcomePageState extends State { Divider( color: Colors.transparent, ), - RaisedButton( - color: Colors.orange, - textColor: Colors.white, - child: InkWell(child: Text(AppLocalizations.of(context).translate("Next"))), + ElevatedButton( + style: ElevatedButton.styleFrom( + primary: Colors.orange, + onSurface: Colors.white, + ), + child: InkWell(child: Text(AppLocalizations.of(context)!.translate("Next"))), onPressed: () => {Navigator.of(context).pop(), Navigator.of(context).pushNamed("home")}, ) ], diff --git a/lib/view/evaluation.dart b/lib/view/evaluation.dart index c587b08..c799307 100644 --- a/lib/view/evaluation.dart +++ b/lib/view/evaluation.dart @@ -1,6 +1,6 @@ import 'dart:collection'; import 'dart:ui'; - +import 'package:intl/intl.dart'; import 'package:aitrainer_app/bloc/result/result_bloc.dart'; import 'package:aitrainer_app/util/app_language.dart'; import 'package:aitrainer_app/model/cache.dart'; @@ -14,26 +14,25 @@ import 'package:aitrainer_app/widgets/app_bar_min.dart'; import 'package:aitrainer_app/widgets/bottom_nav.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:aitrainer_app/model/result.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class EvaluationPage extends StatelessWidget with Trans { @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + dynamic arguments = ModalRoute.of(context)!.settings.arguments; ExerciseRepository exerciseRepository; - - if (arguments != null) { + if (arguments is LinkedHashMap) { exerciseRepository = arguments['exerciseRepository']; } else { exerciseRepository = ExerciseRepository(); } + ResultType resultType = ResultType.none; String imageUrl = ""; - if (Cache().userLoggedIn.sex == "m") { + if (Cache().userLoggedIn!.sex == "m") { resultType = ResultType.man; imageUrl = 'asset/image/WT_Results_for_men.jpg'; } else { @@ -42,16 +41,16 @@ class EvaluationPage extends StatelessWidget with Trans { } if (arguments['past'] != null && arguments['past'] == true) { - Exercise exercise = arguments['exercise']; + Exercise? exercise = arguments['exercise']; if (exercise != null) { - ExerciseType exerciseType = exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId); + ExerciseType exerciseType = exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId!) as ExerciseType; exerciseRepository.exerciseType = exerciseType; exerciseRepository.exercise = exercise; - String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd); - exerciseRepository.getSameExercise(exercise.exerciseTypeId, exerciseDate); + String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); + exerciseRepository.getSameExercise(exercise.exerciseTypeId!, exerciseDate); } } - if (exerciseRepository.exerciseType.getAbility().equalsTo(ExerciseAbility.running)) { + if (exerciseRepository.exerciseType!.getAbility().equalsTo(ExerciseAbility.running)) { resultType = ResultType.running; imageUrl = 'asset/image/WT_Results_for_runners.jpg'; } @@ -79,7 +78,7 @@ class EvaluationPage extends StatelessWidget with Trans { context: context), child: BlocConsumer(listener: (context, state) { if (state is ResultError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.error, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -97,8 +96,8 @@ class EvaluationPage extends StatelessWidget with Trans { Widget getEvaluationWidgets(ResultBloc resultBloc) { String exerciseName = AppLanguage().appLocal == Locale("en") - ? resultBloc.exerciseRepository.exerciseType.name - : resultBloc.exerciseRepository.exerciseType.nameTranslation; + ? resultBloc.exerciseRepository.exerciseType!.name + : resultBloc.exerciseRepository.exerciseType!.nameTranslation; return Container( padding: EdgeInsets.only(left: 10, right: 10), child: CustomScrollView(scrollDirection: Axis.vertical, slivers: [ @@ -134,7 +133,7 @@ class EvaluationPage extends StatelessWidget with Trans { ), SliverList( delegate: SliverChildListDelegate([ - Text(DateFormat('y-M-d HH:mm', AppLanguage().appLocal.toString()).format(resultBloc.exerciseRepository.start), + Text(DateFormat('y-M-d HH:mm', AppLanguage().appLocal.toString()).format(resultBloc.exerciseRepository.start!), textAlign: TextAlign.center, maxLines: 2, softWrap: true, @@ -188,7 +187,7 @@ class EvaluationPage extends StatelessWidget with Trans { } Widget getSuggestionTitle(ResultBloc resultBloc) { - if (resultBloc.exerciseRepository.exerciseType.unitQuantityUnit != null) { + if (resultBloc.exerciseRepository.exerciseType!.unitQuantityUnit != null) { return SliverList( delegate: SliverChildListDelegate( [ @@ -254,7 +253,7 @@ class EvaluationPage extends StatelessWidget with Trans { } Widget getSuggestion(ResultBloc resultBloc) { - if (resultBloc.exerciseRepository.exerciseType.unitQuantityUnit != null) { + if (resultBloc.exerciseRepository.exerciseType!.unitQuantityUnit != null) { return SliverList( delegate: SliverChildListDelegate( [ @@ -282,9 +281,9 @@ class EvaluationPage extends StatelessWidget with Trans { } Widget getSuggestionWidget(ResultBloc resultBloc, String title, String picture, String repeats, double percent, String restTime) { - String unitQuantityUnit = resultBloc.exerciseRepository.exerciseType.unitQuantityUnit == null + String unitQuantityUnit = resultBloc.exerciseRepository.exerciseType!.unitQuantityUnit == null ? "" - : resultBloc.exerciseRepository.exerciseType.unitQuantityUnit; + : resultBloc.exerciseRepository.exerciseType!.unitQuantityUnit!; return Column( children: [ Text(t(title), @@ -399,19 +398,19 @@ class EvaluationPage extends StatelessWidget with Trans { Widget getSummary(ResultBloc bloc) { int index = 0; - List resultList = List(); + List resultList = []; - bloc.exerciseRepository.actualExerciseList.forEach((actual) { + bloc.exerciseRepository.actualExerciseList!.forEach((actual) { //final String unit = t(bloc.exerciseRepository.exerciseType.unit); - final String unit = bloc.exerciseRepository.exerciseType.unitQuantityUnit != null - ? bloc.exerciseRepository.exerciseType.unitQuantityUnit - : bloc.exerciseRepository.exerciseType.unit; + final String unit = bloc.exerciseRepository.exerciseType!.unitQuantityUnit != null + ? bloc.exerciseRepository.exerciseType!.unitQuantityUnit! + : bloc.exerciseRepository.exerciseType!.unit; String exerciseElement = ""; - String exerciseRepeats = actual.quantity.toStringAsFixed(0); - if (bloc.exerciseRepository.exerciseType.unit == "second") { - exerciseRepeats = bloc.printTime(actual.quantity); + String exerciseRepeats = actual.quantity!.toStringAsFixed(0); + if (bloc.exerciseRepository.exerciseType!.unit == "second") { + exerciseRepeats = bloc.printTime(actual.quantity!); } - final String exerciseUnitQuantity = actual.unitQuantity != null ? "x" + actual.unitQuantity.toStringAsFixed(0) : ""; + final String exerciseUnitQuantity = actual.unitQuantity != null ? "x" + actual.unitQuantity!.toStringAsFixed(0) : ""; if (index == 0) { exerciseElement = t("Test") + ": "; } else if (index == 1) { @@ -471,7 +470,7 @@ class EvaluationPage extends StatelessWidget with Trans { } List getResultData(ResultBloc resultBloc) { - List data = List(); + List data = []; resultBloc.resultRepository.getResults().forEach((element) { data.add(getResultWidget(element)); @@ -480,8 +479,8 @@ class EvaluationPage extends StatelessWidget with Trans { } Widget getResultWidget(ResultExt element) { - bool hasHardware = Cache().hasHardware; - bool blur = (!hasHardware && element.isHardware()); + bool? hasHardware = Cache().hasHardware; + bool blur = (hasHardware != null && !hasHardware && element.isHardware()!); /* print("Blur: " + element.getDescription() + ": " + @@ -518,7 +517,7 @@ class EvaluationPage extends StatelessWidget with Trans { style: GoogleFonts.archivoBlack(fontSize: 28, color: blur ? Colors.white12 : Colors.white), ), Text( - t(element.getDescription()), + t(element.getDescription()!), style: GoogleFonts.archivoBlack(fontSize: 14, color: blur ? Colors.white12 : Colors.white), textAlign: TextAlign.left, ), diff --git a/lib/view/exercise_control_page.dart b/lib/view/exercise_control_page.dart index c94661c..8ac9c69 100644 --- a/lib/view/exercise_control_page.dart +++ b/lib/view/exercise_control_page.dart @@ -14,9 +14,8 @@ import 'package:aitrainer_app/widgets/timer_widget.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExerciseControlPage extends StatefulWidget { _ExerciseControlPage createState() => _ExerciseControlPage(); @@ -34,7 +33,7 @@ class _ExerciseControlPage extends State with Trans { @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; final ExerciseRepository exerciseRepository = arguments['exerciseRepository']; final bool readonly = arguments['readonly']; setContext(context); @@ -46,7 +45,7 @@ class _ExerciseControlPage extends State with Trans { ..add(ExerciseControlLoad()), child: BlocConsumer(listener: (context, state) { if (state is ExerciseControlError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -67,8 +66,8 @@ class _ExerciseControlPage extends State with Trans { Form getControlForm(ExerciseControlBloc exerciseBloc, TimerBloc timerBloc) { this.offset = exerciseBloc.scrollOffset; String exerciseName = AppLanguage().appLocal == Locale("en") - ? exerciseBloc.exerciseRepository.exerciseType.name - : exerciseBloc.exerciseRepository.exerciseType.nameTranslation; + ? exerciseBloc.exerciseRepository.exerciseType!.name + : exerciseBloc.exerciseRepository.exerciseType!.nameTranslation; return Form( child: Scaffold( resizeToAvoidBottomInset: true, @@ -79,7 +78,7 @@ class _ExerciseControlPage extends State with Trans { alignment: Alignment.center, decoration: BoxDecoration( image: DecorationImage( - image: Cache().userLoggedIn.sex == "m" + image: Cache().userLoggedIn!.sex == "m" ? AssetImage("asset/image/WT_Results_for_men.jpg") : AssetImage("asset/image/WT_Results_for_female.jpg"), fit: BoxFit.cover, @@ -156,7 +155,7 @@ class _ExerciseControlPage extends State with Trans { " " + exerciseBloc.initialRM.toStringAsFixed(0) + " " + - exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit, + exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit!, style: GoogleFonts.inter( color: Colors.yellow[300], fontSize: 18, @@ -242,7 +241,7 @@ class _ExerciseControlPage extends State with Trans { } List getButton(int step, ExerciseControlBloc exerciseBloc) { - List widgets = List(); + List widgets = []; if (step < exerciseBloc.step) { widgets.add(Icon( CustomIcon.check_circle, @@ -289,8 +288,9 @@ class _ExerciseControlPage extends State with Trans { children: [ TextSpan(text: t("Please repeat with ")), TextSpan( - text: - exerciseBloc.unitQuantity.toStringAsFixed(0) + " " + exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit, + text: exerciseBloc.unitQuantity.toStringAsFixed(0) + + " " + + exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit!, style: GoogleFonts.inter( decoration: TextDecoration.underline, fontSize: 16, @@ -320,12 +320,14 @@ class _ExerciseControlPage extends State with Trans { maxValue: 200, initalValue: exerciseBloc.quantity.round(), unit: t("reps"), - color: Colors.yellow[50], + color: Colors.yellow[50]!, onChange: (value) => {exerciseBloc.add(ExerciseControlQuantityChange(quantity: value.toDouble(), step: step))}), - FlatButton( - padding: EdgeInsets.all(0), - textColor: Colors.white, - focusColor: Colors.blueAccent, + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(0), + primary: Colors.white, + onSurface: Colors.blueAccent, + ), onPressed: () => { exerciseBloc.add(ExerciseControlSubmit(step: step)), if (step == 3) @@ -364,13 +366,13 @@ class _ExerciseControlPage extends State with Trans { class UnitQuantityControl extends StatefulWidget { final ExerciseControlBloc exerciseBloc; final int step; - const UnitQuantityControl({this.exerciseBloc, this.step}); + const UnitQuantityControl({required this.exerciseBloc, required this.step}); @override _UnitQuantityControlState createState() => _UnitQuantityControlState(); } class _UnitQuantityControlState extends State with Trans { - double changedValue; + late double changedValue; @override Widget build(BuildContext context) { changedValue = widget.exerciseBloc.unitQuantity; @@ -428,7 +430,7 @@ class _UnitQuantityControlState extends State with Trans { maxValue: (widget.exerciseBloc.unitQuantity + 10).round(), initalValue: widget.exerciseBloc.unitQuantity.round(), unit: t("kg"), - color: Colors.yellow[50], + color: Colors.yellow[50]!, onChange: (value) => {changedValue = value}), Align( alignment: Alignment.center, diff --git a/lib/view/exercise_execute_page.dart b/lib/view/exercise_execute_page.dart index a6802aa..af92f1d 100644 --- a/lib/view/exercise_execute_page.dart +++ b/lib/view/exercise_execute_page.dart @@ -21,21 +21,21 @@ class ExerciseExecutePage extends StatefulWidget { class _ExerciseExecutePage extends State with Trans { final GlobalKey _scaffoldKey = new GlobalKey(); // ignore: close_sinks - ExerciseExecutePlanBloc bloc; + late ExerciseExecutePlanBloc bloc; @override void initState() { super.initState(); /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { BlocProvider.of(context).add(ExerciseByPlanLoad()); }); } @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; final int customerId = arguments['customerId']; bloc = BlocProvider.of(context); bloc.customerId = customerId; @@ -48,7 +48,7 @@ class _ExerciseExecutePage extends State with Trans { padding: EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( - image: customerId == Cache().userLoggedIn.customerId + image: customerId == Cache().userLoggedIn!.customerId ? AssetImage('asset/image/WT_black_background.jpg') : AssetImage('asset/image/WT_light_background.jpg'), fit: BoxFit.cover, @@ -58,7 +58,7 @@ class _ExerciseExecutePage extends State with Trans { child: BlocConsumer(listener: (context, state) { if (state is ExerciseByPlanError) { //LoadingDialog.hide(context); - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( state.message, ), @@ -89,7 +89,7 @@ class _ExerciseExecutePage extends State with Trans { } List nodeExercisePlan(ExerciseExecutePlanBloc bloc) { - List exerciseTypes = List(); + List exerciseTypes = []; Card explanation = Card( color: Colors.white38, child: Container( @@ -145,7 +145,7 @@ class _ExerciseExecutePage extends State with Trans { child: InkWell( onTap: () { final LinkedHashMap args = LinkedHashMap(); - args['customerId'] = Cache().userLoggedIn.customerId; + args['customerId'] = Cache().userLoggedIn!.customerId; Navigator.of(context).pop(); Navigator.of(context).pushNamed('exercisePlanCustomPage', arguments: args); }, @@ -169,7 +169,7 @@ class _ExerciseExecutePage extends State with Trans { } List _getChildList(List listWorkoutTree, ExerciseExecutePlanBloc bloc) { - List list = List(); + List list = []; listWorkoutTree.forEach((element) { if (element.selected) { list.add(TreeViewChild( diff --git a/lib/view/exercise_execute_plan_add_page.dart b/lib/view/exercise_execute_plan_add_page.dart index 3b3b37f..fe2d46e 100644 --- a/lib/view/exercise_execute_plan_add_page.dart +++ b/lib/view/exercise_execute_plan_add_page.dart @@ -12,9 +12,8 @@ import 'package:aitrainer_app/widgets/number_picker.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExerciseExecutePlanAddPage extends StatefulWidget { _ExerciseExecuteAddPage createState() => _ExerciseExecuteAddPage(); @@ -32,7 +31,7 @@ class _ExerciseExecuteAddPage extends State with Tra @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; // ignore: close_sinks final ExerciseExecutePlanBloc planBloc = arguments['blocExerciseByPlan']; final int customerId = arguments['customerId']; @@ -49,7 +48,7 @@ class _ExerciseExecuteAddPage extends State with Tra planBloc: planBloc), child: BlocConsumer(listener: (context, state) { if (state is ExerciseExecutePlanAddError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -70,8 +69,8 @@ class _ExerciseExecuteAddPage extends State with Tra Form getControlForm(ExerciseExecutePlanAddBloc exerciseBloc) { String exerciseName = AppLanguage().appLocal == Locale("en") - ? exerciseBloc.exerciseRepository.exerciseType.name - : exerciseBloc.exerciseRepository.exerciseType.nameTranslation; + ? exerciseBloc.exerciseRepository.exerciseType!.name + : exerciseBloc.exerciseRepository.exerciseType!.nameTranslation; return Form( child: Scaffold( @@ -136,7 +135,7 @@ class _ExerciseExecuteAddPage extends State with Tra } List repeatExercises(ExerciseExecutePlanAddBloc exerciseBloc) { - List listColumns = List(); + List listColumns = []; for (int i = 0; i < exerciseBloc.countSteps; i++) { Column col = Column( mainAxisAlignment: MainAxisAlignment.spaceAround, @@ -181,29 +180,31 @@ class _ExerciseExecuteAddPage extends State with Tra color: Colors.transparent, ), Row(mainAxisAlignment: MainAxisAlignment.start, children: [ - exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit == null + exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit == null ? Offstage() : NumberPickerWidget( minValue: 0, maxValue: 1000, fontSize: 16, initalValue: exerciseBloc.unitQuantity.toInt(), - unit: t(exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit), - color: Colors.yellow[50], + unit: t(exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit!), + color: Colors.yellow[50]!, onChange: (value) => {exerciseBloc.add(ExerciseExecutePlanAddChangeUnitQuantity(quantity: value.toDouble()))}), NumberPickerWidget( minValue: 0, maxValue: 200, fontSize: 16, initalValue: exerciseBloc.quantity.toInt(), - unit: t(exerciseBloc.exerciseRepository.exerciseType.unit), //t("repeat"), - color: Colors.yellow[50], + unit: t(exerciseBloc.exerciseRepository.exerciseType!.unit), //t("repeat"), + color: Colors.yellow[50]!, onChange: (value) => {exerciseBloc.add(ExerciseExecutePlanAddChangeQuantity(quantity: value.toDouble()))}), ]), - FlatButton( - padding: EdgeInsets.all(0), - textColor: Colors.white, - focusColor: Colors.blueAccent, + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(0), + primary: Colors.white, + onSurface: Colors.blueAccent, + ), onPressed: () => { if (exerciseBloc.step == i + 1) {exerciseBloc.add(ExerciseExecutePlanAddSubmit())}, if (i + 1 == exerciseBloc.countSteps) {Navigator.of(context).pop()} @@ -260,7 +261,7 @@ class _ExerciseExecuteAddPage extends State with Tra } List getButton(int step, ExerciseExecutePlanAddBloc exerciseBloc) { - List widgets = List(); + List widgets = []; if (step < exerciseBloc.step) { widgets.add(Icon( CustomIcon.check_circle, diff --git a/lib/view/exercise_log_page.dart b/lib/view/exercise_log_page.dart index 219b8ad..288fede 100644 --- a/lib/view/exercise_log_page.dart +++ b/lib/view/exercise_log_page.dart @@ -17,7 +17,7 @@ import 'package:aitrainer_app/util/common.dart'; import 'package:aitrainer_app/util/trans.dart'; import 'package:flutter/material.dart'; import 'package:aitrainer_app/widgets/treeview_parent_widget.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExerciseLogPage extends StatefulWidget { @override @@ -27,7 +27,7 @@ class ExerciseLogPage extends StatefulWidget { class _ExerciseLogPage extends State with Trans, Common { @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; final int customerId = arguments['customerId']; setContext(context); @@ -35,7 +35,7 @@ class _ExerciseLogPage extends State with Trans, Common { create: (context) => ExerciseLogBloc(exerciseRepository: ExerciseRepository())..add(ExerciseLogLoad()), child: BlocConsumer(listener: (context, state) { if (state is ExerciseLogError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -57,7 +57,7 @@ class _ExerciseLogPage extends State with Trans, Common { padding: EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( - image: customerId == Cache().userLoggedIn.customerId + image: customerId == Cache().userLoggedIn!.customerId ? AssetImage('asset/image/WT_black_background.jpg') : AssetImage('asset/image/WT_light_background.jpg'), fit: BoxFit.cover, @@ -80,15 +80,15 @@ class _ExerciseLogPage extends State with Trans, Common { List _getTreeChildren(ExerciseLogBloc exerciseLogBloc, int customerId) { final ExerciseRepository exerciseRepository = exerciseLogBloc.exerciseRepository; - if (customerId == Cache().userLoggedIn.customerId) { + if (customerId == Cache().userLoggedIn!.customerId) { exerciseRepository.exerciseList = exerciseRepository.getExerciseList(); - } else if (Cache().getTrainee() != null && customerId == Cache().getTrainee().customerId) { + } else if (Cache().getTrainee() != null && customerId == Cache().getTrainee()!.customerId) { exerciseRepository.exerciseList = exerciseRepository.getExerciseListTrainee(); } //print("ExerciseList ${exerciseRepository.exerciseList}"); exerciseRepository.sortByDate(); - List listWidget = List(); + List listWidget = []; Card explanation = Card( color: Colors.white60, @@ -121,10 +121,10 @@ class _ExerciseLogPage extends State with Trans, Common { ))); listWidget.add(explanation); - List listExercises = List(); + List listExercises = []; String origDate = ""; - exerciseRepository.exerciseLogList.forEach((exercise) { - String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd); + exerciseRepository.exerciseLogList!.forEach((exercise) { + String exerciseDate = DateFormat("yyyy-MM-dd", AppLanguage().appLocal.toString()).format(exercise.dateAdd!); if (origDate != exerciseDate) { if (origDate.length == 0) { @@ -138,7 +138,7 @@ class _ExerciseLogPage extends State with Trans, Common { parent: TreeviewParentWidget(text: origDate), children: _getChildList(listExercises, exerciseRepository, exerciseLogBloc), ))); - listExercises = List(); + listExercises = []; listExercises.add(exercise); origDate = exerciseDate; } @@ -162,12 +162,12 @@ class _ExerciseLogPage extends State with Trans, Common { } List _getChildList(List listExercises, ExerciseRepository exerciseRepository, ExerciseLogBloc exerciseLogBloc) { - List list = List(); + List list = []; bool isEnglish = AppLanguage().appLocal == Locale('en'); listExercises.forEach((exercise) { - ExerciseType exerciseType = exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId); - String exerciseName = isEnglish ? exerciseType.name : exerciseType.nameTranslation; + ExerciseType? exerciseType = exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId!); + String exerciseName = isEnglish ? exerciseType!.name : exerciseType!.nameTranslation; list.add( Card( @@ -193,7 +193,7 @@ class _ExerciseLogPage extends State with Trans, Common { fit: FlexFit.tight, flex: 20, child: Text( - exercise.summary == null ? "" : exercise.summary, + exercise.summary == null ? "" : exercise.summary!, style: TextStyle(fontSize: 12, color: Colors.blue[800]), )), IconButton( @@ -241,14 +241,14 @@ class _ExerciseLogPage extends State with Trans, Common { } void confirmationDialog(ExerciseLogBloc bloc, Exercise exercise) { - ExerciseType exerciseType = bloc.exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId); - String exerciseName = AppLanguage().appLocal == Locale("en") ? exerciseType.name : exerciseType.nameTranslation; + ExerciseType? exerciseType = bloc.exerciseRepository.getExerciseTypeById(exercise.exerciseTypeId!); + String exerciseName = AppLanguage().appLocal == Locale("en") ? exerciseType!.name : exerciseType!.nameTranslation; String strDate = AppLanguage().appLocal == Locale("en") - ? "on the " + DateFormat(DateFormat.YEAR_MONTH_DAY, AppLanguage().appLocal.toString()).format(exercise.dateAdd.toUtc()) - : DateFormat(DateFormat.YEAR_MONTH_DAY, AppLanguage().appLocal.toString()).format(exercise.dateAdd.toUtc()) + "-n"; + ? "on the " + DateFormat(DateFormat.YEAR_MONTH_DAY, AppLanguage().appLocal.toString()).format(exercise.dateAdd!.toUtc()) + : DateFormat(DateFormat.YEAR_MONTH_DAY, AppLanguage().appLocal.toString()).format(exercise.dateAdd!.toUtc()) + "-n"; - final String unitQuantity = exercise.unitQuantity == null ? "" : "x" + exercise.unitQuantity.toStringAsFixed(0); + final String unitQuantity = exercise.unitQuantity == null ? "" : "x" + exercise.unitQuantity!.toStringAsFixed(0); showCupertinoDialog( useRootNavigator: true, @@ -263,7 +263,7 @@ class _ExerciseLogPage extends State with Trans, Common { style: (TextStyle(color: Colors.blue)), ), Text( - exercise.quantity.toStringAsFixed(0) + unitQuantity + " ", + exercise.quantity!.toStringAsFixed(0) + unitQuantity + " ", //+ //exerciseType.unitQuantityUnit == null // ? "" @@ -276,11 +276,11 @@ class _ExerciseLogPage extends State with Trans, Common { ), ]), actions: [ - FlatButton( + TextButton( child: Text(t("No")), onPressed: () => Navigator.pop(context), ), - FlatButton( + TextButton( child: Text(t("Yes")), onPressed: () { Navigator.pop(context); diff --git a/lib/view/exercise_new_page.dart b/lib/view/exercise_new_page.dart index 28ea790..e142322 100644 --- a/lib/view/exercise_new_page.dart +++ b/lib/view/exercise_new_page.dart @@ -20,9 +20,8 @@ import 'package:aitrainer_app/widgets/size_widget.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExerciseNewPage extends StatefulWidget { _ExerciseNewPageState createState() => _ExerciseNewPageState(); @@ -31,7 +30,7 @@ class ExerciseNewPage extends StatefulWidget { class _ExerciseNewPageState extends State with Trans, Logging { @override Widget build(BuildContext context) { - final ExerciseType exerciseType = ModalRoute.of(context).settings.arguments; + final ExerciseType exerciseType = ModalRoute.of(context)!.settings.arguments as ExerciseType; // ignore: close_sinks final menuBloc = BlocProvider.of(context); setContext(context); @@ -46,23 +45,22 @@ class _ExerciseNewPageState extends State with Trans, Logging { child: BlocConsumer( listener: (context, state) { if (state is ExerciseNewError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is ExerciseNewSaved) { final LinkedHashMap args = LinkedHashMap(); // ignore: close_sinks - final TestSetExecuteBloc executeBloc = BlocProvider.of(context); - print("Execute paralell $exerciseType paralell: ${executeBloc.paralellTest}"); + final TestSetExecuteBloc? executeBloc = BlocProvider.of(context); if (executeBloc != null && executeBloc.existsActivePlan() == true) { Navigator.of(context).pushNamed("testSetExecute"); } else { // ignore: close_sinks final bloc = BlocProvider.of(context); - if (bloc.exerciseRepository.exerciseType.unitQuantityUnit == null) { + if (bloc.exerciseRepository.exerciseType!.unitQuantityUnit == null) { args['exerciseRepository'] = bloc.exerciseRepository; Navigator.of(context).pushNamed('evaluationPage', arguments: args); - } else if (menuBloc.ability.equalsTo(ExerciseAbility.oneRepMax)) { + } else if (menuBloc.ability!.equalsTo(ExerciseAbility.oneRepMax)) { args['exerciseRepository'] = bloc.exerciseRepository; args['percent'] = 0.75; args['readonly'] = false; @@ -85,13 +83,13 @@ class _ExerciseNewPageState extends State with Trans, Logging { } Widget getExerciseSaveWidget(ExerciseNewBloc exerciseBloc, ExerciseType exerciseType, MenuBloc menuBloc) { - if (exerciseBloc.exerciseRepository.exerciseType.name == "BMR") { + if (exerciseBloc.exerciseRepository.exerciseType!.name == "BMR") { return BMR(exerciseBloc: exerciseBloc); } - if (exerciseBloc.exerciseRepository.exerciseType.name == "BMI") { + if (exerciseBloc.exerciseRepository.exerciseType!.name == "BMI") { return BMI(exerciseBloc: exerciseBloc); } - if (exerciseBloc.exerciseRepository.exerciseType.name == "Sizes") { + if (exerciseBloc.exerciseRepository.exerciseType!.name == "Sizes") { return SizeWidget(exerciseBloc: exerciseBloc); } @@ -107,12 +105,12 @@ class _ExerciseNewPageState extends State with Trans, Logging { ), ), child: ExerciseSave( - exerciseName: exerciseBloc.exerciseRepository.exerciseType.nameTranslation, - exerciseDescription: exerciseBloc.exerciseRepository.exerciseType.descriptionTranslation, + exerciseName: exerciseBloc.exerciseRepository.exerciseType!.nameTranslation, + exerciseDescription: exerciseBloc.exerciseRepository.exerciseType!.descriptionTranslation, exerciseTask: t("Please take a relative bigger weight and repeat 12-20 times"), - unit: exerciseBloc.exerciseRepository.exerciseType.unit, - unitQuantityUnit: exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit, - hasUnitQuantity: exerciseBloc.exerciseRepository.exerciseType.unitQuantityUnit != null, + unit: exerciseBloc.exerciseRepository.exerciseType!.unit, + unitQuantityUnit: exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit, + hasUnitQuantity: exerciseBloc.exerciseRepository.exerciseType!.unitQuantityUnit != null, onQuantityChanged: (value) { exerciseBloc.add(ExerciseNewQuantityChange(quantity: double.parse(value))); }, @@ -138,7 +136,7 @@ class _ExerciseNewPageState extends State with Trans, Logging { void save(ExerciseNewBloc bloc, MenuBloc menuBloc) { // ignore: close_sinks - final TestSetExecuteBloc executeBloc = BlocProvider.of(context); + final TestSetExecuteBloc? executeBloc = BlocProvider.of(context); if (executeBloc != null && executeBloc.existsActivePlan() == true) { confirmationOverride(bloc); @@ -148,19 +146,19 @@ class _ExerciseNewPageState extends State with Trans, Logging { } void confirmationSave(ExerciseNewBloc bloc, MenuBloc menuBloc) { - if (bloc.exerciseRepository.exercise.quantity == null) { + if (bloc.exerciseRepository.exercise!.quantity == null) { return; } - String quantity = bloc.exerciseRepository.exercise.quantity % 1 == 0 - ? bloc.exerciseRepository.exercise.quantity.round().toString() - : bloc.exerciseRepository.exercise.quantity.toString(); + String quantity = bloc.exerciseRepository.exercise!.quantity! % 1 == 0 + ? bloc.exerciseRepository.exercise!.quantity!.round().toString() + : bloc.exerciseRepository.exercise!.quantity!.toString(); String unitQuantity = ""; - if (bloc.exerciseRepository.exercise.unitQuantity != null) { - unitQuantity = bloc.exerciseRepository.exercise.unitQuantity % 1 == 0 - ? bloc.exerciseRepository.exercise.unitQuantity.round().toString() - : bloc.exerciseRepository.exercise.unitQuantity.toString(); + if (bloc.exerciseRepository.exercise!.unitQuantity != null) { + unitQuantity = bloc.exerciseRepository.exercise!.unitQuantity! % 1 == 0 + ? bloc.exerciseRepository.exercise!.unitQuantity!.round().toString() + : bloc.exerciseRepository.exercise!.unitQuantity.toString(); } // ignore: close_sinks @@ -174,34 +172,34 @@ class _ExerciseNewPageState extends State with Trans, Logging { content: Column(children: [ Divider(), Text( - t("Exercise") + ": " + bloc.exerciseRepository.exerciseType.name, + t("Exercise") + ": " + bloc.exerciseRepository.exerciseType!.name, style: (TextStyle(color: Colors.blue)), ), Text( - quantity + " " + t(bloc.exerciseRepository.exerciseType.unit), + quantity + " " + t(bloc.exerciseRepository.exerciseType!.unit), style: (TextStyle(color: Colors.deepOrange)), ), Text( - bloc.exerciseRepository.exerciseType.unitQuantity == "1" - ? t("with") + " " + unitQuantity + " " + t(bloc.exerciseRepository.exerciseType.unitQuantityUnit) + bloc.exerciseRepository.exerciseType!.unitQuantity == "1" + ? t("with") + " " + unitQuantity + " " + t(bloc.exerciseRepository.exerciseType!.unitQuantityUnit!) : "", style: (TextStyle(color: Colors.deepOrange)), ), ]), actions: [ - FlatButton( + TextButton( child: Text(t("No")), onPressed: () => Navigator.pop(context), ), - FlatButton( + TextButton( child: Text(t("Yes")), onPressed: () { saveAll(bloc); if (executeBloc.existsActivePlan() == true) { executeBloc.add(TestSetExecuteExerciseFinished( - exerciseTypeId: bloc.exerciseRepository.exerciseType.exerciseTypeId, - quantity: bloc.exerciseRepository.exercise.quantity, - unitQuantity: bloc.exerciseRepository.exercise.unitQuantity)); + exerciseTypeId: bloc.exerciseRepository.exerciseType!.exerciseTypeId, + quantity: bloc.exerciseRepository.exercise!.quantity!, + unitQuantity: bloc.exerciseRepository.exercise!.unitQuantity!)); } Navigator.pop(context); }, @@ -211,7 +209,7 @@ class _ExerciseNewPageState extends State with Trans, Logging { } void saveAll(ExerciseNewBloc bloc) { - bloc.exerciseRepository.setCustomer(Cache().userLoggedIn); + bloc.exerciseRepository.setCustomer(Cache().userLoggedIn!); bloc.add(ExerciseNewSubmit()); } @@ -228,11 +226,11 @@ class _ExerciseNewPageState extends State with Trans, Logging { Text(t("Do you want to override it?"), style: GoogleFonts.archivoBlack(fontSize: 16, color: Colors.blue[800])), ]), actions: [ - FlatButton( + TextButton( child: Text(t("No"), style: GoogleFonts.archivoBlack(fontSize: 16, color: Colors.blue[800])), onPressed: () => Navigator.pop(context), ), - FlatButton( + TextButton( child: Text(t("Yes"), style: GoogleFonts.archivoBlack(fontSize: 16, color: Colors.red[800])), onPressed: () { Navigator.pop(context); diff --git a/lib/view/exercise_plan_custom_detail_add_page.dart b/lib/view/exercise_plan_custom_detail_add_page.dart index d9349dc..eae32a3 100644 --- a/lib/view/exercise_plan_custom_detail_add_page.dart +++ b/lib/view/exercise_plan_custom_detail_add_page.dart @@ -10,12 +10,11 @@ import 'package:aitrainer_app/widgets/app_bar.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:keyboard_actions/keyboard_actions.dart'; import 'package:keyboard_actions/keyboard_actions_config.dart'; import 'package:keyboard_actions/keyboard_actions_item.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExercisePlanDetailAddPage extends StatefulWidget { @override @@ -92,7 +91,7 @@ class _ExercisePlanDetailAddPage extends State with T @override Widget build(BuildContext context) { - LinkedHashMap args = ModalRoute.of(context).settings.arguments; + LinkedHashMap args = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; // ignore: close_sinks final ExercisePlanBloc planBloc = args['bloc']; final WorkoutMenuTree workoutMenuTree = args['workoutTreeItem']; @@ -106,7 +105,7 @@ class _ExercisePlanDetailAddPage extends State with T child: BlocConsumer( listener: (context, state) { if (state is ExercisePlanCustomAddError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, @@ -126,17 +125,20 @@ class _ExercisePlanDetailAddPage extends State with T Widget getForm(ExercisePlanCustomAddBloc bloc, WorkoutMenuTree workoutMenuTree) { String exerciseName = ""; - if (bloc != null) { - exerciseName = AppLanguage().appLocal == Locale("en") - ? bloc.exercisePlanRepository.getActualPlanDetail().exerciseType.name - : bloc.exercisePlanRepository.getActualPlanDetail().exerciseType.nameTranslation; + if (bloc.exercisePlanRepository.getActualPlanDetail() == null || bloc.serie == null) { + return Offstage(); } - final bool weightVisible = bloc.exercisePlanRepository.getActualPlanDetail().exerciseType.unitQuantityUnit != null; - String summary = bloc.serie.toStringAsFixed(0) + " x " + bloc.quantity.toStringAsFixed(0); + + exerciseName = AppLanguage().appLocal == Locale("en") + ? bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.name + : bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.nameTranslation; + + final bool weightVisible = bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.unitQuantityUnit != null; + String summary = bloc.serie!.toStringAsFixed(0) + " x " + bloc.quantity.toStringAsFixed(0); if (bloc.quantityUnit > 0) { summary += " x " + bloc.quantityUnit.toStringAsFixed(0) + " kg"; } - final String unit = bloc.exercisePlanRepository.getActualPlanDetail().exerciseType.unit; + final String unit = bloc.exercisePlanRepository.getActualPlanDetail()!.exerciseType!.unit; return Form( child: Scaffold( resizeToAvoidBottomInset: true, @@ -191,7 +193,7 @@ class _ExercisePlanDetailAddPage extends State with T borderSide: BorderSide(color: Colors.black26, width: 0.4), ), ), - initialValue: bloc.serie.toStringAsFixed(0), + initialValue: bloc.serie!.toStringAsFixed(0), focusNode: _nodeText1, keyboardType: TextInputType.number, style: GoogleFonts.archivoBlack(fontSize: 60, color: Colors.yellow[200]), @@ -209,7 +211,7 @@ class _ExercisePlanDetailAddPage extends State with T border: OutlineInputBorder( gapPadding: 4.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), focusNode: _nodeText2, @@ -231,7 +233,7 @@ class _ExercisePlanDetailAddPage extends State with T border: OutlineInputBorder( gapPadding: 2.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), focusNode: _nodeText3, @@ -251,7 +253,7 @@ class _ExercisePlanDetailAddPage extends State with T Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - FlatButton( + TextButton( onPressed: () => { bloc.add(ExercisePlanCustomAddRemove()), Navigator.of(context).pop(), @@ -267,7 +269,7 @@ class _ExercisePlanDetailAddPage extends State with T ], ), ), - FlatButton( + TextButton( onPressed: () => { bloc.add(ExercisePlanCustomAddSubmit()), Navigator.of(context).pop(), diff --git a/lib/view/exercise_plan_custom_page.dart b/lib/view/exercise_plan_custom_page.dart index 1ac5615..963189b 100644 --- a/lib/view/exercise_plan_custom_page.dart +++ b/lib/view/exercise_plan_custom_page.dart @@ -14,7 +14,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class ExercisePlanCustomPage extends StatefulWidget { @override @@ -24,21 +24,21 @@ class ExercisePlanCustomPage extends StatefulWidget { class _ExercisePlanCustomPage extends State with Trans { final GlobalKey _scaffoldKey = new GlobalKey(); // ignore: close_sinks - ExercisePlanBloc bloc; + late ExercisePlanBloc bloc; @override void initState() { super.initState(); /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { BlocProvider.of(context).add(ExercisePlanLoad()); }); } @override Widget build(BuildContext context) { - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; final int customerId = arguments['customerId']; bloc = BlocProvider.of(context); bloc.customerId = customerId; @@ -51,7 +51,7 @@ class _ExercisePlanCustomPage extends State with Trans { padding: EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( - image: customerId == Cache().userLoggedIn.customerId + image: customerId == Cache().userLoggedIn!.customerId ? AssetImage('asset/image/WT_black_background.jpg') : AssetImage('asset/image/WT_light_background.jpg'), fit: BoxFit.cover, @@ -60,7 +60,7 @@ class _ExercisePlanCustomPage extends State with Trans { ), child: BlocConsumer(listener: (context, state) { if (state is ExercisePlanError) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( state.message, ), @@ -88,7 +88,7 @@ class _ExercisePlanCustomPage extends State with Trans { } List _getTreeChildren(ExercisePlanBloc bloc) { - List exerciseTypes = List(); + List exerciseTypes = []; Card explanation = Card( color: Colors.white60, @@ -135,10 +135,10 @@ class _ExercisePlanCustomPage extends State with Trans { } List _getChildList(List listWorkoutTree, ExercisePlanBloc bloc) { - List list = List(); + List list = []; listWorkoutTree.forEach((element) { final String unitQuantityUnit = - element.exerciseType != null && element.exerciseType.unitQuantityUnit != null ? element.exerciseType.unitQuantityUnit : ""; + element.exerciseType != null && element.exerciseType!.unitQuantityUnit != null ? element.exerciseType!.unitQuantityUnit! : ""; list.add(TreeViewChild( startExpanded: false, parent: Card( @@ -175,12 +175,12 @@ class _ExercisePlanCustomPage extends State with Trans { InkWell( child: !element.selected || bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId] == null || - bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].change == null + bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId]!.change == null ? Text("") : Text( - bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].repeats.toString() + + bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId]!.repeats.toString() + " x " + - bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId].weightEquation + + bloc.exercisePlanRepository.exercisePlanDetails[element.exerciseTypeId]!.weightEquation! + unitQuantityUnit, style: TextStyle(fontSize: 9, color: Colors.green), ), diff --git a/lib/view/exercise_type_description.dart b/lib/view/exercise_type_description.dart deleted file mode 100644 index 4f2d9f1..0000000 --- a/lib/view/exercise_type_description.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'package:aitrainer_app/util/app_language.dart'; -import 'package:aitrainer_app/repository/exercise_repository.dart'; -import 'package:aitrainer_app/widgets/app_bar_min.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; - -class ExerciseTypeDescription extends StatelessWidget { - @override - Widget build(BuildContext context) { - final ExerciseRepository exerciseRepository = ModalRoute.of(context).settings.arguments; - String exerciseDescription = AppLanguage().appLocal == Locale("en") - ? exerciseRepository.exerciseType.description - : exerciseRepository.exerciseType.descriptionTranslation; - - String exerciseName = - AppLanguage().appLocal == Locale("en") ? exerciseRepository.exerciseType.name : exerciseRepository.exerciseType.nameTranslation; - - return Scaffold( - appBar: AppBarMin( - back: true, - ), - body: Container( - width: MediaQuery.of(context).size.width, - height: MediaQuery.of(context).size.height, - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('asset/image/WT_light_background.jpg'), - fit: BoxFit.fill, - alignment: Alignment.center, - ), - ), - padding: EdgeInsets.only(left: 20, top: 20, right: 15), - child: ListView(children: [ - Text( - exerciseName, - style: TextStyle(color: Colors.blueGrey, fontSize: 20, fontWeight: FontWeight.bold), - ), - Divider( - color: Colors.transparent, - ), - InkWell( - child: Text( - exerciseDescription, - style: TextStyle(color: Colors.blueGrey, fontSize: 18, fontWeight: FontWeight.normal), - ), - ), - ]))); - } -} diff --git a/lib/view/login.dart b/lib/view/login.dart index 7692cfd..50dd671 100644 --- a/lib/view/login.dart +++ b/lib/view/login.dart @@ -9,9 +9,8 @@ import 'package:aitrainer_app/widgets/dialog_long.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import '../library_keys.dart'; @@ -30,7 +29,7 @@ class LoginPage extends StatelessWidget with Trans { LoginBloc(userRepository: UserRepository(), accountBloc: accountBloc, context: context, isRegistration: false), child: BlocConsumer(listener: (context, state) { if (state is LoginError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white)))); } else if (state is LoginSuccess) { Navigator.of(context).pushNamed('home'); @@ -71,11 +70,11 @@ class LoginPage extends StatelessWidget with Trans { child: Container( padding: const EdgeInsets.only(left: 20, right: 20), child: ListView(shrinkWrap: false, padding: EdgeInsets.only(top: 150.0), children: [ - ListTile(title: Text(t("Login"), style: GoogleFonts.inter())), + ListTile(title: Text(t("Login"), style: GoogleFonts.inter(fontSize: 24))), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - FlatButton( + TextButton( child: Image.asset( 'asset/image/button_fb.png', width: 60, @@ -83,7 +82,7 @@ class LoginPage extends StatelessWidget with Trans { onPressed: () => {loginBloc.add(LoginFB())}, ), Platform.isAndroid - ? FlatButton( + ? TextButton( child: Image.asset( 'asset/image/button_google.png', width: 60, @@ -92,7 +91,7 @@ class LoginPage extends StatelessWidget with Trans { ) : Offstage(), Platform.isIOS - ? FlatButton( + ? TextButton( child: Image.asset( 'asset/image/button_apple.png', width: 60, @@ -115,13 +114,14 @@ class LoginPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 4.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: loginBloc.userRepository.user.email, autovalidateMode: AutovalidateMode.onUserInteraction, validator: (val) { - return t(loginBloc.emailValidation(val)); + String? validationText = loginBloc.emailValidation(val!); + return validationText == null ? null : t(validationText); }, onChanged: (value) => loginBloc.add(LoginEmailChange(email: value)), keyboardType: TextInputType.emailAddress, @@ -146,13 +146,14 @@ class LoginPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 1.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: loginBloc.userRepository.user.password, autovalidateMode: AutovalidateMode.always, validator: (val) { - return t(loginBloc.passwordValidation(val)); + String? validationText = loginBloc.passwordValidation(val!); + return validationText == null ? null : t(validationText); }, onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)), keyboardType: TextInputType.visiblePassword, @@ -162,7 +163,7 @@ class LoginPage extends StatelessWidget with Trans { color: Colors.transparent, ), Row(mainAxisAlignment: MainAxisAlignment.end, children: [ - FlatButton( + TextButton( key: LibraryKeys.loginOKButton, child: Stack( alignment: Alignment.center, diff --git a/lib/view/menu_page.dart b/lib/view/menu_page.dart index 074d3db..24299e3 100644 --- a/lib/view/menu_page.dart +++ b/lib/view/menu_page.dart @@ -11,14 +11,14 @@ import 'package:flutter_bloc/flutter_bloc.dart'; class MenuPage extends StatefulWidget { int parent; - MenuPage({this.parent}); + MenuPage({required this.parent}); _MenuPage createState() => _MenuPage(); } class _MenuPage extends State { // ignore: close_sinks - MenuBloc menuBloc; + late MenuBloc menuBloc; @override void initState() { @@ -43,7 +43,7 @@ class _MenuPage extends State { ), child: BlocConsumer(listener: (context, state) { if (state is MenuError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { diff --git a/lib/view/mydevelopment_body_page.dart b/lib/view/mydevelopment_body_page.dart index b186e80..dca6181 100644 --- a/lib/view/mydevelopment_body_page.dart +++ b/lib/view/mydevelopment_body_page.dart @@ -11,7 +11,7 @@ import 'package:aitrainer_app/util/trans.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:aitrainer_app/bloc/body_development/body_development_bloc.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; class MyDevelopmentBodyPage extends StatefulWidget { @override @@ -21,7 +21,7 @@ class MyDevelopmentBodyPage extends StatefulWidget { class _MyDevelopmentBodyPage extends State with Trans, Common { bool isStart = false; // ignore: close_sinks - BodyDevelopmentBloc bloc; + late BodyDevelopmentBloc bloc; @override void initState() { @@ -48,7 +48,7 @@ class _MyDevelopmentBodyPage extends State with Trans, Co } /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { BlocProvider.of(context).add(BodyDevelopmentLoad()); }); } @@ -56,7 +56,7 @@ class _MyDevelopmentBodyPage extends State with Trans, Co @override Widget build(BuildContext context) { bloc = BlocProvider.of(context); - LinkedHashMap arguments = ModalRoute.of(context).settings.arguments; + LinkedHashMap arguments = ModalRoute.of(context)!.settings.arguments as LinkedHashMap; final int customerId = arguments['customerId']; setContext(context); @@ -66,7 +66,7 @@ class _MyDevelopmentBodyPage extends State with Trans, Co padding: EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( - image: customerId == Cache().userLoggedIn.customerId + image: customerId == Cache().userLoggedIn!.customerId ? AssetImage('asset/image/WT_light_background.jpg') : AssetImage('asset/image/WT_menu_dark.jpg'), fit: BoxFit.cover, diff --git a/lib/view/mydevelopment_muscle_page.dart b/lib/view/mydevelopment_muscle_page.dart index 2a4f08d..7c39b43 100644 --- a/lib/view/mydevelopment_muscle_page.dart +++ b/lib/view/mydevelopment_muscle_page.dart @@ -16,7 +16,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; class MyDevelopmentMusclePage extends StatefulWidget { @override @@ -25,8 +24,8 @@ class MyDevelopmentMusclePage extends StatefulWidget { class _MyDevelopmentMuscleState extends State with Common, Trans { // ignore: close_sinks - DevelopmentByMuscleBloc bloc; - double cWidth; + late DevelopmentByMuscleBloc bloc; + late double cWidth; @override void initState() { @@ -52,7 +51,7 @@ class _MyDevelopmentMuscleState extends State with Comm } /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { BlocProvider.of(context).add(DevelopmentByMuscleLoad()); }); } @@ -77,7 +76,7 @@ class _MyDevelopmentMuscleState extends State with Comm child: BlocConsumer( listener: (context, state) { if (state is DevelopmentByMuscleErrorState) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( state.message, ), @@ -102,7 +101,7 @@ class _MyDevelopmentMuscleState extends State with Comm } List _getTreeChildren(SplayTreeMap tree, DevelopmentByMuscleBloc bloc) { - List exerciseTypes = List(); + List exerciseTypes = []; Card explanation = Card( color: Colors.white60, @@ -229,7 +228,7 @@ class _MyDevelopmentMuscleState extends State with Comm return exerciseTypes; } - Widget _getExerciseWidget({@required String exerciseTypeName, bool noData = false}) { + Widget _getExerciseWidget({required String exerciseTypeName, bool noData = false}) { return TreeviewParentWidget( text: exerciseTypeName, backgroundColor: !noData ? Colors.white38 : Colors.white12, @@ -238,7 +237,7 @@ class _MyDevelopmentMuscleState extends State with Comm LinkedHashMap _getChildList(List listWorkoutTree, DevelopmentByMuscleBloc bloc) { LinkedHashMap rc = LinkedHashMap(); - List list = List(); + List list = []; bool hasSummaryNoData = true; listWorkoutTree.forEach((element) { final bool hasNoData = (bloc.listChartData[element.exerciseTypeId] == null); @@ -257,7 +256,7 @@ class _MyDevelopmentMuscleState extends State with Comm hasNoData ? Container() : Text( - element.exerciseType.nameTranslation, + element.exerciseType!.nameTranslation, style: TextStyle(color: Colors.deepOrange), ), hasNoData @@ -296,7 +295,7 @@ class _MyDevelopmentMuscleState extends State with Comm getTextStyles: (_) => TextStyle(fontSize: 8, color: Colors.blueGrey), interval: bloc.listChartData[element.exerciseTypeId] == null ? 100 - : bloc.listChartData[element.exerciseTypeId].interval, + : bloc.listChartData[element.exerciseTypeId]!.interval, margin: 10, getTitles: (double value) { return value.toStringAsFixed(0) + unit; @@ -306,7 +305,7 @@ class _MyDevelopmentMuscleState extends State with Comm ), gridData: FlGridData( show: true, - checkToShowHorizontalLine: (value) => value % bloc.listChartData[element.exerciseTypeId].gridInterval == 0, + checkToShowHorizontalLine: (value) => value % bloc.listChartData[element.exerciseTypeId]!.gridInterval == 0, getDrawingHorizontalLine: (value) { return FlLine( color: Colors.black26, @@ -316,7 +315,7 @@ class _MyDevelopmentMuscleState extends State with Comm ), groupsSpace: 2, barGroups: - bloc.listChartData[element.exerciseTypeId] == null ? [] : bloc.listChartData[element.exerciseTypeId].data, + bloc.listChartData[element.exerciseTypeId] == null ? [] : bloc.listChartData[element.exerciseTypeId]!.data, ), swapAnimationDuration: Duration(milliseconds: 1200), ), diff --git a/lib/view/mydevelopment_page.dart b/lib/view/mydevelopment_page.dart index fbf0056..13cb84b 100644 --- a/lib/view/mydevelopment_page.dart +++ b/lib/view/mydevelopment_page.dart @@ -89,7 +89,7 @@ class _MyDevelopmentPage extends State with Trans { onTap: () => { if (Cache().userLoggedIn != null) { - args['customerId'] = Cache().userLoggedIn.customerId, + args['customerId'] = Cache().userLoggedIn!.customerId, Navigator.of(context).pushNamed('mydevelopmentBodyPage', arguments: args) } }, @@ -185,17 +185,18 @@ class _MyDevelopmentPage extends State with Trans { Widget hiddenWidget(CustomerRepository customerRepository, ExerciseRepository exerciseRepository) { final LinkedHashMap args = LinkedHashMap(); if (Cache().getTrainee() != null) { - return FlatButton( - padding: EdgeInsets.all(20), - textColor: Colors.white, - color: Colors.black12, - focusColor: Colors.blueAccent, + return TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(20), + primary: Colors.white, + onSurface: Colors.blueAccent, + ), onPressed: () => { if (Cache().getTrainee() != null) { args['exerciseRepository'] = exerciseRepository, args['customerRepository'] = customerRepository, - args['customerId'] = Cache().getTrainee().customerId, + args['customerId'] = Cache().getTrainee()!.customerId, Navigator.of(context).pushNamed('exerciseLogPage', arguments: args) }, }, @@ -213,7 +214,7 @@ class _MyDevelopmentPage extends State with Trans { final LinkedHashMap args = LinkedHashMap(); args['exerciseRepository'] = exerciseRepository; args['customerRepository'] = customerRepository; - args['customerId'] = Cache().userLoggedIn.customerId; + args['customerId'] = Cache().userLoggedIn!.customerId; Navigator.of(context).pushNamed('exerciseLogPage', arguments: args); } } diff --git a/lib/view/mydevelopment_sizes_page.dart b/lib/view/mydevelopment_sizes_page.dart index e8f5e8b..833eec0 100644 --- a/lib/view/mydevelopment_sizes_page.dart +++ b/lib/view/mydevelopment_sizes_page.dart @@ -5,9 +5,9 @@ import 'package:aitrainer_app/util/trans.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import '../widgets/app_bar.dart'; import '../widgets/input_dialog_widget.dart'; @@ -26,8 +26,8 @@ class _SizeState extends State with Trans { create: (context) => DevelopmentSizesBloc(customerRepository: CustomerRepository())..add(DevelopmentSizesLoad()), child: BlocConsumer(listener: (context, state) { if (state is DevelopmentSizesError) { - Scaffold.of(context) - .showSnackBar(SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); + ScaffoldMessenger.of(context).showSnackBar( + (SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white))))); } }, builder: (context, state) { final bloc = BlocProvider.of(context); @@ -74,7 +74,7 @@ class _SizeState extends State with Trans { double mediaHeight = MediaQuery.of(context).size.height * .8; bloc.customerRepository.setMediaDimensions(mediaWidth, mediaHeight); - List list = List(); + List list = []; list.add( bloc.isMan @@ -90,8 +90,8 @@ class _SizeState extends State with Trans { ), ); list.add(Positioned( - top: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: true).toDouble(), - left: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: false, isLeft: true).toDouble() - 45, + top: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: true)!.toDouble(), + left: bloc.customerRepository.getWeightCoordinate(bloc.isMan, isTop: false, isLeft: true)!.toDouble() - 45, child: GestureDetector( //onTap: () => onPressed(bloc.customerRepository.getPropertyByName("Weight")), child: Image.asset( @@ -132,13 +132,13 @@ class _SizeState extends State with Trans { } List getSizeElements(DevelopmentSizesBloc bloc) { - List list = List(); + List list = []; bloc.customerRepository.manSizes.forEach((element) { list.add( Positioned( - top: element.top.toDouble(), - left: element.left.toDouble(), + top: element.top!.toDouble(), + left: element.left!.toDouble(), child: element.value != 0 ? Container( width: 20, @@ -187,7 +187,7 @@ class _SizeState extends State with Trans { builder: (context) => InputDialog( title: t("Size Of Your"), subtitle: element.propertyNameTranslation, - initialValue: element.value, + initialValue: element.value!, onChanged: (value) { //widget.exerciseBloc.add(ExerciseNewSizeChange(propertyName: element.propertyName, value: value)); }, diff --git a/lib/view/myexcercise_plan_page.dart b/lib/view/myexcercise_plan_page.dart index aa5e43c..949ad08 100644 --- a/lib/view/myexcercise_plan_page.dart +++ b/lib/view/myexcercise_plan_page.dart @@ -58,7 +58,7 @@ class _MyExercisePlanPage extends State with Trans, Logging if (Cache().userLoggedIn != null) { args['exerciseRepository'] = exerciseRepository, - args['customerId'] = Cache().userLoggedIn.customerId, + args['customerId'] = Cache().userLoggedIn!.customerId, Navigator.of(context).pushNamed('exercisePlanCustomPage', arguments: args) } }, @@ -80,7 +80,7 @@ class _MyExercisePlanPage extends State with Trans, Logging onTap: () => { if (Cache().userLoggedIn != null) { - args['customerId'] = Cache().userLoggedIn.customerId, + args['customerId'] = Cache().userLoggedIn!.customerId, Navigator.of(context).pushNamed('exerciseExecutePlanPage', arguments: args) } }, @@ -190,16 +190,17 @@ class _MyExercisePlanPage extends State with Trans, Logging Widget hiddenPlanWidget(ExerciseRepository exerciseRepository) { final LinkedHashMap args = LinkedHashMap(); if (Cache().getTrainee() != null) { - return FlatButton( - padding: EdgeInsets.all(20), - textColor: Colors.white, - color: Colors.black12, - focusColor: Colors.blueAccent, + return TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(20), + primary: Colors.white, + onSurface: Colors.black12, + ), onPressed: () => { if (Cache().getTrainee() != null) { args['exerciseRepository'] = exerciseRepository, - args['customerId'] = Cache().getTrainee().customerId, + args['customerId'] = Cache().getTrainee()!.customerId, Navigator.of(context).pushNamed('exercisePlanCustomPage', arguments: args) } }, @@ -215,16 +216,17 @@ class _MyExercisePlanPage extends State with Trans, Logging Widget hiddenTrainingWidget() { final LinkedHashMap args = LinkedHashMap(); if (Cache().getTrainee() != null) { - log("!!Trainee: " + Cache().getTrainee().firstname + " " + Cache().getTrainee().name); - return FlatButton( - padding: EdgeInsets.all(20), - textColor: Colors.white, - color: Colors.black12, - focusColor: Colors.blueAccent, + log("!!Trainee: " + Cache().getTrainee()!.firstname! + " " + Cache().getTrainee()!.name!); + return TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(20), + primary: Colors.white, + onSurface: Colors.black12, + ), onPressed: () => { if (Cache().getTrainee() != null) { - args['customerId'] = Cache().getTrainee().customerId, + args['customerId'] = Cache().getTrainee()!.customerId, Navigator.of(context).pushNamed('exerciseExecutePlanPage', arguments: args) } }, diff --git a/lib/view/registration.dart b/lib/view/registration.dart index aba2cb8..60bf2f3 100644 --- a/lib/view/registration.dart +++ b/lib/view/registration.dart @@ -10,9 +10,8 @@ import 'package:aitrainer_app/widgets/dialog_long.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import '../library_keys.dart'; @@ -31,13 +30,8 @@ class RegistrationPage extends StatelessWidget with Trans { LoginBloc(userRepository: UserRepository(), accountBloc: accountBloc, context: context, isRegistration: true), child: BlocConsumer(listener: (context, state) { if (state is LoginError) { - String message = t(state.message); - if (message == null) { - message = ""; - } else { - Scaffold.of(context).showSnackBar( - SnackBar(backgroundColor: Colors.orange, content: Text(message, style: TextStyle(color: Colors.white)))); - } + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white)))); } else if (state is LoginSuccess) { //Navigator.of(context).pushNamed('customerModifyPage'); showDialog( @@ -95,7 +89,7 @@ class RegistrationPage extends StatelessWidget with Trans { Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - FlatButton( + TextButton( child: Image.asset( 'asset/image/button_fb.png', width: 60, @@ -103,7 +97,7 @@ class RegistrationPage extends StatelessWidget with Trans { onPressed: () => {loginBloc.add(RegistrationFB())}, ), Platform.isAndroid - ? FlatButton( + ? TextButton( child: Image.asset( 'asset/image/button_google.png', width: 60, @@ -112,7 +106,7 @@ class RegistrationPage extends StatelessWidget with Trans { ) : Offstage(), Platform.isIOS - ? FlatButton( + ? TextButton( child: Image.asset( 'asset/image/button_apple.png', width: 60, @@ -133,13 +127,14 @@ class RegistrationPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 4.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: loginBloc.userRepository.user.email, autovalidateMode: AutovalidateMode.onUserInteraction, validator: (val) { - return t(loginBloc.emailValidation(val)); + final String? validator = loginBloc.emailValidation(val!); + return validator == null ? null : t(validator); }, onChanged: (value) => loginBloc.add(LoginEmailChange(email: value)), keyboardType: TextInputType.emailAddress, @@ -164,13 +159,14 @@ class RegistrationPage extends StatelessWidget with Trans { border: OutlineInputBorder( gapPadding: 1.0, borderRadius: BorderRadius.circular(12.0), - borderSide: BorderSide(color: Colors.green[50], width: 0.4), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), ), ), initialValue: loginBloc.userRepository.user.password, autovalidateMode: AutovalidateMode.always, validator: (val) { - return t(loginBloc.passwordValidation(val)); + final String? validator = loginBloc.passwordValidation(val!); + return validator == null ? null : t(validator); }, onChanged: (value) => loginBloc.add(LoginPasswordChange(password: value)), keyboardType: TextInputType.visiblePassword, @@ -184,7 +180,7 @@ class RegistrationPage extends StatelessWidget with Trans { color: Colors.transparent, ), Row(mainAxisAlignment: MainAxisAlignment.start, children: [ - FlatButton( + TextButton( key: LibraryKeys.loginOKButton, child: Stack( alignment: Alignment.center, @@ -233,7 +229,7 @@ class RegistrationPage extends StatelessWidget with Trans { value: loginBloc.dataPolicyAllowed, activeColor: Colors.indigo, onChanged: (value) { - loginBloc.add(DataProtectionClicked(marked: value)); + loginBloc.add(DataProtectionClicked(marked: value!)); }, controlAffinity: ListTileControlAffinity.leading, // <-- leading Checkbox ); diff --git a/lib/view/reset_password.dart b/lib/view/reset_password.dart index c9044a5..440ce9b 100644 --- a/lib/view/reset_password.dart +++ b/lib/view/reset_password.dart @@ -1,13 +1,12 @@ -import 'package:aitrainer_app/bloc/reset_password_bloc.dart'; +import 'package:aitrainer_app/bloc/password_reset/password_reset_bloc.dart'; import 'package:aitrainer_app/repository/user_repository.dart'; import 'package:aitrainer_app/util/trans.dart'; import 'package:aitrainer_app/widgets/app_bar_min.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import '../library_keys.dart'; @@ -20,49 +19,50 @@ class ResetPasswordPage extends StatelessWidget with Trans { Widget build(BuildContext context) { setContext(context); return BlocProvider( - create: (context) => ResetPasswordFormBloc( + create: (context) => PasswordResetBloc( userRepository: UserRepository(), ), child: Builder(builder: (context) { - final loginBloc = BlocProvider.of(context); return Scaffold( key: _scaffoldKey, appBar: AppBarMin(), - body: FormBlocListener( - /* onSubmitting: (context, state) { - LoadingDialog.show(context); - }, */ - onSuccess: (context, state) { - Navigator.of(context).pop(); + body: BlocConsumer( + listener: (context, state) { + if (state is PasswordResetError) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white)))); + } else if (state is PasswordResetReady) { + Navigator.of(context).pop(); + } }, - onFailure: (context, state) { - showInSnackBar(state.failureResponse); - }, - child: SafeArea( - bottom: false, - child: Container( - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage('asset/image/WT_login.jpg'), - fit: BoxFit.cover, - alignment: Alignment.center, + builder: (context, state) { + final loginBloc = BlocProvider.of(context); + return SafeArea( + bottom: false, + child: Container( + decoration: BoxDecoration( + image: DecorationImage( + image: AssetImage('asset/image/WT_login.jpg'), + fit: BoxFit.cover, + alignment: Alignment.center, + ), + ), + child: ModalProgressHUD( + child: buildResetPasswordForm(loginBloc), + inAsyncCall: state is PasswordResetLoading, + opacity: 0.5, + color: Colors.black54, + progressIndicator: CircularProgressIndicator(), ), ), - child: ModalProgressHUD( - child: buildResetPasswordForm(loginBloc), - inAsyncCall: loginBloc.loading == true, - opacity: 0.5, - color: Colors.black54, - progressIndicator: CircularProgressIndicator(), - ), - ), - ), + ); + }, ), ); })); } - Widget buildResetPasswordForm(ResetPasswordFormBloc formBloc) { + Widget buildResetPasswordForm(PasswordResetBloc loginBloc) { return Form( key: _formKey, child: Container( @@ -81,14 +81,28 @@ class ResetPasswordPage extends StatelessWidget with Trans { ], ), Divider(), - TextFieldBlocBuilder( + TextFormField( key: LibraryKeys.loginEmailField, - textFieldBloc: formBloc.emailField, decoration: InputDecoration( - fillColor: Colors.white, + contentPadding: EdgeInsets.only(left: 15, top: 15, bottom: 15), + labelText: t('Email'), + fillColor: Colors.white24, filled: true, - labelText: 'Email', + border: OutlineInputBorder( + gapPadding: 4.0, + borderRadius: BorderRadius.circular(12.0), + borderSide: BorderSide(color: Colors.green[50]!, width: 0.4), + ), ), + initialValue: loginBloc.userRepository.user.email, + autovalidateMode: AutovalidateMode.onUserInteraction, + validator: (val) { + final String? validator = loginBloc.emailValidation(val!); + return validator == null ? null : t(validator); + }, + onChanged: (value) => loginBloc.add(PasswordResetEmailChange(email: value)), + keyboardType: TextInputType.emailAddress, + style: new TextStyle(fontSize: 16, color: Colors.indigo), ), Divider( color: Colors.transparent, @@ -97,7 +111,7 @@ class ResetPasswordPage extends StatelessWidget with Trans { color: Colors.transparent, ), Row(mainAxisAlignment: MainAxisAlignment.end, children: [ - new FlatButton( + TextButton( key: LibraryKeys.loginOKButton, child: Stack( alignment: Alignment.center, @@ -109,8 +123,7 @@ class ResetPasswordPage extends StatelessWidget with Trans { ), ], ), - //Image.asset('asset/image/WT_OK.png', width: 100, height: 100), - onPressed: () => {formBloc.add(SubmitFormBloc())}), + onPressed: () => loginBloc.add(PasswordResetSubmit())), ]), Divider( color: Colors.transparent, @@ -125,9 +138,4 @@ class ResetPasswordPage extends StatelessWidget with Trans { ])), ); } - - void showInSnackBar(String error) { - _scaffoldKey.currentState - .showSnackBar(SnackBar(backgroundColor: Colors.orange, content: Text(error, style: TextStyle(color: Colors.white)))); - } } diff --git a/lib/view/sales_page.dart b/lib/view/sales_page.dart index 22f9412..5814c1c 100644 --- a/lib/view/sales_page.dart +++ b/lib/view/sales_page.dart @@ -7,7 +7,7 @@ import 'package:aitrainer_app/widgets/sales_button.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class SalesPage extends StatelessWidget with Trans, Logging { @@ -23,7 +23,7 @@ class SalesPage extends StatelessWidget with Trans, Logging { child: BlocConsumer(listener: (context, state) { if (state is SalesError) { log("Error: " + state.message); - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(t(state.message), style: TextStyle(color: Colors.white)))); } else if (state is SalesSuccessful) { showDialog( @@ -145,12 +145,12 @@ class SalesPage extends StatelessWidget with Trans, Logging { } List getButtons(SalesBloc bloc) { - List buttons = List(); + List buttons = []; bloc.product2Display.forEach((element) { final String title = element.sort == 3 ? t("Montly") : t("Annual"); final String desc4 = element.sort == 1 ? "" : t("Predictions with Artificial Intelligence"); - String badge; + late String badge; if (element.sort == 2) { badge = t("14% discount"); } else if (element.sort == 1) { @@ -158,7 +158,7 @@ class SalesPage extends StatelessWidget with Trans, Logging { } Widget button = SalesButton( title: title, - price: element.localizedPrice, + price: element.localizedPrice!, desc1: t("Development programs"), desc2: t("Suggestions based on your actual status"), desc3: t("Special customized training plans"), diff --git a/lib/view/settings.dart b/lib/view/settings.dart index 85e6087..c5cf213 100644 --- a/lib/view/settings.dart +++ b/lib/view/settings.dart @@ -12,7 +12,7 @@ import 'package:aitrainer_app/widgets/bottom_nav.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:toggle_switch/toggle_switch.dart'; // ignore: must_be_immutable @@ -39,7 +39,7 @@ class SettingsPage extends StatelessWidget with Trans { child: Form( child: BlocConsumer(listener: (context, state) { if (state is SettingsError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is SettingsReady) { menuBloc.add(MenuRecreateTree()); @@ -71,8 +71,8 @@ class SettingsPage extends StatelessWidget with Trans { child: Text(value), ); }).toList(), - onChanged: (String lang) => { - settingsBloc.add(SettingsChangeLanguage(language: lang)), + onChanged: (lang) => { + settingsBloc.add(SettingsChangeLanguage(language: lang as String)), Track().track(TrackingEvent.settings_lang, eventValue: lang) })), getServer(settingsBloc), @@ -81,7 +81,7 @@ class SettingsPage extends StatelessWidget with Trans { } ListTile getServer(SettingsBloc settingsBloc) { - if (Cache().userLoggedIn == null || Cache().userLoggedIn.admin != 1) { + if (Cache().userLoggedIn == null || Cache().userLoggedIn!.admin != 1) { return ListTile( title: Container(), ); @@ -119,7 +119,7 @@ class SettingsPage extends StatelessWidget with Trans { minWidth: 120.0, minHeight: 30.0, fontSize: 14.0, - initialLabelIndex: Cache().hasHardware ? 0 : 1, + initialLabelIndex: Cache().hasHardware! ? 0 : 1, activeBgColor: Colors.indigo, activeFgColor: Colors.white, inactiveBgColor: Colors.white60, diff --git a/lib/view/test_set_control.dart b/lib/view/test_set_control.dart index 36460f9..1a66dc4 100644 --- a/lib/view/test_set_control.dart +++ b/lib/view/test_set_control.dart @@ -14,13 +14,13 @@ import 'package:aitrainer_app/widgets/number_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class TestSetControl extends StatelessWidget with Trans { @override Widget build(BuildContext context) { - final HashMap args = ModalRoute.of(context).settings.arguments; + final HashMap args = ModalRoute.of(context)!.settings.arguments as HashMap; final ExerciseType exerciseType = args['exerciseType']; final ExercisePlanDetail exercisePlanDetail = args['exercisePlanDetail']; // ignore: close_sinks @@ -35,7 +35,7 @@ class TestSetControl extends StatelessWidget with Trans { padding: EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( - image: Cache().userLoggedIn.sex == "m" + image: Cache().userLoggedIn!.sex == "m" ? AssetImage("asset/image/WT_Results_for_men.jpg") : AssetImage("asset/image/WT_Results_for_female.jpg"), fit: BoxFit.cover, @@ -47,7 +47,7 @@ class TestSetControl extends StatelessWidget with Trans { TestSetControlBloc(exercisePlanDetail: exercisePlanDetail, executeBloc: executeBloc, exerciseType: exerciseType), child: BlocConsumer(listener: (context, state) { if (state is TestSetControlError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -76,7 +76,7 @@ class TestSetControl extends StatelessWidget with Trans { child: Column( children: [ Text( - exercisePlanDetail.exerciseType.nameTranslation, + exercisePlanDetail.exerciseType!.nameTranslation, style: GoogleFonts.archivoBlack( fontWeight: FontWeight.bold, fontSize: 24, @@ -130,7 +130,7 @@ class TestSetControl extends StatelessWidget with Trans { children: [ TextSpan(text: t("Please repeat with ")), TextSpan( - text: bloc.initUnitQuantity.toStringAsFixed(0) + " " + bloc.exercisePlanDetail.exerciseType.unitQuantityUnit, + text: bloc.initUnitQuantity.toStringAsFixed(0) + " " + bloc.exercisePlanDetail.exerciseType!.unitQuantityUnit!, style: GoogleFonts.inter( decoration: TextDecoration.underline, fontSize: 16, @@ -160,12 +160,14 @@ class TestSetControl extends StatelessWidget with Trans { maxValue: 200, initalValue: bloc.initQuantity.round(), unit: t("reps"), - color: Colors.yellow[50], + color: Colors.yellow[50]!, onChange: (value) => {bloc.add(TestSetControlQuantityChange(quantity: value.toDouble()))}), - FlatButton( - padding: EdgeInsets.all(0), - textColor: Colors.white, - focusColor: Colors.blueAccent, + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.all(0), + primary: Colors.white, + onSurface: Colors.blueAccent, + ), onPressed: () => { bloc.add(TestSetControlSubmit()), { diff --git a/lib/view/test_set_edit.dart b/lib/view/test_set_edit.dart index deecd75..02720e9 100644 --- a/lib/view/test_set_edit.dart +++ b/lib/view/test_set_edit.dart @@ -13,18 +13,18 @@ import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class TestSetEdit extends StatelessWidget with Trans { @override Widget build(BuildContext context) { - HashMap args = ModalRoute.of(context).settings.arguments; + HashMap args = ModalRoute.of(context)!.settings.arguments as HashMap; final String templateName = args['templateName']; final String templateNameTranslation = args['templateNameTranslation']; // ignore: close_sinks final MenuBloc menuBloc = BlocProvider.of(context); - TestSetEditBloc bloc; + late TestSetEditBloc? bloc; setContext(context); return Scaffold( @@ -48,7 +48,7 @@ class TestSetEdit extends StatelessWidget with Trans { menuBloc: menuBloc), child: BlocConsumer(listener: (context, state) { if (state is TestSetEditError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is TestSetEditSaved) { Navigator.of(context).pop(); @@ -57,7 +57,7 @@ class TestSetEdit extends StatelessWidget with Trans { }, builder: (context, state) { bloc = BlocProvider.of(context); return ModalProgressHUD( - child: getTestSetWidget(bloc, templateNameTranslation), + child: getTestSetWidget(bloc!, templateNameTranslation), inAsyncCall: state is TestSetEditLoading, opacity: 0.5, color: Colors.black54, @@ -77,7 +77,7 @@ class TestSetEdit extends StatelessWidget with Trans { Navigator.of(context).pop(), if (bloc != null) { - bloc.add(TestSetEditSubmit()), + bloc!.add(TestSetEditSubmit()), } }, onCancel: () => {Navigator.of(context).pop()}, @@ -156,7 +156,7 @@ class TestSetEdit extends StatelessWidget with Trans { } List imageSliders(List alternatives, MenuBloc menuBloc, WorkoutMenuTree workoutTree, TestSetEditBloc bloc) { - final List list = List(); + final List list = []; if (bloc.exercisePlanDetails[workoutTree.exerciseTypeId] == null) { list.add(Container( padding: EdgeInsets.only(top: 25, bottom: 25), @@ -177,7 +177,7 @@ class TestSetEdit extends StatelessWidget with Trans { } else { ExerciseType exerciseType = bloc.exercisePlanDetails[workoutTree.exerciseTypeId]; - final WorkoutMenuTree actualWorkoutTree = bloc.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseType.exerciseTypeId); + final WorkoutMenuTree actualWorkoutTree = bloc.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(exerciseType.exerciseTypeId)!; list.add(getImageStack(actualWorkoutTree, menuBloc, bloc)); } @@ -225,11 +225,11 @@ class TestSetEdit extends StatelessWidget with Trans { } List getExerciseTypeWidgets(TestSetEditBloc bloc) { - final List widgets = List(); + final List widgets = []; bloc.exerciseTypes.forEach((element) { - final WorkoutMenuTree workoutTree = bloc.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(element.exerciseTypeId); + final WorkoutMenuTree? workoutTree = bloc.menuBloc.menuTreeRepository.getMenuItemByExerciseTypeId(element.exerciseTypeId); - final List alternativeMenuItems = bloc.menuBloc.menuTreeRepository.getWorkoutTreeAlternatives(workoutTree); + final List? alternativeMenuItems = bloc.menuBloc.menuTreeRepository.getWorkoutTreeAlternatives(workoutTree); if (workoutTree != null && alternativeMenuItems != null) { final Widget widget = CarouselSlider( options: CarouselOptions( diff --git a/lib/view/test_set_execute.dart b/lib/view/test_set_execute.dart index 7c3a310..b900866 100644 --- a/lib/view/test_set_execute.dart +++ b/lib/view/test_set_execute.dart @@ -12,7 +12,7 @@ import 'package:aitrainer_app/widgets/victory_widget.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:timeline_tile/timeline_tile.dart'; // ignore: must_be_immutable @@ -40,7 +40,7 @@ class TestSetExecute extends StatelessWidget with Trans { ), child: BlocConsumer(listener: (context, state) { if (state is TestSetExecuteError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is TestSetExecuteFinished) { showDialog( @@ -64,7 +64,7 @@ class TestSetExecute extends StatelessWidget with Trans { }), ), floatingActionButton: FloatingActionButton.extended( - onPressed: () => executeExercise(executeBloc, executeBloc.getNext(), context), + onPressed: () => executeExercise(executeBloc, executeBloc.getNext()!, context), backgroundColor: Colors.orange[800], icon: Icon(CustomIcon.weight_hanging), label: Text( @@ -82,7 +82,7 @@ class TestSetExecute extends StatelessWidget with Trans { } List getTiles(TestSetExecuteBloc bloc, BuildContext context) { - List tiles = List(); + List tiles = []; tiles.add(getStartTile(bloc)); tiles.addAll(getExerciseTiles(bloc, context)); tiles.add(getEndTile()); @@ -248,18 +248,18 @@ class TestSetExecute extends StatelessWidget with Trans { } List getExerciseTiles(TestSetExecuteBloc bloc, BuildContext context) { - List tiles = List(); + List tiles = []; if (bloc.exercisePlanDetails != null) { - bloc.exercisePlanDetails.forEach((element) { - if (element != null && element.exerciseTypeId != null) { - tiles.add(GestureDetector( - onDoubleTap: () => print("Execute ${element.exerciseType.nameTranslation}"), - onTap: () => executeExercise(bloc, element, context), - child: ExerciseTile( - bloc: bloc, - exercisePlanDetail: element, - ))); - } + bloc.exercisePlanDetails!.forEach((element) { + //if (element != null && element.exerciseTypeId != null) { + tiles.add(GestureDetector( + onDoubleTap: () => print("Execute ${element.exerciseType!.nameTranslation}"), + onTap: () => executeExercise(bloc, element, context), + child: ExerciseTile( + bloc: bloc, + exercisePlanDetail: element, + ))); + //} }); } @@ -267,8 +267,8 @@ class TestSetExecute extends StatelessWidget with Trans { } void executeExercise(TestSetExecuteBloc bloc, ExercisePlanDetail exercisePlanDetail, BuildContext context) { - ExercisePlanDetail next = bloc.getNext(); - print("Detail: $next"); + ExercisePlanDetail? next = bloc.getNext(); + if (next != null) { final HashMap args = HashMap(); args['exerciseType'] = exercisePlanDetail.exerciseType; @@ -279,7 +279,7 @@ class TestSetExecute extends StatelessWidget with Trans { String description2 = ""; if (next.exerciseTypeId != exercisePlanDetail.exerciseTypeId) { title = t("Stop!"); - description = t("Please continue with the next exercise in the queue:") + next.exerciseType.nameTranslation; + description = t("Please continue with the next exercise in the queue:") + next.exerciseType!.nameTranslation; description2 = t("Or, you can redifine this exercise queue in the Compact Test menu"); } else { if (exercisePlanDetail.state.equalsTo(ExercisePlanDetailState.inProgress)) { @@ -318,10 +318,10 @@ class ExerciseTile extends StatelessWidget with Trans { final TestSetExecuteBloc bloc; final ExercisePlanDetail exercisePlanDetail; - ExerciseTile({this.bloc, this.exercisePlanDetail}); + ExerciseTile({required this.bloc, required this.exercisePlanDetail}); Widget getIndicator(ExercisePlanDetailState state) { - ExercisePlanDetail next = bloc.getNext(); + ExercisePlanDetail? next = bloc.getNext(); bool actual = false; if (next != null) { if (next.exerciseTypeId == exercisePlanDetail.exerciseTypeId) { @@ -359,8 +359,8 @@ class ExerciseTile extends StatelessWidget with Trans { Widget build(BuildContext context) { final ExercisePlanDetailState state = exercisePlanDetail.state; final bool done = state.equalsTo(ExercisePlanDetailState.finished); - final String countSerie = exercisePlanDetail.exercises == null ? "1" : (exercisePlanDetail.exercises.length).toString(); - final String serie = exercisePlanDetail.exerciseType.unitQuantityUnit == null ? "/1" : "/4"; + final String countSerie = exercisePlanDetail.exercises == null ? "1" : (exercisePlanDetail.exercises!.length).toString(); + final String serie = exercisePlanDetail.exerciseType!.unitQuantityUnit == null ? "/1" : "/4"; setContext(context); return Container( color: Colors.transparent, @@ -387,8 +387,8 @@ class ExerciseTile extends StatelessWidget with Trans { width: 120, height: 80, child: MenuImage( - imageName: bloc.getActualImageName(exercisePlanDetail.exerciseType.exerciseTypeId), - workoutTreeId: bloc.getActualWorkoutTreeId(exercisePlanDetail.exerciseType.exerciseTypeId), + imageName: bloc.getActualImageName(exercisePlanDetail.exerciseType!.exerciseTypeId), + workoutTreeId: bloc.getActualWorkoutTreeId(exercisePlanDetail.exerciseType!.exerciseTypeId)!, )), SizedBox( width: 10, @@ -403,7 +403,7 @@ class ExerciseTile extends StatelessWidget with Trans { ), children: [ TextSpan( - text: exercisePlanDetail.exerciseType.nameTranslation, + text: exercisePlanDetail.exerciseType!.nameTranslation, style: GoogleFonts.inter( fontSize: 14, fontWeight: FontWeight.bold, @@ -421,18 +421,18 @@ class ExerciseTile extends StatelessWidget with Trans { ), ], )), - exercisePlanDetail.exerciseType.unitQuantityUnit != null + exercisePlanDetail.exerciseType!.unitQuantityUnit != null ? TextSpan( text: "\n", ) : TextSpan(), - exercisePlanDetail.exerciseType.unitQuantityUnit != null + exercisePlanDetail.exerciseType!.unitQuantityUnit != null ? TextSpan( - text: t(exercisePlanDetail.exerciseType.unitQuantityUnit) + ": ", + text: t(exercisePlanDetail.exerciseType!.unitQuantityUnit!) + ": ", style: GoogleFonts.inter( fontSize: 12, color: done ? Colors.grey[100] : Colors.yellow[400], fontWeight: FontWeight.bold)) : TextSpan(), - exercisePlanDetail.exerciseType.unitQuantityUnit != null + exercisePlanDetail.exerciseType!.unitQuantityUnit != null ? TextSpan( text: t(bloc.getExerciseWeight(exercisePlanDetail)), style: GoogleFonts.inter( @@ -443,7 +443,7 @@ class ExerciseTile extends StatelessWidget with Trans { text: "\n", ), TextSpan( - text: t(exercisePlanDetail.exerciseType.unit) + ": ", + text: t(exercisePlanDetail.exerciseType!.unit) + ": ", style: GoogleFonts.inter( fontSize: 12, color: done ? Colors.grey[100] : Colors.yellow[400], fontWeight: FontWeight.bold)), TextSpan( diff --git a/lib/view/test_set_new.dart b/lib/view/test_set_new.dart index d130dbb..5c47114 100644 --- a/lib/view/test_set_new.dart +++ b/lib/view/test_set_new.dart @@ -13,18 +13,18 @@ import 'package:aitrainer_app/widgets/exercise_save.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; // ignore: must_be_immutable class TestSetNew extends StatelessWidget with Trans { @override Widget build(BuildContext context) { - final HashMap args = ModalRoute.of(context).settings.arguments; + final HashMap args = ModalRoute.of(context)!.settings.arguments as HashMap; final ExerciseType exerciseType = args['exerciseType']; final int exercisePlanDetailId = args['exercisePlanDetailId']; // ignore: close_sinks final TestSetExecuteBloc executeBloc = args['testSetExecuteBloc']; - TestSetNewBloc bloc; + late TestSetNewBloc bloc; setContext(context); return Scaffold( appBar: AppBarNav(depth: 1), @@ -45,13 +45,13 @@ class TestSetNew extends StatelessWidget with Trans { executeBloc: executeBloc), child: BlocConsumer(listener: (context, state) { if (state is TestSetNewError) { - Scaffold.of(context).showSnackBar( + ScaffoldMessenger.of(context).showSnackBar( SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } else if (state is TestSetNewReady) { print("Actual state: ${executeBloc.actualState(exerciseType.exerciseTypeId).toString()}"); if (executeBloc.actualState(exerciseType.exerciseTypeId).equalsTo(ExercisePlanDetailState.inProgress)) { HashMap args = HashMap(); - final ExercisePlanDetail actualExercisePlanDetail = executeBloc.actualExercisePlanDetail(exerciseType.exerciseTypeId); + final ExercisePlanDetail actualExercisePlanDetail = executeBloc.actualExercisePlanDetail(exerciseType.exerciseTypeId)!; args['exerciseType'] = exerciseType; args['exercisePlanDetail'] = actualExercisePlanDetail; args['testSetExecuteBloc'] = executeBloc; @@ -94,7 +94,7 @@ class TestSetNew extends StatelessWidget with Trans { exerciseDescription: bloc.exerciseType.descriptionTranslation, exerciseTask: t("Please take a relative bigger weight and repeat 12-20 times"), unit: bloc.exerciseType.unit, - unitQuantityUnit: bloc.exerciseType.unitQuantityUnit, + unitQuantityUnit: bloc.exerciseType.unitQuantityUnit!, hasUnitQuantity: bloc.exerciseType.unitQuantityUnit != null, onQuantityChanged: (value) { bloc.add(TestSetNewChangeQuantity(quantity: double.parse(value))); diff --git a/lib/widgets/app_bar.dart b/lib/widgets/app_bar.dart index 9868a91..3692690 100644 --- a/lib/widgets/app_bar.dart +++ b/lib/widgets/app_bar.dart @@ -16,10 +16,10 @@ import 'package:rainbow_color/rainbow_color.dart'; import 'dialog_html.dart'; class AppBarNav extends StatefulWidget implements PreferredSizeWidget { - final MenuBloc menuBloc; - final bool isMenu; - final int depth; - const AppBarNav({this.menuBloc, this.isMenu, this.depth}); + final MenuBloc? menuBloc; + final bool? isMenu; + final int? depth; + AppBarNav({this.menuBloc, this.isMenu, this.depth}); @override _AppBarNav createState() => _AppBarNav(); @@ -29,9 +29,9 @@ class AppBarNav extends StatefulWidget implements PreferredSizeWidget { } class _AppBarNav extends State with SingleTickerProviderStateMixin, Common { - Animation colorAnim; - AnimationController colorController; - MenuBloc menuBloc; + late Animation colorAnim; + late AnimationController colorController; + late MenuBloc menuBloc; @override void initState() { @@ -83,7 +83,6 @@ class _AppBarNav extends State with SingleTickerProviderStateMixin, C children: [ Image.asset( 'asset/image/WT_long_logo.png', - //fit: BoxFit.cover, height: 45.0, ), getTestServer(), @@ -94,12 +93,12 @@ class _AppBarNav extends State with SingleTickerProviderStateMixin, C leading: IconButton( icon: Icon(Icons.arrow_back, color: Colors.white), onPressed: () => { - timerBloc.add(TimerEnd()), + timerBloc.add(TimerEnd(duration: 0)), if (widget.isMenu != null) { if (menuBloc.workoutItem != null) { - menuBloc.add(MenuTreeUp(parent: menuBloc.workoutItem.parent)), + menuBloc.add(MenuTreeUp(parent: menuBloc.workoutItem!.parent)), } } else if (widget.depth != null) @@ -148,18 +147,18 @@ class _AppBarNav extends State with SingleTickerProviderStateMixin, C ExerciseRepository exerciseRepository = ExerciseRepository(); exerciseRepository.getBaseExerciseFinishedPercent(); percent = Cache().getPercentExercises(); - if (percent == null || percent == -1) { + if (percent == -1) { percent = 0; } } - if (percent == null || percent.isNaN) { + if (percent.isNaN) { percent = 0; } - int sizeExerciseList = Cache().getExercises() == null ? 0 : Cache().getExercises().length; + int sizeExerciseList = Cache().getExercises() == null ? 0 : Cache().getExercises()!.length; if (sizeExerciseList == 0) { - String text = AppLocalizations.of(context).translate("Make your first test"); + String text = AppLocalizations.of(context)!.translate("Make your first test"); double fontSize = text.length > 24 ? 13 : 16; - return Stack(alignment: Alignment.topLeft, overflow: Overflow.clip, children: [ + return Stack(alignment: Alignment.topLeft, children: [ GestureDetector( onTap: () => progressExplanation(), child: Text( @@ -178,7 +177,7 @@ class _AppBarNav extends State with SingleTickerProviderStateMixin, C lineHeight: 14.0, percent: percent, center: Text( - (percent * 100).toStringAsFixed(0) + "% " + AppLocalizations.of(context).translate("finished"), + (percent * 100).toStringAsFixed(0) + "% " + AppLocalizations.of(context)!.translate("finished"), style: new TextStyle(fontSize: 10.0), ), trailing: Icon( @@ -201,8 +200,8 @@ class _AppBarNav extends State with SingleTickerProviderStateMixin, C context: context, builder: (BuildContext context) { return DialogHTML( - title: AppLocalizations.of(context).translate("Progressindicator for the tests"), - htmlData: AppLocalizations.of(context).translate("Progressindicator_desc"), + title: AppLocalizations.of(context)!.translate("Progressindicator for the tests"), + htmlData: AppLocalizations.of(context)!.translate("Progressindicator_desc"), ); }); } diff --git a/lib/widgets/app_bar_min.dart b/lib/widgets/app_bar_min.dart index 3eaeee9..44ad236 100644 --- a/lib/widgets/app_bar_min.dart +++ b/lib/widgets/app_bar_min.dart @@ -37,7 +37,6 @@ class _AppBarNav extends State with Common { children: [ Image.asset( 'asset/image/WT_long_logo.png', - //fit: BoxFit.cover, height: 45.0, ), getTestServer(), @@ -48,7 +47,7 @@ class _AppBarNav extends State with Common { leading: IconButton( icon: Icon(Icons.arrow_back, color: widget.back ? Colors.white : Colors.black), onPressed: () => { - timerBloc.add(TimerEnd()), + timerBloc.add(TimerEnd(duration: 0)), if (widget.back) {Navigator.of(context).pop()} }, )); diff --git a/lib/widgets/app_bar_progress.dart b/lib/widgets/app_bar_progress.dart index 423804d..d1ce76c 100644 --- a/lib/widgets/app_bar_progress.dart +++ b/lib/widgets/app_bar_progress.dart @@ -8,7 +8,7 @@ import 'package:liquid_progress_indicator/liquid_progress_indicator.dart'; class AppBarProgress extends StatefulWidget implements PreferredSizeWidget { final int max; final int min; - const AppBarProgress({this.max, this.min}); + const AppBarProgress({required this.max, required this.min}); @override _AppBarNav createState() => _AppBarNav(); @@ -18,7 +18,7 @@ class AppBarProgress extends StatefulWidget implements PreferredSizeWidget { } class _AppBarNav extends State with SingleTickerProviderStateMixin, Common { - AnimationController _animationController; + late AnimationController _animationController; @override void initState() { @@ -50,7 +50,7 @@ class _AppBarNav extends State with SingleTickerProviderStateMix title: getAnimatedWidget(), leading: IconButton( icon: Icon(Icons.arrow_back, color: Colors.white), - onPressed: () => {timerBloc.add(TimerEnd()), Navigator.of(context).pop()}, + onPressed: () => {timerBloc.add(TimerEnd(duration: 0)), Navigator.of(context).pop()}, )); } diff --git a/lib/widgets/bmi_widget.dart b/lib/widgets/bmi_widget.dart index f31db27..533e321 100644 --- a/lib/widgets/bmi_widget.dart +++ b/lib/widgets/bmi_widget.dart @@ -1,7 +1,6 @@ import 'package:aitrainer_app/bloc/exercise_new/exercise_new_bloc.dart'; import 'package:aitrainer_app/util/app_localization.dart'; import 'package:aitrainer_app/util/trans.dart'; -import 'package:animated_widgets/widgets/rotation_animated.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -12,7 +11,7 @@ import 'package:keyboard_actions/keyboard_actions.dart'; // ignore: must_be_immutable class BMI extends StatefulWidget { final ExerciseNewBloc exerciseBloc; - BMI({this.exerciseBloc}); + BMI({required this.exerciseBloc}); @override _BMIState createState() => _BMIState(); @@ -37,7 +36,7 @@ class _BMIState extends State with Trans { padding: EdgeInsets.all(8.0), color: Colors.orange[500], child: Text( - AppLocalizations.of(context).translate("Done"), + AppLocalizations.of(context)!.translate("Done"), style: TextStyle(color: Colors.white), ), ), @@ -55,7 +54,7 @@ class _BMIState extends State with Trans { color: Colors.orange, padding: EdgeInsets.all(8.0), child: Text( - AppLocalizations.of(context).translate("Done"), + AppLocalizations.of(context)!.translate("Done"), style: TextStyle(color: Colors.white), ), ), @@ -147,7 +146,8 @@ class _BMIState extends State with Trans { Positioned( top: widget.exerciseBloc.bmiTop, left: widget.exerciseBloc.bmiLeft, - child: RotationAnimatedWidget.tween( + child: + Container() /* RotationAnimatedWidget.tween( enabled: true, duration: const Duration(milliseconds: 1000), rotationDisabled: Rotation.deg(), @@ -155,7 +155,8 @@ class _BMIState extends State with Trans { child: Image.asset( "asset/image/BMI_mutato.png", width: 65, - ))) + )) */ + ) ]), Divider(color: Colors.transparent), Container( @@ -240,13 +241,13 @@ class _BMIState extends State with Trans { } Widget getHeightInput() { - if (widget.exerciseBloc.customerRepository.customer.birthYear < 2003) { + if (widget.exerciseBloc.customerRepository.customer.birthYear! < 2003) { return Flexible( child: TextFormField( focusNode: _nodeText2, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 15, top: 5, bottom: 5), - labelText: AppLocalizations.of(context).translate("Actual Height"), + labelText: AppLocalizations.of(context)!.translate("Actual Height"), labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, @@ -283,7 +284,7 @@ class _BMIState extends State with Trans { focusNode: _nodeText1, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 15, top: 5, bottom: 5), - labelText: AppLocalizations.of(context).translate("Actual Weight"), + labelText: AppLocalizations.of(context)!.translate("Actual Weight"), labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, diff --git a/lib/widgets/bmr_widget.dart b/lib/widgets/bmr_widget.dart index 38acc1e..b5bdc16 100644 --- a/lib/widgets/bmr_widget.dart +++ b/lib/widgets/bmr_widget.dart @@ -1,8 +1,9 @@ import 'package:aitrainer_app/bloc/exercise_new/exercise_new_bloc.dart'; -import 'package:aitrainer_app/library/dropdown_search.dart'; +//import 'package:aitrainer_app/library/dropdown_search.dart'; import 'package:aitrainer_app/util/app_localization.dart'; import 'package:aitrainer_app/model/fitness_state.dart'; import 'package:aitrainer_app/util/trans.dart'; +import 'package:dropdown_search/dropdown_search.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -14,7 +15,7 @@ import 'package:keyboard_actions/keyboard_actions.dart'; class BMR extends StatefulWidget { final ExerciseNewBloc exerciseBloc; - BMR({this.exerciseBloc}); + BMR({required this.exerciseBloc}); @override _BMRState createState() => _BMRState(); @@ -42,7 +43,7 @@ class _BMRState extends State with Trans { padding: EdgeInsets.all(8.0), color: Colors.orange[500], child: Text( - AppLocalizations.of(context).translate("Done"), + AppLocalizations.of(context)!.translate("Done"), style: TextStyle(color: Colors.white), ), ), @@ -57,7 +58,7 @@ class _BMRState extends State with Trans { padding: EdgeInsets.all(8.0), color: Colors.orange[500], child: Text( - AppLocalizations.of(context).translate("Done"), + AppLocalizations.of(context)!.translate("Done"), style: TextStyle(color: Colors.white), ), ), @@ -75,7 +76,7 @@ class _BMRState extends State with Trans { color: Colors.orange, padding: EdgeInsets.all(8.0), child: Text( - AppLocalizations.of(context).translate("Done"), + AppLocalizations.of(context)!.translate("Done"), style: TextStyle(color: Colors.white), ), ), @@ -195,13 +196,13 @@ class _BMRState extends State with Trans { } Widget getHeightInput() { - if (widget.exerciseBloc.customerRepository.customer.birthYear < 2003) { + if (widget.exerciseBloc.customerRepository.customer.birthYear! < 2003) { return Flexible( child: TextFormField( focusNode: _nodeText2, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5), - labelText: AppLocalizations.of(context).translate("Actual Height"), + labelText: AppLocalizations.of(context)!.translate("Actual Height"), labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, @@ -228,7 +229,7 @@ class _BMRState extends State with Trans { focusNode: _nodeText3, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5), - labelText: AppLocalizations.of(context).translate("Birth Year"), + labelText: AppLocalizations.of(context)!.translate("Birth Year"), labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, @@ -306,7 +307,7 @@ class _BMRState extends State with Trans { ); } - Widget _customDropDownItem(BuildContext context, FitnessState item, String itemDesignation) { + Widget _customDropDownItem(BuildContext context, FitnessState? item, String itemDesignation) { return Container( child: (item == null) ? ListTile( @@ -350,7 +351,7 @@ class _BMRState extends State with Trans { focusNode: _nodeText1, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 10, top: 5, bottom: 5), - labelText: AppLocalizations.of(context).translate("Actual Weight"), + labelText: AppLocalizations.of(context)!.translate("Actual Weight"), labelStyle: GoogleFonts.inter(fontSize: 16, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, diff --git a/lib/widgets/bottom_bar_multiple_exercises.dart b/lib/widgets/bottom_bar_multiple_exercises.dart index 65300f5..4b4188e 100644 --- a/lib/widgets/bottom_bar_multiple_exercises.dart +++ b/lib/widgets/bottom_bar_multiple_exercises.dart @@ -14,14 +14,14 @@ import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:modal_progress_hud/modal_progress_hud.dart'; +import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart'; import 'package:flutter/cupertino.dart'; // ignore: must_be_immutable class BottomBarMultipleExercises extends StatefulWidget { - bool isSet = false; - final List details; - int exerciseTypeId; + bool? isSet = false; + final List? details; + int? exerciseTypeId; BottomBarMultipleExercises({this.details, this.isSet, this.exerciseTypeId}); @override @@ -33,19 +33,19 @@ class _BottomBarMultipleExercisesState extends State final Color bgrColorEnd = Colors.blue; final Color active = Colors.black; final Color inactive = Colors.black26; - ScrollController _controller; + ScrollController? _controller; @override void initState() { super.initState(); - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { _controller = ScrollController(); }); } @override void dispose() { - _controller.dispose(); + _controller!.dispose(); super.dispose(); } @@ -57,7 +57,7 @@ class _BottomBarMultipleExercisesState extends State // ignore: close_sinks final TestSetExecuteBloc bloc = BlocProvider.of(context); bloc.menuBloc = menuBloc; - bloc.setExerciseTypeId(widget.exerciseTypeId); + bloc.setExerciseTypeId(widget.exerciseTypeId!); bloc.add(TestSetExecuteLoad()); return Container( decoration: BoxDecoration( @@ -74,7 +74,7 @@ class _BottomBarMultipleExercisesState extends State height: 90, child: BlocConsumer(listener: (context, state) { if (state is TestSetExecuteError) { - Scaffold.of(context) + ScaffoldMessenger.of(context) .showSnackBar(SnackBar(backgroundColor: Colors.orange, content: Text(state.message, style: TextStyle(color: Colors.white)))); } }, builder: (context, state) { @@ -107,8 +107,8 @@ class _BottomBarMultipleExercisesState extends State } List getChildren(TestSetExecuteBloc bloc) { - final List list = List(); - if (!widget.isSet && !bloc.hasBegun()) { + final List list = []; + if (!widget.isSet! && !bloc.hasBegun()) { list.add(GestureDetector( onTap: () => newExercise(bloc), child: ClipRRect( @@ -131,10 +131,10 @@ class _BottomBarMultipleExercisesState extends State //if (bloc.miniTestSet && widget.isSet || bloc.paralellTest && !widget.isSet) { if (bloc.exercisePlanDetails != null) { - bloc.exercisePlanDetails.forEach((element) { + bloc.exercisePlanDetails!.forEach((element) { final bool highlighted = element.exerciseTypeId == widget.exerciseTypeId; - list.add(getImageStack(element.exerciseType.nameTranslation, bloc, element.exerciseTypeId, - bloc.getActualImageName(element.exerciseType.exerciseTypeId), + list.add(getImageStack(element.exerciseType!.nameTranslation, bloc, element.exerciseTypeId, + bloc.getActualImageName(element.exerciseType!.exerciseTypeId), highlighted: highlighted)); }); // } @@ -179,11 +179,11 @@ class _BottomBarMultipleExercisesState extends State ), ]))), actions: [ - FlatButton( + TextButton( child: Text(t("No")), onPressed: () => Navigator.pop(context), ), - FlatButton( + TextButton( child: Text(t("Yes")), onPressed: () => { Navigator.pop(context), @@ -198,7 +198,7 @@ class _BottomBarMultipleExercisesState extends State } void addNewExercise(TestSetExecuteBloc bloc) { - WorkoutMenuTree foundMenuItem; + WorkoutMenuTree? foundMenuItem; showDialog( context: context, builder: (BuildContext context) { @@ -207,9 +207,9 @@ class _BottomBarMultipleExercisesState extends State if (foundMenuItem != null) { bloc.add(TestSetExecuteDeleteActive()), - bloc.add(TestSetExecuteNewExercise(exerciseTypeId: widget.exerciseTypeId)), - bloc.add(TestSetExecuteNewExercise(exerciseTypeId: foundMenuItem.exerciseTypeId)), - Track().track(TrackingEvent.exercise_new_paralell, eventValue: foundMenuItem.exerciseType.name), + bloc.add(TestSetExecuteNewExercise(exerciseTypeId: widget.exerciseTypeId!)), + bloc.add(TestSetExecuteNewExercise(exerciseTypeId: foundMenuItem!.exerciseTypeId)), + Track().track(TrackingEvent.exercise_new_paralell, eventValue: foundMenuItem!.exerciseType!.name), }, Navigator.pop(context), }, @@ -225,7 +225,7 @@ class _BottomBarMultipleExercisesState extends State } List imageSliders(TestSetExecuteBloc bloc) { - List list = List(); + List list = []; final Widget widget = ClipRRect( borderRadius: BorderRadius.circular(24.0), child: GestureDetector( @@ -265,7 +265,7 @@ class _BottomBarMultipleExercisesState extends State //color: Colors.transparent, child: Image.asset(image), )), - !widget.isSet && !bloc.hasBegun() + !widget.isSet! && !bloc.hasBegun() ? Positioned( top: -8, child: GestureDetector( diff --git a/lib/widgets/bottom_nav.dart b/lib/widgets/bottom_nav.dart index 9c8a1af..2618466 100644 --- a/lib/widgets/bottom_nav.dart +++ b/lib/widgets/bottom_nav.dart @@ -10,7 +10,7 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BottomNavigator extends StatefulWidget { int bottomNavIndex = 0; - BottomNavigator({this.bottomNavIndex}) { + BottomNavigator({required this.bottomNavIndex}) { this.bottomNavIndex = bottomNavIndex; } @@ -45,11 +45,10 @@ class _NawDrawerWidget extends State with Trans, Logging { fixedColor: active, items: [ BottomNavigationBarItem( - backgroundColor: bgrColor, - icon: Common.badgedIcon(inactive, Icons.home, "home"), - activeIcon: Common.badgedIcon(active, Icons.home, "home"), - title: Text(t("Home"), style: TextStyle(fontSize: 12)), - ), + backgroundColor: bgrColor, + icon: Common.badgedIcon(inactive, Icons.home, "home"), + activeIcon: Common.badgedIcon(active, Icons.home, "home"), + title: Text(t("Home"), style: TextStyle(fontSize: 12))), BottomNavigationBarItem( backgroundColor: bgrColor, icon: Common.badgedIcon(inactive, Icons.trending_up, "development"), diff --git a/lib/widgets/dialog_common.dart b/lib/widgets/dialog_common.dart index c72a6ad..11aee68 100644 --- a/lib/widgets/dialog_common.dart +++ b/lib/widgets/dialog_common.dart @@ -6,12 +6,20 @@ import 'package:google_fonts/google_fonts.dart'; class DialogCommon extends StatefulWidget { final String title, descriptions, text; final VoidCallback onTap; - final VoidCallback onCancel; - String description2, description3; - final Image img; + final VoidCallback? onCancel; + String? description2, description3; + final Image? img; DialogCommon( - {Key key, this.title, this.descriptions, this.description2, this.description3, this.text, this.img, this.onTap, this.onCancel}) + {Key? key, + required this.title, + required this.descriptions, + this.description2, + this.description3, + required this.text, + this.img, + required this.onTap, + required this.onCancel}) : super(key: key) { description2 = description2 ?? ""; description3 = description3 ?? ""; @@ -113,7 +121,7 @@ class _DialogPremiumState extends State with Trans { height: 15, ), Text( - widget.description2, + widget.description2!, style: GoogleFonts.inter( fontSize: 16, color: Colors.white, @@ -136,7 +144,7 @@ class _DialogPremiumState extends State with Trans { height: 15, ), Text( - widget.description3, + widget.description3!, style: GoogleFonts.inter( fontSize: 16, color: Colors.white, @@ -161,7 +169,7 @@ class _DialogPremiumState extends State with Trans { Align( alignment: Alignment.center, child: GestureDetector( - onTap: widget.onTap ?? widget.onTap, + onTap: widget.onTap, child: Stack( alignment: Alignment.center, children: [ @@ -182,7 +190,7 @@ class _DialogPremiumState extends State with Trans { if (widget.onCancel == null) { Navigator.of(context).pop(); } else { - widget.onCancel(); + widget.onCancel!(); } }, child: CircleAvatar( diff --git a/lib/widgets/dialog_html.dart b/lib/widgets/dialog_html.dart index 8777217..eb107a7 100644 --- a/lib/widgets/dialog_html.dart +++ b/lib/widgets/dialog_html.dart @@ -8,7 +8,7 @@ import 'package:google_fonts/google_fonts.dart'; class DialogHTML extends StatefulWidget { final String title; final String htmlData; - DialogHTML({Key key, this.title, this.htmlData}) : super(key: key); + DialogHTML({Key? key, required this.title, required this.htmlData}) : super(key: key); @override _DialogPremiumState createState() { diff --git a/lib/widgets/dialog_long.dart b/lib/widgets/dialog_long.dart index 86c174c..576974c 100644 --- a/lib/widgets/dialog_long.dart +++ b/lib/widgets/dialog_long.dart @@ -6,7 +6,7 @@ import 'package:google_fonts/google_fonts.dart'; // ignore: must_be_immutable class DialogGDPR extends StatefulWidget { - DialogGDPR({Key key}) : super(key: key); + DialogGDPR({Key? key}) : super(key: key); @override _DialogPremiumState createState() { diff --git a/lib/widgets/dialog_premium.dart b/lib/widgets/dialog_premium.dart index 24a8249..400fb39 100644 --- a/lib/widgets/dialog_premium.dart +++ b/lib/widgets/dialog_premium.dart @@ -8,21 +8,21 @@ import 'package:google_fonts/google_fonts.dart'; // ignore: must_be_immutable class DialogPremium extends StatefulWidget { final VoidCallback onTap; - final VoidCallback onCancel; - String description, function, unlockedText; + final VoidCallback? onCancel; + String? description, function, unlockedText; final int unlockRound; bool unlocked; DialogPremium( - {Key key, - @required this.unlockRound, + {Key? key, + required this.unlockRound, this.description, - this.onTap, + required this.onTap, this.onCancel, - @required this.unlocked, + required this.unlocked, this.unlockedText, - @required this.function}) + required this.function}) : super(key: key) { description = description ?? ""; function = function ?? ""; @@ -36,7 +36,8 @@ class DialogPremium extends StatefulWidget { class _DialogPremiumState extends State with Trans { bool isStart = true; - Timer _timer; + late Timer _timer; + @override Widget build(BuildContext context) { setContext(context); @@ -182,7 +183,7 @@ class _DialogPremiumState extends State with Trans { if (widget.onCancel == null) { Navigator.of(context).pop(); } else { - widget.onCancel(); + widget.onCancel!(); } }, child: CircleAvatar( @@ -221,7 +222,7 @@ class _DialogPremiumState extends State with Trans { } List getDescriptionText() { - List list = List(); + List list = []; if (widget.unlockedText != null) { list.add(TextSpan(text: widget.unlockedText)); @@ -231,7 +232,7 @@ class _DialogPremiumState extends State with Trans { list.add(TextSpan(text: t(" "))); list.add( TextSpan( - text: t(widget.function), + text: t(widget.function!), style: GoogleFonts.inter( fontSize: 14, fontWeight: FontWeight.bold, diff --git a/lib/widgets/dialog_widget.dart b/lib/widgets/dialog_widget.dart index d02f6f6..3b4060c 100644 --- a/lib/widgets/dialog_widget.dart +++ b/lib/widgets/dialog_widget.dart @@ -7,9 +7,10 @@ class DialogWidget extends StatefulWidget { final String title, description; final Widget widget; final VoidCallback onTap; - final VoidCallback onCancel; + final VoidCallback? onCancel; - DialogWidget({Key key, this.title, this.description, this.widget, this.onTap, this.onCancel}) : super(key: key); + DialogWidget({Key? key, required this.title, required this.description, required this.widget, required this.onTap, this.onCancel}) + : super(key: key); @override _DialogPremiumState createState() { @@ -112,7 +113,7 @@ class _DialogPremiumState extends State with Trans { Align( alignment: Alignment.center, child: GestureDetector( - onTap: widget.onTap ?? widget.onTap, + onTap: widget.onTap, child: Stack( alignment: Alignment.center, children: [ @@ -133,7 +134,7 @@ class _DialogPremiumState extends State with Trans { if (widget.onCancel == null) { Navigator.of(context).pop(); } else { - widget.onCancel(); + widget.onCancel!(); } }, child: CircleAvatar( diff --git a/lib/widgets/exercise_save.dart b/lib/widgets/exercise_save.dart index 80b6d0b..1a357fb 100644 --- a/lib/widgets/exercise_save.dart +++ b/lib/widgets/exercise_save.dart @@ -13,10 +13,10 @@ import 'dialog_html.dart'; // ignore: must_be_immutable class ExerciseSave extends StatefulWidget { final ValueChanged onQuantityChanged; - final ValueChanged onUnitQuantityChanged; - final VoidCallback onSubmit; + final ValueChanged? onUnitQuantityChanged; + final VoidCallback? onSubmit; final bool hasUnitQuantity; - final String unitQuantityUnit; + final String? unitQuantityUnit; final String unit; final String exerciseName; final String exerciseDescription; @@ -24,16 +24,16 @@ class ExerciseSave extends StatefulWidget { final int exerciseTypeId; ExerciseSave( - {this.onQuantityChanged, + {required this.onQuantityChanged, this.onUnitQuantityChanged, this.onSubmit, - this.hasUnitQuantity, + required this.hasUnitQuantity, this.unitQuantityUnit, - this.unit, - this.exerciseName, - this.exerciseDescription, - this.exerciseTask, - this.exerciseTypeId}); + required this.unit, + required this.exerciseName, + required this.exerciseDescription, + required this.exerciseTask, + required this.exerciseTypeId}); @override _ExerciseSaveState createState() => _ExerciseSaveState(); } @@ -231,7 +231,7 @@ class _ExerciseSaveState extends State with Trans { Divider( color: Colors.transparent, ), - /* FlatButton( + /* TextButton( onPressed: () { widget.onSubmit(); /* showDialog( @@ -265,7 +265,7 @@ class _ExerciseSaveState extends State with Trans { controller: _controller1, decoration: InputDecoration( contentPadding: EdgeInsets.only(left: 25, top: 5, bottom: 5), - labelText: t(widget.unitQuantityUnit), + labelText: t(widget.unitQuantityUnit!), labelStyle: GoogleFonts.inter(fontSize: 20, color: Colors.yellow[50]), fillColor: Colors.black38, filled: true, @@ -278,7 +278,7 @@ class _ExerciseSaveState extends State with Trans { keyboardType: TextInputType.numberWithOptions(decimal: true), textInputAction: TextInputAction.done, style: GoogleFonts.archivoBlack(fontSize: 80, color: Colors.yellow[300]), - onChanged: (value) => widget.onUnitQuantityChanged(value)), + onChanged: (value) => widget.onUnitQuantityChanged!(value)), ]); } return row; @@ -291,10 +291,10 @@ class _ExerciseSaveState extends State with Trans { padding: const EdgeInsets.only(bottom: 0), child: StreamBuilder( stream: stopWatchTimer.rawTime, - initialData: stopWatchTimer.rawTime.value, + initialData: stopWatchTimer.rawTime.valueWrapper?.value, builder: (context, snap) { final value = snap.data; - final displayTime = StopWatchTimer.getDisplayTime(value, hours: false); + final displayTime = StopWatchTimer.getDisplayTime(value!, hours: false); return Column(children: [ Padding( padding: const EdgeInsets.all(8), diff --git a/lib/widgets/home.dart b/lib/widgets/home.dart index 83bfd9e..d0d47ca 100644 --- a/lib/widgets/home.dart +++ b/lib/widgets/home.dart @@ -14,7 +14,7 @@ import 'loading.dart'; // ignore: must_be_immutable class AitrainerHome extends StatefulWidget { - _HomePageState _state; + late _HomePageState _state; @override State createState() { _state = new _HomePageState(); @@ -30,22 +30,20 @@ class _HomePageState extends State with Logging { super.initState(); /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { runDelayedEvent(); }); } Future runDelayedEvent() async { await Future.delayed(Duration(seconds: 2), () async { - if (context != null) { + // ignore: close_sinks + SessionBloc sessionBloc = BlocProvider.of(context); + if (sessionBloc.state != SessionReady()) { // ignore: close_sinks - SessionBloc sessionBloc = BlocProvider.of(context); - if (sessionBloc.state != SessionReady()) { - // ignore: close_sinks - SettingsBloc settingsBloc = BlocProvider.of(context); - settingsBloc.context = context; - sessionBloc.add(SessionStart(settingsBloc: settingsBloc)); - } + SettingsBloc settingsBloc = BlocProvider.of(context); + settingsBloc.context = context; + sessionBloc.add(SessionStart(settingsBloc: settingsBloc)); } }); } @@ -56,7 +54,7 @@ class _HomePageState extends State with Logging { key: _scaffoldKey, body: BlocConsumer(listener: (context, state) { if (state is SessionFailure) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( state.message, ), diff --git a/lib/widgets/image_button.dart b/lib/widgets/image_button.dart index dcc4563..613c8ed 100644 --- a/lib/widgets/image_button.dart +++ b/lib/widgets/image_button.dart @@ -9,38 +9,39 @@ import 'package:google_fonts/google_fonts.dart'; // ignore: must_be_immutable class ImageButton extends StatelessWidget { final String text; - TextStyle style = TextStyle(fontSize: 14); - final String image; - double top; + TextStyle? style = TextStyle(fontSize: 14); + final String? image; + double? top; final double left; - double height; - double width; - bool isShape; - final Bloc bloc; + double? height; + double? width; + bool? isShape; + final Bloc? bloc; final Alignment textAlignment; - final VoidCallback onTap; - bool isLocked; - bool isMarked; - int buttonIndex; + final VoidCallback? onTap; + final bool? isLocked; + bool? isMarked; + int? buttonIndex; ImageButton( - {this.text, + {required this.text, this.style, - this.image, + required this.image, this.top, - this.left, + required this.left, this.height, this.width, this.bloc, this.isShape, - this.textAlignment, + required this.textAlignment, this.onTap, this.buttonIndex, this.isMarked, - @required this.isLocked}) { + required this.isLocked}) { width = width ?? 180; height = height ?? 180; isMarked = isMarked ?? false; + isShape = isShape ?? false; style = style ?? GoogleFonts.archivoBlack( fontSize: 14, @@ -50,19 +51,25 @@ class ImageButton extends StatelessWidget { @override Widget build(BuildContext context) { if (top == null) { - top = height - (style.fontSize - 5) * text.length - 2 * left < 0 ? height - 2 * style.fontSize - 22 : height - style.fontSize - 37; + top = height! - (style!.fontSize! - 5) * text.length - 2 * left < 0 + ? height! - 2 * style!.fontSize! - 22 + : height! - style!.fontSize! - 37; //print("Top: " + top.toStringAsFixed(0) + " length: " + ((style.fontSize - 5) * text.length).toString()); } final double width = MediaQuery.of(context).size.width; //print("Mediawidth: " + width.toStringAsFixed(0)); return Stack(alignment: AlignmentDirectional.bottomStart, children: [ - FlatButton( + TextButton( + style: TextButton.styleFrom( + padding: EdgeInsets.only(left: 0.0, bottom: 0), + shape: getShape(isShape!), + ), child: image == null ? _getButtonImage("asset/image/WT_menu_dark.jpg") - : isMarked + : isMarked! ? Stack( children: [ - _getButtonImage(image), + _getButtonImage(image!), Container( width: width, height: height, @@ -75,9 +82,7 @@ class ImageButton extends StatelessWidget { ) ], ) - : _getButtonImage(image), - padding: EdgeInsets.only(left: 0.0, bottom: 0), - shape: getShape(isShape), + : _getButtonImage(image!), onPressed: onTap ?? onTap, ), Container( @@ -109,7 +114,7 @@ class ImageButton extends StatelessWidget { Positioned( top: 10, left: (width / 2 - 30) / 2 - 75, - child: !isLocked + child: !isLocked! ? Offstage() : GestureDetector( child: Image.asset( @@ -126,7 +131,7 @@ class ImageButton extends StatelessWidget { Positioned( top: 10, left: (width / 2 - 30) / 2 - 75, - child: isMarked + child: isMarked! ? GestureDetector( child: Image.asset( 'asset/image/haken.png', diff --git a/lib/widgets/input_dialog_widget.dart b/lib/widgets/input_dialog_widget.dart index 39473dc..498eaa1 100644 --- a/lib/widgets/input_dialog_widget.dart +++ b/lib/widgets/input_dialog_widget.dart @@ -15,7 +15,7 @@ class InputDialog extends StatefulWidget { final String subtitle; - const InputDialog({this.onChanged, this.initialValue, this.title, this.subtitle}); + const InputDialog({required this.onChanged, required this.initialValue, required this.title, required this.subtitle}); @override _InputDialogState createState() => _InputDialogState(); @@ -165,25 +165,29 @@ class _InputDialogState extends State> with Trans { Row( mainAxisSize: MainAxisSize.min, children: [ - RaisedButton( + ElevatedButton( + style: ElevatedButton.styleFrom( + primary: Colors.black26, + onSurface: Colors.white, + ), onPressed: () { Navigator.of(context).pop(); }, child: Text(t('Cancel')), - color: Colors.black26, - textColor: Colors.white, ), SizedBox( width: 8, ), - RaisedButton( + ElevatedButton( + style: ElevatedButton.styleFrom( + primary: Colors.orange[600], + onSurface: Colors.white, + ), onPressed: () { widget.onChanged(this.inputValue); return Navigator.of(context).pop(true); }, child: Text(t('Save')), - color: Colors.orange[600], - textColor: Colors.white, ) ], ) diff --git a/lib/widgets/menu_image.dart b/lib/widgets/menu_image.dart index cffe8c4..3df5113 100644 --- a/lib/widgets/menu_image.dart +++ b/lib/widgets/menu_image.dart @@ -2,20 +2,20 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:aitrainer_app/library/image_cache.dart' as wt; -import 'package:transparent_image/transparent_image.dart'; +import 'package:aitrainer_app/library/transparent_image.dart'; class MenuImage extends StatelessWidget { - final int workoutTreeId; + final int? workoutTreeId; final String imageName; - const MenuImage({this.workoutTreeId, this.imageName}); + const MenuImage({required this.workoutTreeId, required this.imageName}); @override Widget build(BuildContext context) { if (workoutTreeId == null) { return Offstage(); } - String imageString = this.getImage(workoutTreeId, imageName); - Widget widget; + String? imageString = this.getImage(workoutTreeId!, imageName); + Widget? widget; if (imageString != null) { widget = ClipRRect( borderRadius: BorderRadius.circular(24.0), @@ -29,7 +29,7 @@ class MenuImage extends StatelessWidget { )); } else { if (imageName.contains("https")) { - if (!wt.ImageCache().existsImageInMap(workoutTreeId, imageName)) { + if (!wt.ImageCache().existsImageInMap(workoutTreeId!, imageName)) { widget = ClipRRect( borderRadius: BorderRadius.circular(24.0), child: Container( @@ -56,8 +56,8 @@ class MenuImage extends StatelessWidget { return widget; } - String getImage(int id, String name) { - String imageString; + String? getImage(int id, String name) { + String? imageString; if (name.contains("http")) { imageString = wt.ImageCache().getImageString(id, name); } diff --git a/lib/widgets/menu_info_widget.dart b/lib/widgets/menu_info_widget.dart deleted file mode 100644 index be96613..0000000 --- a/lib/widgets/menu_info_widget.dart +++ /dev/null @@ -1,100 +0,0 @@ -import 'dart:ui'; - -import 'package:aitrainer_app/bloc/menu/menu_bloc.dart'; -import 'package:aitrainer_app/util/common.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; - -// ignore: must_be_immutable -class MenuInfoWidget extends StatelessWidget with Common { - final String title; - final double titleSize; - final Color titleColor; - final FontWeight titleWeight; - final String text; - final double textSize; - final Color textColor; - final FontWeight textWeight; - final Icon leadingIcon; - final Color leadingIconColor; - final String text2; - final String text3; - final String link; - final int parentMenu; - final MenuBloc bloc; - - MenuInfoWidget( - {this.title, - this.titleSize, - this.titleColor, - this.titleWeight, - @required this.text, - this.textSize, - this.textColor, - this.textWeight, - this.leadingIcon, - this.leadingIconColor, - this.text2, - this.text3, - this.link, - this.parentMenu, - this.bloc}); - - @override - Widget build(BuildContext context) { - return Container( - padding: EdgeInsets.only(top: 10.0, left: 15, right: 10, bottom: 5), - - decoration: BoxDecoration( - color: Colors.black.withOpacity(0.5), - border: Border.all(color: Colors.white60), - borderRadius: BorderRadius.all(Radius.circular(16.0)), - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - title, - maxLines: 4, - textAlign: TextAlign.center, - style: TextStyle(color: titleColor, fontSize: titleSize, fontWeight: titleWeight), - ), - Divider(), - Text( - text, - maxLines: 6, - style: TextStyle(color: textColor, fontSize: textSize, fontWeight: textWeight), - ), - /* Divider(), - Text( - text2, - maxLines: 6, - style: TextStyle( - color: textColor, fontSize: textSize, fontWeight: textWeight), - ), */ - Divider(), - Text( - text3, - maxLines: 6, - style: TextStyle(color: textColor, fontSize: textSize, fontWeight: textWeight), - ), - getLink(), - ], - ), - //), - // ) - ); - } - - Widget getLink() { - int missingId; - return InkWell( - child: new Text( - link, - style: TextStyle(color: Colors.lightBlueAccent, fontSize: textSize, fontFamily: 'Arial', fontWeight: textWeight), - ), - onTap: () => - {missingId = bloc.menuTreeRepository.getMissingTreeIdByName(bloc.missingTreeName), bloc.add(MenuTreeJump(parent: missingId))}); - } -} diff --git a/lib/widgets/menu_page_widget.dart b/lib/widgets/menu_page_widget.dart index debe861..df23b78 100644 --- a/lib/widgets/menu_page_widget.dart +++ b/lib/widgets/menu_page_widget.dart @@ -27,7 +27,7 @@ import 'dialog_html.dart'; // ignore: must_be_immutable class MenuPageWidget extends StatefulWidget { - int parent; + int? parent; MenuPageWidget({this.parent}); @@ -38,7 +38,7 @@ class MenuPageWidget extends StatefulWidget { class _MenuPageWidgetState extends State with Trans, Logging { final double baseWidth = 312; final double baseHeight = 675.2; - MenuBloc menuBloc; + late MenuBloc menuBloc; final scrollController = ScrollController(); final bool activeExercisePlan = Cache().activeExercisePlan != null; final EzAnimation animation = EzAnimation(35.0, 10.0, Duration(seconds: 2), reverseCurve: Curves.linear); @@ -58,7 +58,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { } /// We require the initializers to run after the loading screen is rendered - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { menuBloc.add(MenuCreate()); }); @@ -79,15 +79,19 @@ class _MenuPageWidgetState extends State with Trans, Logging { double cWidth = MediaQuery.of(context).size.width; double cHeight = MediaQuery.of(context).size.height; + if (widget.parent == null) { + widget.parent = 0; + } + return CustomScrollView( // Must add scrollController to sliver root controller: scrollController, scrollDirection: Axis.vertical, - slivers: buildMenuColumn(widget.parent, context, menuBloc, cWidth, cHeight)); + slivers: buildMenuColumn(widget.parent!, context, menuBloc, cWidth, cHeight)); } List buildMenuColumn(int parent, BuildContext context, MenuBloc menuBloc, double cWidth, double cHeight) { - final List slivers = List(); + final List slivers = []; bool isChild = menuBloc.menuTreeRepository.isChildAndGym(menuBloc.parent); if (!isChild) { @@ -97,14 +101,14 @@ class _MenuPageWidgetState extends State with Trans, Logging { slivers.add(getFilterElements(menuBloc)); } - final List _columnChildren = List(); + final List _columnChildren = []; if (menuBloc.getFilteredBranch(menuBloc.parent).isEmpty) { _columnChildren.add(Container( padding: EdgeInsets.only(top: 15.0), child: Center( child: Stack(alignment: Alignment.bottomLeft, children: [ - Text(AppLocalizations.of(context).translate("All Exercises has been filtered out"), + Text(AppLocalizations.of(context)!.translate("All Exercises has been filtered out"), style: GoogleFonts.inter(color: Colors.white)), ])))); } else { @@ -118,9 +122,9 @@ class _MenuPageWidgetState extends State with Trans, Logging { position: BadgePosition.bottomEnd(end: 0), animationDuration: Duration(milliseconds: 500), animationType: BadgeAnimationType.slide, - badgeColor: Colors.orange[800], + badgeColor: Colors.orange[800]!, showBadge: workoutTree.base, - badgeContent: Text(AppLocalizations.of(context).translate("base"), + badgeContent: Text(AppLocalizations.of(context)!.translate("base"), style: TextStyle( color: Colors.white, fontSize: 12, @@ -129,7 +133,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { showBadge: workoutTree.nameEnglish == "One Rep Max" || workoutTree.nameEnglish == "Endurance", animationDuration: Duration(milliseconds: 800), animationType: BadgeAnimationType.fade, - badgeColor: Colors.blue[100], + badgeColor: Colors.blue[100]!, badgeContent: GestureDetector( onTap: () => { showDialog( @@ -138,16 +142,15 @@ class _MenuPageWidgetState extends State with Trans, Logging { return DialogHTML( title: workoutTree.name, htmlData: workoutTree.nameEnglish == "Endurance" - ? AppLocalizations.of(context).translate("Endurance_desc") - : AppLocalizations.of(context).translate("OneRepMax_desc"), + ? AppLocalizations.of(context)!.translate("Endurance_desc") + : AppLocalizations.of(context)!.translate("OneRepMax_desc"), ); }) }, child: Icon(Icons.info_outline_rounded)), child: Stack(alignment: Alignment.bottomLeft, children: [ - FlatButton( + TextButton( child: badgedIcon(workoutTree, cWidth, cHeight), - padding: EdgeInsets.only(left: 0.0, bottom: 0), onPressed: () => menuClick(workoutTree, menuBloc, context), ), /* Container( @@ -197,7 +200,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { delegate: SliverChildListDelegate([ Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( - AppLocalizations.of(context).translate("Equipment Filter"), + AppLocalizations.of(context)!.translate("Equipment Filter"), textAlign: TextAlign.center, style: GoogleFonts.archivoBlack( fontSize: 24, @@ -229,7 +232,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { } SliverGrid getFilterElements(MenuBloc menuBloc) { - List list = List(); + List list = []; menuBloc.exerciseDeviceRepository.getGymDevices().forEach((element) { String deviceName = AppLanguage().appLocal == Locale('en') ? element.name : element.nameTranslation; @@ -299,11 +302,11 @@ class _MenuPageWidgetState extends State with Trans, Logging { listItems: menuBloc.menuTreeRepository.menuAsExercise, onFind: (value) { if (Cache().userLoggedIn == null) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: Colors.orange, - content: Text(AppLocalizations.of(context).translate('Please log in'), style: TextStyle(color: Colors.white)))); + content: Text(AppLocalizations.of(context)!.translate('Please log in'), style: TextStyle(color: Colors.white)))); } else { - Track().track(TrackingEvent.search, eventValue: value.exerciseType.name); + Track().track(TrackingEvent.search, eventValue: value.exerciseType!.name); menuBloc.ability = ExerciseAbility.oneRepMax; Navigator.of(context).pushNamed('exerciseNewPage', arguments: value.exerciseType); } @@ -348,12 +351,12 @@ class _MenuPageWidgetState extends State with Trans, Logging { void menuClick(WorkoutMenuTree workoutTree, MenuBloc menuBloc, BuildContext context) { if (Cache().userLoggedIn == null) { - Scaffold.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: Colors.orange, - content: Text(AppLocalizations.of(context).translate('Please log in'), style: TextStyle(color: Colors.white)))); + content: Text(AppLocalizations.of(context)!.translate('Please log in'), style: TextStyle(color: Colors.white)))); } else { if (workoutTree.child == false) { - if (ExerciseAbility.mini_test_set.equalsTo(menuBloc.ability) && workoutTree.parent != 0) { + if (menuBloc.ability != null && ExerciseAbility.mini_test_set.equalsTo(menuBloc.ability!) && workoutTree.parent != 0) { HashMap args = HashMap(); args['templateName'] = workoutTree.nameEnglish; args['templateNameTranslation'] = workoutTree.name; @@ -363,7 +366,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { } else { menuBloc.add(MenuClickExercise(exerciseTypeId: workoutTree.id)); - if (workoutTree.exerciseType.name == "Custom" && Cache().userLoggedIn.admin == 1) { + if (workoutTree.exerciseType!.name == "Custom" && Cache().userLoggedIn!.admin == 1) { Navigator.of(context).pushNamed('exerciseCustomPage', arguments: workoutTree.exerciseType); } else { Navigator.of(context).pushNamed('exerciseNewPage', arguments: workoutTree.exerciseType); @@ -399,11 +402,7 @@ class _MenuPageWidgetState extends State with Trans, Logging { color: Colors.white, fontSize: 16, )), - child: buttonImage == null - ? Container( - color: Colors.transparent, - ) - : buttonImage, + child: buttonImage, ); } diff --git a/lib/widgets/menu_search_bar.dart b/lib/widgets/menu_search_bar.dart index a1dd584..5e7efb2 100644 --- a/lib/widgets/menu_search_bar.dart +++ b/lib/widgets/menu_search_bar.dart @@ -2,7 +2,8 @@ import 'dart:async'; import 'package:aitrainer_app/model/workout_menu_tree.dart'; import 'package:aitrainer_app/util/trans.dart'; -import 'package:aitrainer_app/library/dropdown_search.dart'; +import 'package:dropdown_search/dropdown_search.dart'; +//import 'package:aitrainer_app/library/dropdown_search.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; @@ -25,10 +26,10 @@ class SearchBarStream { // ignore: must_be_immutable class MenuSearchBar extends StatelessWidget { - final List listItems; + final List listItems; final Function(WorkoutMenuTree) onFind; bool showIcon; - MenuSearchBar({@required this.listItems, this.onFind, this.showIcon = true}); + MenuSearchBar({required this.listItems, required this.onFind, this.showIcon = true}); @override Widget build(BuildContext context) { @@ -42,11 +43,11 @@ class MenuSearchBar extends StatelessWidget { // ignore: must_be_immutable class AnimatedSearch extends StatefulWidget { - final List listItems; + final List listItems; final Function(WorkoutMenuTree) onFind; bool showIcon = true; - AnimatedSearch({this.listItems, this.onFind, this.showIcon}); + AnimatedSearch({required this.listItems, required this.onFind, required this.showIcon}); @override _AnimatedSearch createState() => _AnimatedSearch(); @@ -117,10 +118,10 @@ class _AnimatedSearch extends State { // ignore: must_be_immutable class Search extends StatelessWidget with Trans { - final List listItems; + final List listItems; final Function(WorkoutMenuTree) onFind; - Search({this.listItems, this.onFind}); + Search({required this.listItems, required this.onFind}); @override Widget build(BuildContext context) { @@ -193,7 +194,7 @@ class Search extends StatelessWidget with Trans { textAlign: TextAlign.center, style: GoogleFonts.inter(color: Colors.yellow[200], fontSize: 16), )), - dropdownBuilder: (context, WorkoutMenuTree item, itemDesignation) => Container( + dropdownBuilder: (context, WorkoutMenuTree? item, itemDesignation) => Container( child: ListView(scrollDirection: Axis.vertical, shrinkWrap: true, children: [ (item == null) ? Container( @@ -224,8 +225,8 @@ class AnimateExpansion extends StatefulWidget { final double axisAlignment; AnimateExpansion({ this.animate = false, - this.axisAlignment, - this.child, + required this.axisAlignment, + required this.child, }); @override @@ -233,8 +234,8 @@ class AnimateExpansion extends StatefulWidget { } class _AnimateExpansionState extends State with SingleTickerProviderStateMixin { - AnimationController _animationController; - Animation _animation; + late AnimationController _animationController; + late Animation _animation; void prepareAnimations() { _animationController = AnimationController( diff --git a/lib/widgets/number_picker.dart b/lib/widgets/number_picker.dart index 1758381..7487775 100644 --- a/lib/widgets/number_picker.dart +++ b/lib/widgets/number_picker.dart @@ -10,9 +10,17 @@ class NumberPickerWidget extends StatefulWidget { final int initalValue; final String unit; final Color color; - double fontSize; + double? fontSize; - NumberPickerWidget({Key key, this.minValue, this.maxValue, this.initalValue, this.unit, this.fontSize, this.color, this.onChange}) + NumberPickerWidget( + {Key? key, + required this.minValue, + required this.maxValue, + required this.initalValue, + required this.unit, + this.fontSize, + required this.color, + required this.onChange}) : super(key: key) { fontSize = fontSize ?? 20; } @@ -21,7 +29,7 @@ class NumberPickerWidget extends StatefulWidget { } class _NumberPickerWidgetState extends State with Trans { - FixedExtentScrollController _scrollController; + late FixedExtentScrollController _scrollController; @override void initState() { diff --git a/lib/widgets/sales_button.dart b/lib/widgets/sales_button.dart index 6642f38..7bf70b9 100644 --- a/lib/widgets/sales_button.dart +++ b/lib/widgets/sales_button.dart @@ -4,30 +4,30 @@ import 'package:google_fonts/google_fonts.dart'; // ignore: must_be_immutable class SalesButton extends StatelessWidget { - TextStyle style = TextStyle(fontSize: 14); + TextStyle? style; TextStyle descStyle = TextStyle(fontSize: 14); final String title; final String price; final String desc1; final String desc2; final String desc3; - String desc4; - final String badgeText; + String? desc4; + final String? badgeText; final Color badgeColor; final VoidCallback onTap; SalesButton( - {this.title, - this.price, - this.desc1, - this.desc2, - this.desc3, + {required this.title, + required this.price, + required this.desc1, + required this.desc2, + required this.desc3, this.desc4, this.badgeText, - this.badgeColor, - this.onTap, - this.style, - this.descStyle}) { + required this.badgeColor, + required this.onTap, + required this.style, + required this.descStyle}) { style = style ?? GoogleFonts.archivoBlack( fontSize: 14, @@ -53,7 +53,7 @@ class SalesButton extends StatelessWidget { borderRadius: BorderRadius.circular(5), shape: BadgeShape.square, badgeContent: badgeText != null - ? Text(badgeText, + ? Text(badgeText!, style: TextStyle( color: Colors.white, backgroundColor: badgeColor, @@ -89,7 +89,7 @@ class SalesButton extends StatelessWidget { Container(padding: EdgeInsets.only(left: 3, right: 3, bottom: 4), child: Text(desc3, maxLines: 2, style: descStyle)), Container( padding: EdgeInsets.only(left: 3, right: 3), - child: Text(desc4, maxLines: 2, style: GoogleFonts.inter(fontSize: 10, color: Colors.red[800]))) + child: Text(desc4!, maxLines: 2, style: GoogleFonts.inter(fontSize: 10, color: Colors.red[800]))) ], ), )), diff --git a/lib/widgets/size_widget.dart b/lib/widgets/size_widget.dart index 72d49be..1cd6b20 100644 --- a/lib/widgets/size_widget.dart +++ b/lib/widgets/size_widget.dart @@ -13,7 +13,7 @@ import 'input_dialog_widget.dart'; class SizeWidget extends StatefulWidget { final ExerciseNewBloc exerciseBloc; - SizeWidget({this.exerciseBloc}); + SizeWidget({required this.exerciseBloc}); @override _SizeState createState() => _SizeState(); @@ -54,7 +54,7 @@ class _SizeState extends State with Trans { double mediaHeight = MediaQuery.of(context).size.height * .8; //print("w " + mediaWidth.toString() + "h " + mediaHeight.toString()); widget.exerciseBloc.customerRepository.setMediaDimensions(mediaWidth, mediaHeight); - List list = List(); + List list = []; list.add(GestureDetector( onTap: () => {print("Save"), widget.exerciseBloc.add(ExerciseNewSaveWeight())}, child: SizedBox( @@ -76,13 +76,14 @@ class _SizeState extends State with Trans { ), ); list.add(Positioned( - top: widget.exerciseBloc.customerRepository.getWeightCoordinate(widget.exerciseBloc.customerRepository.isMan, isTop: true).toDouble(), + top: + widget.exerciseBloc.customerRepository.getWeightCoordinate(widget.exerciseBloc.customerRepository.isMan, isTop: true)!.toDouble(), left: widget.exerciseBloc.customerRepository - .getWeightCoordinate(widget.exerciseBloc.customerRepository.isMan, isTop: false, isLeft: true) + .getWeightCoordinate(widget.exerciseBloc.customerRepository.isMan, isTop: false, isLeft: true)! .toDouble() - 45, child: GestureDetector( - onTap: () => onPressed(widget.exerciseBloc.customerRepository.getPropertyByName("Weight")), + onTap: () => onPressed(widget.exerciseBloc.customerRepository.getPropertyByName("Weight")!), child: Image.asset( "asset/image/merleg.png", height: 120, @@ -130,13 +131,13 @@ class _SizeState extends State with Trans { } List getSizeElements() { - List list = List(); + List list = []; widget.exerciseBloc.customerRepository.manSizes.forEach((element) { list.add( Positioned( - top: element.top.toDouble(), - left: element.left.toDouble(), + top: element.top!.toDouble(), + left: element.left!.toDouble(), child: element.value != 0 ? Container( width: 20, @@ -186,7 +187,7 @@ class _SizeState extends State with Trans { builder: (context) => InputDialog( title: t("Size Of Your"), subtitle: element.propertyNameTranslation, - initialValue: element.value, + initialValue: element.value!, onChanged: (value) { widget.exerciseBloc.add(ExerciseNewSizeChange(propertyName: element.propertyName, value: value)); }, diff --git a/lib/widgets/time_picker.dart b/lib/widgets/time_picker.dart index 01663b8..36a3e2c 100644 --- a/lib/widgets/time_picker.dart +++ b/lib/widgets/time_picker.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; class TimePickerWidget extends StatefulWidget { final Function(double) onChange; - const TimePickerWidget({Key key, this.onChange}) : super(key: key); + const TimePickerWidget({Key? key, required this.onChange}) : super(key: key); @override _TimePickerWidgetState createState() => _TimePickerWidgetState(); } diff --git a/lib/widgets/timer_widget.dart b/lib/widgets/timer_widget.dart index b5ee59b..78f63b7 100644 --- a/lib/widgets/timer_widget.dart +++ b/lib/widgets/timer_widget.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; class TimerWidget extends StatelessWidget { final TimerBloc bloc; - const TimerWidget({this.bloc}); + const TimerWidget({required this.bloc}); @override Widget build(BuildContext context) { diff --git a/lib/widgets/treeview_parent_widget.dart b/lib/widgets/treeview_parent_widget.dart index 67200c0..5026bd9 100644 --- a/lib/widgets/treeview_parent_widget.dart +++ b/lib/widgets/treeview_parent_widget.dart @@ -5,16 +5,16 @@ import 'package:google_fonts/google_fonts.dart'; class TreeviewParentWidget extends StatelessWidget { final String text; final Color backgroundColor; - final Color color; + final Color? color; //final DateTime lastModified; - TreeviewParentWidget({@required this.text, this.backgroundColor = Colors.white38, this.color}); + TreeviewParentWidget({required this.text, this.backgroundColor = Colors.white38, this.color}); @override Widget build(BuildContext context) { Widget parentWidget = Text( this.text, - style: GoogleFonts.archivoBlack(fontSize: 24, color: color ?? Colors.blue[800], backgroundColor: Colors.transparent), + style: GoogleFonts.archivoBlack(fontSize: 24, color: color ?? Colors.blue[800]!, backgroundColor: Colors.transparent), ); Icon icon = Icon(Icons.person); diff --git a/lib/widgets/victory_widget.dart b/lib/widgets/victory_widget.dart index 92a17de..f3c55bf 100644 --- a/lib/widgets/victory_widget.dart +++ b/lib/widgets/victory_widget.dart @@ -11,12 +11,12 @@ class VictoryConfetti extends StatefulWidget { } class _VictoryConfettiState extends State { - ConfettiController _controllerBottomCenter; + late ConfettiController _controllerBottomCenter; @override void initState() { _controllerBottomCenter = ConfettiController(duration: const Duration(seconds: 2)); - SchedulerBinding.instance.addPostFrameCallback((_) { + SchedulerBinding.instance!.addPostFrameCallback((_) { Future.delayed(Duration(milliseconds: 500)).then((value) => _controllerBottomCenter.play()); }); super.initState(); @@ -68,14 +68,14 @@ class _VictoryConfettiState extends State { } class Victory extends StatefulWidget { - final bool victory; + final bool? victory; const Victory({this.victory}); @override _VictoryState createState() => _VictoryState(); } class _VictoryState extends State { - final EzAnimation animation = EzAnimation(1.0, 200.0, Duration(seconds: 3), reverseCurve: null); + final EzAnimation animation = EzAnimation(1.0, 200.0, Duration(seconds: 3), reverseCurve: Curves.easeIn); @override void initState() { @@ -101,7 +101,7 @@ class _VictoryState extends State { height: animation.value, child: Row(children: [ VictoryConfetti(), - widget.victory ? Image.asset("asset/image/WT_cup_victory400.png") : Offstage(), + widget.victory != null && widget.victory == true ? Image.asset("asset/image/WT_cup_victory400.png") : Offstage(), ]), ), ); diff --git a/pubspec.lock b/pubspec.lock index 290dd08..d0704ae 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,21 +7,14 @@ packages: name: _fe_analyzer_shared url: "https://pub.dartlang.org" source: hosted - version: "12.0.0" + version: "19.0.0" analyzer: dependency: transitive description: name: analyzer url: "https://pub.dartlang.org" source: hosted - version: "0.40.6" - animated_widgets: - dependency: "direct main" - description: - name: animated_widgets - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.6" + version: "1.3.0" apple_sign_in: dependency: "direct main" description: @@ -35,63 +28,56 @@ packages: name: archive url: "https://pub.dartlang.org" source: hosted - version: "2.0.13" + version: "3.1.2" args: dependency: transitive description: name: args url: "https://pub.dartlang.org" source: hosted - version: "1.6.0" + version: "2.0.0" async: dependency: transitive description: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.5.0-nullsafety.1" - audioplayer: - dependency: "direct main" - description: - name: audioplayer - url: "https://pub.dartlang.org" - source: hosted - version: "0.8.1" + version: "2.5.0" badges: dependency: "direct main" description: name: badges url: "https://pub.dartlang.org" source: hosted - version: "1.1.6" + version: "2.0.0-nullsafety.1" bloc: dependency: transitive description: name: bloc url: "https://pub.dartlang.org" source: hosted - version: "6.1.1" + version: "7.0.0" bloc_test: dependency: "direct dev" description: name: bloc_test url: "https://pub.dartlang.org" source: hosted - version: "7.1.0" + version: "8.0.0" boolean_selector: dependency: transitive description: name: boolean_selector url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0" build: dependency: transitive description: name: build url: "https://pub.dartlang.org" source: hosted - version: "1.6.1" + version: "1.6.3" build_config: dependency: transitive description: @@ -105,63 +91,63 @@ packages: name: build_daemon url: "https://pub.dartlang.org" source: hosted - version: "2.1.6" + version: "2.1.10" build_resolvers: dependency: transitive description: name: build_resolvers url: "https://pub.dartlang.org" source: hosted - version: "1.5.2" + version: "1.5.4" build_runner: dependency: "direct dev" description: name: build_runner url: "https://pub.dartlang.org" source: hosted - version: "1.11.0" + version: "1.11.5" build_runner_core: dependency: transitive description: name: build_runner_core url: "https://pub.dartlang.org" source: hosted - version: "6.1.6" + version: "6.1.10" built_collection: dependency: transitive description: name: built_collection url: "https://pub.dartlang.org" source: hosted - version: "4.3.2" + version: "5.0.0" built_value: dependency: transitive description: name: built_value url: "https://pub.dartlang.org" source: hosted - version: "7.1.0" + version: "8.0.4" carousel_slider: dependency: "direct main" description: name: carousel_slider url: "https://pub.dartlang.org" source: hosted - version: "3.0.0" + version: "4.0.0-nullsafety.0" characters: dependency: transitive description: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.3" + version: "1.1.0" charcode: dependency: transitive description: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0" checked_yaml: dependency: transitive description: @@ -175,238 +161,252 @@ packages: name: chewie url: "https://pub.dartlang.org" source: hosted - version: "0.12.2" + version: "1.0.0" chewie_audio: dependency: transitive description: name: chewie_audio url: "https://pub.dartlang.org" source: hosted - version: "1.1.1" + version: "1.2.0" cli_util: dependency: transitive description: name: cli_util url: "https://pub.dartlang.org" source: hosted - version: "0.2.0" + version: "0.3.0" clock: dependency: transitive description: name: clock url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0" code_builder: dependency: transitive description: name: code_builder url: "https://pub.dartlang.org" source: hosted - version: "3.6.0" + version: "3.7.0" collection: dependency: transitive description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0-nullsafety.3" + version: "1.15.0" confetti: dependency: "direct main" description: name: confetti url: "https://pub.dartlang.org" source: hosted - version: "0.5.5" + version: "0.6.0-nullsafety" convert: dependency: transitive description: name: convert url: "https://pub.dartlang.org" source: hosted - version: "2.1.1" + version: "3.0.0" coverage: dependency: transitive description: name: coverage url: "https://pub.dartlang.org" source: hosted - version: "0.14.2" + version: "0.15.2" crypto: dependency: "direct main" description: name: crypto url: "https://pub.dartlang.org" source: hosted - version: "2.1.5" + version: "3.0.0" css_colors: dependency: transitive description: name: css_colors url: "https://pub.dartlang.org" source: hosted - version: "1.0.2" + version: "1.1.0" csslib: dependency: transitive description: name: csslib url: "https://pub.dartlang.org" source: hosted - version: "0.16.2" + version: "0.17.0" cupertino_icons: dependency: "direct main" description: name: cupertino_icons url: "https://pub.dartlang.org" source: hosted - version: "1.0.0" + version: "1.0.2" dart_style: dependency: transitive description: name: dart_style url: "https://pub.dartlang.org" source: hosted - version: "1.3.10" + version: "1.3.14" devicelocale: dependency: "direct main" description: name: devicelocale url: "https://pub.dartlang.org" source: hosted - version: "0.3.3" + version: "0.4.1" + dropdown_search: + dependency: "direct main" + description: + name: dropdown_search + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.0" equatable: dependency: "direct main" description: name: equatable url: "https://pub.dartlang.org" source: hosted - version: "1.2.5" + version: "2.0.0" ezanimation: dependency: "direct main" description: name: ezanimation url: "https://pub.dartlang.org" source: hosted - version: "0.4.1" + version: "0.5.0" fake_async: dependency: transitive description: name: fake_async url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0" ffi: dependency: transitive description: name: ffi url: "https://pub.dartlang.org" source: hosted - version: "0.1.3" + version: "1.0.0" file: dependency: transitive description: name: file url: "https://pub.dartlang.org" source: hosted - version: "5.2.1" + version: "6.1.0" firebase: dependency: transitive description: name: firebase url: "https://pub.dartlang.org" source: hosted - version: "7.3.3" + version: "9.0.1" firebase_analytics: dependency: "direct main" description: name: firebase_analytics url: "https://pub.dartlang.org" source: hosted - version: "6.3.0" + version: "8.0.0-dev.0" firebase_analytics_platform_interface: dependency: transitive description: name: firebase_analytics_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.0.0-dev.0" firebase_analytics_web: dependency: transitive description: name: firebase_analytics_web url: "https://pub.dartlang.org" source: hosted - version: "0.1.1" + version: "0.3.0-dev.0" firebase_auth: dependency: "direct main" description: name: firebase_auth url: "https://pub.dartlang.org" source: hosted - version: "0.18.4+1" + version: "1.0.1" firebase_auth_platform_interface: dependency: transitive description: name: firebase_auth_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.1.4" + version: "4.0.0" firebase_auth_web: dependency: transitive description: name: firebase_auth_web url: "https://pub.dartlang.org" source: hosted - version: "0.3.2+3" + version: "1.0.3" firebase_core: dependency: "direct main" description: name: firebase_core url: "https://pub.dartlang.org" source: hosted - version: "0.5.3" + version: "1.0.2" firebase_core_platform_interface: dependency: transitive description: name: firebase_core_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.1.0" + version: "4.0.0" firebase_core_web: dependency: transitive description: name: firebase_core_web url: "https://pub.dartlang.org" source: hosted - version: "0.2.1+1" + version: "1.0.2" firebase_messaging: dependency: "direct main" description: name: firebase_messaging url: "https://pub.dartlang.org" source: hosted - version: "7.0.3" + version: "9.1.0" + firebase_messaging_platform_interface: + dependency: transitive + description: + name: firebase_messaging_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + firebase_messaging_web: + dependency: transitive + description: + name: firebase_messaging_web + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.3" fixnum: dependency: transitive description: name: fixnum url: "https://pub.dartlang.org" source: hosted - version: "0.10.11" + version: "1.0.0" fl_chart: dependency: "direct main" description: name: fl_chart url: "https://pub.dartlang.org" source: hosted - version: "0.12.2" - flurry: - dependency: "direct main" - description: - name: flurry - url: "https://pub.dartlang.org" - source: hosted - version: "0.0.7" + version: "0.30.0" flutter: dependency: "direct main" description: flutter @@ -418,63 +418,63 @@ packages: name: flutter_bloc url: "https://pub.dartlang.org" source: hosted - version: "6.1.2" + version: "7.0.0" flutter_facebook_auth: dependency: "direct main" description: name: flutter_facebook_auth url: "https://pub.dartlang.org" source: hosted - version: "2.0.1" + version: "3.3.1+1" flutter_facebook_auth_platform_interface: dependency: transitive description: name: flutter_facebook_auth_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.1" + version: "2.4.0" flutter_facebook_auth_web: dependency: transitive description: name: flutter_facebook_auth_web url: "https://pub.dartlang.org" source: hosted - version: "1.0.6" - flutter_form_bloc: - dependency: "direct main" - description: - name: flutter_form_bloc - url: "https://pub.dartlang.org" - source: hosted - version: "0.19.0" + version: "2.4.0+2" flutter_html: dependency: "direct main" description: name: flutter_html url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" - flutter_keyboard_visibility: - dependency: transitive - description: - name: flutter_keyboard_visibility - url: "https://pub.dartlang.org" - source: hosted - version: "3.3.0" + version: "2.0.0-nullsafety.0" flutter_launcher_icons: dependency: "direct dev" description: name: flutter_launcher_icons url: "https://pub.dartlang.org" source: hosted - version: "0.8.1" + version: "0.9.0" flutter_layout_grid: dependency: transitive description: name: flutter_layout_grid url: "https://pub.dartlang.org" source: hosted - version: "0.10.5" + version: "1.0.1" + flutter_local_notifications: + dependency: "direct main" + description: + name: flutter_local_notifications + url: "https://pub.dartlang.org" + source: hosted + version: "5.0.0" + flutter_local_notifications_platform_interface: + dependency: transitive + description: + name: flutter_local_notifications_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.0" flutter_localizations: dependency: "direct main" description: flutter @@ -486,14 +486,14 @@ packages: name: flutter_secure_storage url: "https://pub.dartlang.org" source: hosted - version: "3.3.5" + version: "4.1.0" flutter_svg: dependency: transitive description: name: flutter_svg url: "https://pub.dartlang.org" source: hosted - version: "0.19.1" + version: "0.21.0-nullsafety.0" flutter_test: dependency: "direct dev" description: flutter @@ -504,48 +504,41 @@ packages: description: flutter source: sdk version: "0.0.0" - form_bloc: - dependency: transitive - description: - name: form_bloc - url: "https://pub.dartlang.org" - source: hosted - version: "0.19.1" glob: dependency: transitive description: name: glob url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "2.0.1" google_fonts: dependency: "direct main" description: name: google_fonts url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "2.0.0" google_sign_in: dependency: "direct main" description: name: google_sign_in url: "https://pub.dartlang.org" source: hosted - version: "4.5.9" + version: "5.0.1" google_sign_in_platform_interface: dependency: transitive description: name: google_sign_in_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "2.0.1" google_sign_in_web: dependency: transitive description: name: google_sign_in_web url: "https://pub.dartlang.org" source: hosted - version: "0.9.2" + version: "0.10.0" graphs: dependency: transitive description: @@ -559,14 +552,14 @@ packages: name: html url: "https://pub.dartlang.org" source: hosted - version: "0.14.0+4" + version: "0.15.0" http: dependency: "direct dev" description: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.12.2" + version: "0.13.1" http_multi_server: dependency: transitive description: @@ -580,35 +573,28 @@ packages: name: http_parser url: "https://pub.dartlang.org" source: hosted - version: "3.1.4" + version: "4.0.0" image: dependency: transitive description: name: image url: "https://pub.dartlang.org" source: hosted - version: "2.1.19" - import_js_library: - dependency: transitive - description: - name: import_js_library - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.2" + version: "3.0.2" infinite_listview: dependency: "direct main" description: name: infinite_listview url: "https://pub.dartlang.org" source: hosted - version: "1.0.1+1" + version: "1.1.0" intl: dependency: "direct dev" description: name: intl url: "https://pub.dartlang.org" source: hosted - version: "0.16.1" + version: "0.17.0" io: dependency: transitive description: @@ -622,7 +608,7 @@ packages: name: js url: "https://pub.dartlang.org" source: hosted - version: "0.6.3-nullsafety.2" + version: "0.6.3" json_annotation: dependency: transitive description: @@ -636,7 +622,7 @@ packages: name: keyboard_actions url: "https://pub.dartlang.org" source: hosted - version: "3.3.1+1" + version: "3.4.0" liquid_progress_indicator: dependency: "direct main" description: @@ -657,14 +643,14 @@ packages: name: matcher url: "https://pub.dartlang.org" source: hosted - version: "0.12.10-nullsafety.1" + version: "0.12.10" meta: dependency: transitive description: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.3" + version: "1.3.0" mime: dependency: transitive description: @@ -678,42 +664,28 @@ packages: name: mockito url: "https://pub.dartlang.org" source: hosted - version: "4.1.4" - modal_progress_hud: - dependency: "direct main" + version: "5.0.3" + mocktail: + dependency: transitive description: - name: modal_progress_hud + name: mocktail url: "https://pub.dartlang.org" source: hosted - version: "0.1.3" + version: "0.1.1" + modal_progress_hud_nsn: + dependency: "direct main" + description: + name: modal_progress_hud_nsn + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0-nullsafety-1" nested: dependency: transitive description: name: nested url: "https://pub.dartlang.org" source: hosted - version: "0.0.4" - network_image_to_byte: - dependency: "direct main" - description: - name: network_image_to_byte - url: "https://pub.dartlang.org" - source: hosted - version: "0.0.1" - node_interop: - dependency: transitive - description: - name: node_interop - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.1" - node_io: - dependency: transitive - description: - name: node_io - url: "https://pub.dartlang.org" - source: hosted - version: "1.2.0" + version: "1.0.0" node_preamble: dependency: transitive description: @@ -727,259 +699,259 @@ packages: name: package_config url: "https://pub.dartlang.org" source: hosted - version: "1.9.3" + version: "2.0.0" package_info: dependency: "direct main" description: name: package_info url: "https://pub.dartlang.org" source: hosted - version: "0.4.3+4" + version: "2.0.0" path: dependency: transitive description: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.1" + version: "1.8.0" path_drawing: dependency: transitive description: name: path_drawing url: "https://pub.dartlang.org" source: hosted - version: "0.4.1+1" + version: "0.5.0-nullsafety.0" path_parsing: dependency: transitive description: name: path_parsing url: "https://pub.dartlang.org" source: hosted - version: "0.1.4" + version: "0.2.0-nullsafety.0" path_provider: dependency: transitive description: name: path_provider url: "https://pub.dartlang.org" source: hosted - version: "1.6.27" + version: "2.0.1" path_provider_linux: dependency: transitive description: name: path_provider_linux url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+2" + version: "2.0.0" path_provider_macos: dependency: transitive description: name: path_provider_macos url: "https://pub.dartlang.org" source: hosted - version: "0.0.4+8" + version: "2.0.0" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.4" + version: "2.0.1" path_provider_windows: dependency: transitive description: name: path_provider_windows url: "https://pub.dartlang.org" source: hosted - version: "0.0.4+3" + version: "2.0.0" pedantic: dependency: transitive description: name: pedantic url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.2" + version: "1.11.0" percent_indicator: dependency: "direct main" description: name: percent_indicator url: "https://pub.dartlang.org" source: hosted - version: "2.1.9" + version: "3.3.0-nullsafety.1" petitparser: dependency: transitive description: name: petitparser url: "https://pub.dartlang.org" source: hosted - version: "3.1.0" + version: "4.0.2" platform: dependency: transitive description: name: platform url: "https://pub.dartlang.org" source: hosted - version: "2.2.1" + version: "3.0.0" plugin_platform_interface: dependency: transitive description: name: plugin_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.0.0" pool: dependency: transitive description: name: pool url: "https://pub.dartlang.org" source: hosted - version: "1.5.0-nullsafety.2" + version: "1.5.0" process: dependency: transitive description: name: process url: "https://pub.dartlang.org" source: hosted - version: "3.0.13" + version: "4.2.1" provider: dependency: transitive description: name: provider url: "https://pub.dartlang.org" source: hosted - version: "4.3.3" + version: "5.0.0" pub_semver: dependency: transitive description: name: pub_semver url: "https://pub.dartlang.org" source: hosted - version: "1.4.4" + version: "2.0.0" pubspec_parse: dependency: transitive description: name: pubspec_parse url: "https://pub.dartlang.org" source: hosted - version: "0.1.7" + version: "0.1.8" purchases_flutter: dependency: "direct main" description: name: purchases_flutter url: "https://pub.dartlang.org" source: hosted - version: "2.0.3" + version: "3.1.0" quiver: dependency: transitive description: name: quiver url: "https://pub.dartlang.org" source: hosted - version: "2.1.5" + version: "3.0.0" rainbow_color: dependency: "direct main" description: name: rainbow_color url: "https://pub.dartlang.org" source: hosted - version: "0.1.1" + version: "2.0.1" rainbow_vis: dependency: transitive description: name: rainbow_vis url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.0.0" random_color: dependency: transitive description: name: random_color url: "https://pub.dartlang.org" source: hosted - version: "1.0.5" + version: "1.0.6-nullsafety" rxdart: dependency: transitive description: name: rxdart url: "https://pub.dartlang.org" source: hosted - version: "0.24.1" + version: "0.26.0" sentry: dependency: "direct main" description: name: sentry url: "https://pub.dartlang.org" source: hosted - version: "4.0.4" + version: "4.1.0-nullsafety.1" shared_preferences: dependency: "direct dev" description: name: shared_preferences url: "https://pub.dartlang.org" source: hosted - version: "0.5.12+4" + version: "2.0.5" shared_preferences_linux: dependency: transitive description: name: shared_preferences_linux url: "https://pub.dartlang.org" source: hosted - version: "0.0.2+4" + version: "2.0.0" shared_preferences_macos: dependency: transitive description: name: shared_preferences_macos url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+11" + version: "2.0.0" shared_preferences_platform_interface: dependency: transitive description: name: shared_preferences_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.4" + version: "2.0.0" shared_preferences_web: dependency: transitive description: name: shared_preferences_web url: "https://pub.dartlang.org" source: hosted - version: "0.1.2+7" + version: "2.0.0" shared_preferences_windows: dependency: transitive description: name: shared_preferences_windows url: "https://pub.dartlang.org" source: hosted - version: "0.0.2+2" + version: "2.0.0" shelf: dependency: transitive description: name: shelf url: "https://pub.dartlang.org" source: hosted - version: "0.7.9" + version: "1.1.0" shelf_packages_handler: dependency: transitive description: name: shelf_packages_handler url: "https://pub.dartlang.org" source: hosted - version: "2.0.0" + version: "2.0.1" shelf_static: dependency: transitive description: name: shelf_static url: "https://pub.dartlang.org" source: hosted - version: "0.2.9+1" + version: "0.2.9+2" shelf_web_socket: dependency: transitive description: name: shelf_web_socket url: "https://pub.dartlang.org" source: hosted - version: "0.2.3" + version: "0.2.4+1" sky_engine: dependency: transitive description: flutter @@ -998,28 +970,28 @@ packages: name: source_gen url: "https://pub.dartlang.org" source: hosted - version: "0.9.10+1" + version: "0.9.10+3" source_map_stack_trace: dependency: transitive description: name: source_map_stack_trace url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0" source_maps: dependency: transitive description: name: source_maps url: "https://pub.dartlang.org" source: hosted - version: "0.10.10-nullsafety.2" + version: "0.10.10" source_span: dependency: transitive description: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.2" + version: "1.8.0" spider_chart: dependency: "direct main" description: @@ -1033,35 +1005,35 @@ packages: name: sqflite url: "https://pub.dartlang.org" source: hosted - version: "1.3.2+3" + version: "2.0.0+3" sqflite_common: dependency: transitive description: name: sqflite_common url: "https://pub.dartlang.org" source: hosted - version: "1.0.3+1" + version: "2.0.0+2" stack_trace: dependency: transitive description: name: stack_trace url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.1" + version: "1.10.0" stop_watch_timer: dependency: "direct main" description: name: stop_watch_timer url: "https://pub.dartlang.org" source: hosted - version: "0.6.0+1" + version: "1.0.0" stream_channel: dependency: transitive description: name: stream_channel url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0" stream_transform: dependency: transitive description: @@ -1075,49 +1047,56 @@ packages: name: string_scanner url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0" synchronized: dependency: transitive description: name: synchronized url: "https://pub.dartlang.org" source: hosted - version: "2.2.0+2" + version: "3.0.0" term_glyph: dependency: transitive description: name: term_glyph url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0" test: dependency: "direct dev" description: name: test url: "https://pub.dartlang.org" source: hosted - version: "1.16.0-nullsafety.5" + version: "1.16.5" test_api: dependency: transitive description: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.19-nullsafety.2" + version: "0.2.19" test_core: dependency: transitive description: name: test_core url: "https://pub.dartlang.org" source: hosted - version: "0.3.12-nullsafety.5" + version: "0.3.15" timeline_tile: dependency: "direct main" description: name: timeline_tile url: "https://pub.dartlang.org" source: hosted - version: "1.0.0" + version: "2.0.0" + timezone: + dependency: transitive + description: + name: timezone + url: "https://pub.dartlang.org" + source: hosted + version: "0.7.0-nullsafety.0" timing: dependency: transitive description: @@ -1131,56 +1110,49 @@ packages: name: toggle_switch url: "https://pub.dartlang.org" source: hosted - version: "0.1.8" - transparent_image: - dependency: "direct main" - description: - name: transparent_image - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" + version: "0.1.9" typed_data: dependency: transitive description: name: typed_data url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.3" + version: "1.3.0" uuid: dependency: transitive description: name: uuid url: "https://pub.dartlang.org" source: hosted - version: "2.2.2" + version: "3.0.2" vector_math: dependency: transitive description: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0" video_player: dependency: transitive description: name: video_player url: "https://pub.dartlang.org" source: hosted - version: "1.0.1" + version: "2.1.0" video_player_platform_interface: dependency: transitive description: name: video_player_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "2.2.0" + version: "4.1.0" video_player_web: dependency: transitive description: name: video_player_web url: "https://pub.dartlang.org" source: hosted - version: "0.1.4+1" + version: "2.0.0" vm_service: dependency: transitive description: @@ -1194,28 +1166,35 @@ packages: name: wakelock url: "https://pub.dartlang.org" source: hosted - version: "0.2.1+1" + version: "0.4.0" + wakelock_macos: + dependency: transitive + description: + name: wakelock_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0" wakelock_platform_interface: dependency: transitive description: name: wakelock_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "0.1.0+1" + version: "0.2.0" wakelock_web: dependency: transitive description: name: wakelock_web url: "https://pub.dartlang.org" source: hosted - version: "0.1.0+3" + version: "0.2.0" watcher: dependency: transitive description: name: watcher url: "https://pub.dartlang.org" source: hosted - version: "0.9.7+15" + version: "1.0.0" web_socket_channel: dependency: transitive description: @@ -1236,35 +1215,35 @@ packages: name: webview_flutter url: "https://pub.dartlang.org" source: hosted - version: "1.0.7" + version: "2.0.2" win32: dependency: transitive description: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "1.7.4" + version: "2.0.5" xdg_directories: dependency: transitive description: name: xdg_directories url: "https://pub.dartlang.org" source: hosted - version: "0.1.2" + version: "0.2.0" xml: dependency: transitive description: name: xml url: "https://pub.dartlang.org" source: hosted - version: "4.5.1" + version: "5.0.2" yaml: dependency: transitive description: name: yaml url: "https://pub.dartlang.org" source: hosted - version: "2.2.1" + version: "3.1.0" sdks: - dart: ">=2.10.2 <2.11.0" - flutter: ">=1.22.2 <2.0.0" + dart: ">=2.12.0 <3.0.0" + flutter: ">=2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 186d134..de05cb5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,67 +15,64 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # 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.1.10+61 +version: 1.1.10+62 environment: - sdk: ">=2.7.0 <3.0.0" + sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.0 - google_fonts: ^1.1.1 - devicelocale: ^0.3.3 - sentry: ^4.0.3 - flutter_bloc: ^6.1.2 - equatable: ^1.2.5 - #freezed: ^0.12.2 - flutter_form_bloc: ^0.19.0 + google_fonts: ^2.0.0 + devicelocale: ^0.4.1 + sentry: ^4.1.0-nullsafety.1 + flutter_bloc: ^7.0.0 + equatable: ^2.0.0 + spider_chart: ^0.1.5 - rainbow_color: ^0.1.1 - percent_indicator: ^2.1.8 - fl_chart: ^0.12.0 - infinite_listview: ^1.0.1+1 - toggle_switch: ^0.1.8 - keyboard_actions: ^3.3.1+1 - badges: ^1.1.4 + rainbow_color: ^2.0.1 + percent_indicator: ^ 3.3.0-nullsafety.1 + fl_chart: ^0.30.0 + infinite_listview: ^1.1.0 + toggle_switch: ^0.1.9 + keyboard_actions: ^3.4.0 + badges: ^ 2.0.0-nullsafety.1 #health: ^3.0.0 - stop_watch_timer: ^0.6.0+1 + stop_watch_timer: ^1.0.0 #location: ^3.2.4 - modal_progress_hud: ^0.1.3 - flutter_html: ^1.1.1 - wakelock: ^0.2.1+1 - timeline_tile: ^1.0.0 - purchases_flutter: ^2.0.3 - network_image_to_byte: ^0.0.1 - package_info: ^0.4.3+4 + modal_progress_hud_nsn: ^0.1.0-nullsafety-1 + flutter_html: ^2.0.0-nullsafety.0 + wakelock: ^ 0.4.0 + timeline_tile: ^2.0.0 + purchases_flutter: ^3.1.0 + package_info: ^2.0.0 liquid_progress_indicator: ^0.3.2 - audioplayer: ^0.8.1 - ezanimation: ^0.4.1 - confetti: ^0.5.5 - crypto: ^2.1.5 - transparent_image: ^1.0.0 - #auto_animated: ^2.1.0 - carousel_slider: ^3.0.0 + #audioplayer: ^0.8.1 + ezanimation: ^0.5.0 + confetti: ^0.6.0-nullsafety + crypto: ^3.0.0 + carousel_slider: ^4.0.0-nullsafety.0 + dropdown_search: ^0.5.0 - firebase_core: ^0.5.0 - firebase_analytics: ^6.2.0 - firebase_messaging: ^7.0.0 - firebase_auth: ^0.18.3 - flutter_facebook_auth: ^2.0.0+1 - google_sign_in: ^4.5.9 + firebase_core: ^1.0.2 + firebase_analytics: ^8.0.0-dev.0 + firebase_messaging: ^9.1.0 + flutter_local_notifications: ^5.0.0 + firebase_auth: ^1.0.1 + flutter_facebook_auth: ^3.3.1+1 + google_sign_in: ^5.0.1 apple_sign_in: ^0.1.0 smartlook: ^1.0.6 - flurry: ^0.0.7 + + #animated_widgets: ^1.0.6 - animated_widgets: ^1.0.6 - - mockito: ^4.1.3 - sqflite: ^1.3.2+3 - flutter_secure_storage: ^3.3.5 + mockito: ^5.0.3 + sqflite: ^2.0.0+3 + flutter_secure_storage: ^4.1.0 flutter_localizations: sdk: flutter @@ -87,16 +84,16 @@ dev_dependencies: test: '>=1.0.0 <2.0.0' flutter_test: sdk: flutter - bloc_test: ^7.1.0 + bloc_test: ^8.0.0 build_runner: - http: ^0.12.1 - intl: ^0.16.1 - shared_preferences: ^0.5.12+4 + http: ^0.13.1 + intl: ^0.17.0 + shared_preferences: ^2.0.5 - flutter_launcher_icons: ^0.8.1 + flutter_launcher_icons: ^0.9.0 flutter_icons: android: "launcher_icon" diff --git a/test/account_bloc_test.dart b/test/account_bloc_test.dart index 60268ab..ad039ff 100644 --- a/test/account_bloc_test.dart +++ b/test/account_bloc_test.dart @@ -8,7 +8,7 @@ class MockCustomerRepository extends Mock implements CustomerRepository {} void main() { MockCustomerRepository customerRepository; - AccountBloc accountBloc; + late AccountBloc accountBloc; TestWidgetsFlutterBinding.ensureInitialized(); @@ -18,7 +18,7 @@ void main() { }); test.tearDown(() { - accountBloc?.close(); + accountBloc.close(); }); test.test('initial state is correct', () { diff --git a/test/body_type_bloc_test.dart b/test/body_type_bloc_test.dart index 6fb7051..7b60d0b 100644 --- a/test/body_type_bloc_test.dart +++ b/test/body_type_bloc_test.dart @@ -7,12 +7,12 @@ import 'package:flutter_test/flutter_test.dart'; class MockCustomerRepository extends Mock implements CustomerRepository {} void main() { - BodytypeBloc bloc; + late BodytypeBloc bloc; TestWidgetsFlutterBinding.ensureInitialized(); test.setUp(() { - bloc = BodytypeBloc(); + bloc = BodytypeBloc(repository: MockCustomerRepository()); }); test.tearDown(() { diff --git a/test/customer_service_test.dart b/test/customer_service_test.dart index d18ac68..37591eb 100644 --- a/test/customer_service_test.dart +++ b/test/customer_service_test.dart @@ -23,29 +23,27 @@ import 'package:flutter_test/flutter_test.dart'; } */ main() { + setUp(() { + Cache().setTestBaseUrl(); + }); + group('fetchPost', () { + test('returns a List if the http call completes successfully', () async { + final client = CustomerApi(); - setUp(() { - Cache().setTestBaseUrl(); + // Use Mockito to return a successful response when it calls the + // provided http.Client. + List trainees = []; + trainees = await client.getTrainees(62); + + expect(trainees.length, 2); + expect(trainees[0].firstname, "Zalán"); }); - group('fetchPost', () { - test('returns a List if the http call completes successfully', () async { - final client = CustomerApi(); + test('throws an exception if the http call completes with an error', () async { + final client = CustomerApi(); - // Use Mockito to return a successful response when it calls the - // provided http.Client. - List trainees = List(); - trainees = await client.getTrainees(62); - - expect(trainees.length, 2); - expect(trainees[0].firstname, "Zalán"); - }); - - test('throws an exception if the http call completes with an error', () async { - final client = CustomerApi(); - - expect(client.getTrainees(22), throwsException); - }); + expect(client.getTrainees(22), throwsException); }); -} \ No newline at end of file + }); +} diff --git a/test/exercise_plan_bloc.dart b/test/exercise_plan_bloc.dart index 760c490..5d4ee81 100644 --- a/test/exercise_plan_bloc.dart +++ b/test/exercise_plan_bloc.dart @@ -9,8 +9,8 @@ import 'package:test/test.dart'; import 'mocks.dart'; main() { - SimExercisePlanRepository _exercisePlanRepository; - ExercisePlanBloc bloc; + late SimExercisePlanRepository _exercisePlanRepository; + late ExercisePlanBloc bloc; Future setUpPlan() async { final String planName2 = "Test Plan2"; @@ -73,10 +73,10 @@ main() { emitsInOrder(expectedResponse), ).then((_) { expect(bloc.exercisePlanRepository.newPlan, false); - expect(bloc.exercisePlanRepository.exercisePlan.name, "Test Plan2"); - expect(bloc.exercisePlanRepository.exercisePlanDetails[4].weightEquation, "95"); - expect(Cache().getMyExercisePlan().name, "Test Plan2"); - expect(Cache().getMyExercisePlanDetails()[4].weightEquation, "95"); + expect(bloc.exercisePlanRepository.exercisePlan!.name, "Test Plan2"); + expect(bloc.exercisePlanRepository.exercisePlanDetails[4]!.weightEquation, "95"); + expect(Cache().getMyExercisePlan()!.name, "Test Plan2"); + expect(Cache().getMyExercisePlanDetails()[4]!.weightEquation, "95"); }); }); @@ -100,13 +100,13 @@ main() { emitsInOrder(expectedResponse2), ).then((_) { expect(bloc.exercisePlanRepository.newPlan, false); - expect(bloc.exercisePlanRepository.exercisePlan.customerId, 101); + expect(bloc.exercisePlanRepository.exercisePlan!.customerId, 101); expect(bloc.exercisePlanRepository.exercisePlanDetails.length, 3); - expect(bloc.exercisePlanRepository.exercisePlanDetails[5].repeats, 20); - expect(bloc.exercisePlanRepository.exercisePlanDetails[5].change, ModelChange.add); - expect(Cache().getMyExercisePlan().name, "Test Plan2"); - expect(Cache().getMyExercisePlanDetails()[5].weightEquation, "55"); - expect(Cache().getMyExercisePlanDetails()[5].repeats, 20); + expect(bloc.exercisePlanRepository.exercisePlanDetails[5]!.repeats, 20); + expect(bloc.exercisePlanRepository.exercisePlanDetails[5]!.change, ModelChange.add); + expect(Cache().getMyExercisePlan()!.name, "Test Plan2"); + expect(Cache().getMyExercisePlanDetails()[5]!.weightEquation, "55"); + expect(Cache().getMyExercisePlanDetails()[5]!.repeats, 20); }); }); test('Update bloc', () async { @@ -114,9 +114,9 @@ main() { bloc.exercisePlanRepository.getLastExercisePlan(); bloc.exercisePlanRepository.getExercisePlanDetails(); - bloc.exercisePlanRepository.exercisePlanDetails[3].repeats = 25; + bloc.exercisePlanRepository.exercisePlanDetails[3]!.repeats = 25; - bloc.add(ExercisePlanAddExercise(exercisePlanDetail: bloc.exercisePlanRepository.exercisePlanDetails[3])); + bloc.add(ExercisePlanAddExercise(exercisePlanDetail: bloc.exercisePlanRepository.exercisePlanDetails[3]!)); final expectedResponse2 = [ExercisePlanLoading(), ExercisePlanReady()]; @@ -125,15 +125,15 @@ main() { emitsInOrder(expectedResponse2), ).then((_) { expect(bloc.exercisePlanRepository.newPlan, false); - expect(bloc.exercisePlanRepository.exercisePlanDetails[3].repeats, 25); - expect(Cache().getMyExercisePlanDetails()[3].repeats, 25); + expect(bloc.exercisePlanRepository.exercisePlanDetails[3]!.repeats, 25); + expect(Cache().getMyExercisePlanDetails()[3]!.repeats, 25); }); }); test('Delete bloc', () async { bloc.customerId = 101; bloc.exercisePlanRepository.getLastExercisePlan(); bloc.exercisePlanRepository.getExercisePlanDetails(); - bloc.add(ExercisePlanRemoveExercise(exercisePlanDetail: bloc.exercisePlanRepository.exercisePlanDetails[3])); + bloc.add(ExercisePlanRemoveExercise(exercisePlanDetail: bloc.exercisePlanRepository.exercisePlanDetails[3]!)); final expectedResponse2 = [ExercisePlanLoading(), ExercisePlanReady()]; diff --git a/test/exercise_plan_repository_test.dart b/test/exercise_plan_repository_test.dart index 2ffbf78..bf5f0f2 100644 --- a/test/exercise_plan_repository_test.dart +++ b/test/exercise_plan_repository_test.dart @@ -6,8 +6,8 @@ import 'package:test/test.dart'; import 'mocks.dart'; main() { - SimExercisePlanRepository _exercisePlanRepository; - int _customerId; + late SimExercisePlanRepository _exercisePlanRepository; + late int _customerId; Future setUpPlan() async { final String planName2 = "Test Plan2"; @@ -63,11 +63,11 @@ main() { await _exercisePlanRepository.saveExercisePlan(); - expect(_exercisePlanRepository.getExercisePlan().name, planName); - expect(_exercisePlanRepository.getExercisePlan().exercisePlanId > 0, true); + expect(_exercisePlanRepository.getExercisePlan()!.name, planName); + expect(_exercisePlanRepository.getExercisePlan()!.exercisePlanId! > 0, true); - ExercisePlanDetail detail = _exercisePlanRepository.getExercisePlanDetailByExerciseId(55); - expect(detail.exercisePlanId, _exercisePlanRepository.getExercisePlan().exercisePlanId); + ExercisePlanDetail detail = _exercisePlanRepository.getExercisePlanDetailByExerciseId(55)!; + expect(detail.exercisePlanId, _exercisePlanRepository.getExercisePlan()!.exercisePlanId); }); test('save new plan and plan details second', () async { int customerId = 100; @@ -92,27 +92,27 @@ main() { await _exercisePlanRepository.saveExercisePlan(); - expect(_exercisePlanRepository.getExercisePlan().name, planName); - expectLater(_exercisePlanRepository.getExercisePlan().exercisePlanId > 0, true); + expect(_exercisePlanRepository.getExercisePlan()!.name, planName); + expectLater(_exercisePlanRepository.getExercisePlan()!.exercisePlanId! > 0, true); - ExercisePlanDetail detail = _exercisePlanRepository.getExercisePlanDetailByExerciseId(13); - expect(detail.exercisePlanId, _exercisePlanRepository.getExercisePlan().exercisePlanId); + ExercisePlanDetail detail = _exercisePlanRepository.getExercisePlanDetailByExerciseId(13)!; + expect(detail.exercisePlanId, _exercisePlanRepository.getExercisePlan()!.exercisePlanId); expect(detail.repeats, 33); }); }); group('Existing Plan', () { test('Get Last Plan and Details from DB', () async { - ExercisePlan exercisePlan = await _exercisePlanRepository.getLastExercisePlan(); - expect(exercisePlan.customerId, 101); + ExercisePlan? exercisePlan = await _exercisePlanRepository.getLastExercisePlan(); + expect(exercisePlan!.customerId, 101); await _exercisePlanRepository.getExercisePlanDetails(); - expect(_exercisePlanRepository.exercisePlanDetails[3].repeats, 23); - expect(_exercisePlanRepository.exercisePlanDetails[4].weightEquation, "95"); + expect(_exercisePlanRepository.exercisePlanDetails[3]!.repeats, 23); + expect(_exercisePlanRepository.exercisePlanDetails[4]!.weightEquation, "95"); //Test Cache - expect(Cache().getMyExercisePlan().name, "Test Plan2"); - expect(Cache().getMyExercisePlanDetails()[3].weightEquation, "60"); + expect(Cache().getMyExercisePlan()!.name, "Test Plan2"); + expect(Cache().getMyExercisePlanDetails()[3]!.weightEquation, "60"); }); test('Add new PlanDetail', () async { @@ -127,16 +127,16 @@ main() { await _exercisePlanRepository.saveExercisePlan(); - expect(_exercisePlanRepository.getExercisePlan().name, "Test Plan2"); - expect(Cache().getMyExercisePlanDetails()[5].weightEquation, "105"); - expect(Cache().getMyExercisePlanDetails()[5].repeats, 6); + expect(_exercisePlanRepository.getExercisePlan()!.name, "Test Plan2"); + expect(Cache().getMyExercisePlanDetails()[5]!.weightEquation, "105"); + expect(Cache().getMyExercisePlanDetails()[5]!.repeats, 6); }); test('Delete from PlanDetails', () async { _exercisePlanRepository.removeExerciseTypeFromPlanByExerciseTypeId(4); _exercisePlanRepository.saveExercisePlan(); - expect(_exercisePlanRepository.exercisePlanDetails[4].change, ModelChange.delete); + expect(_exercisePlanRepository.exercisePlanDetails[4]!.change, ModelChange.delete); expect(Cache().getMyExercisePlanDetails()[4], isNull); }); }); diff --git a/test/exercise_plan_test.dart b/test/exercise_plan_test.dart index 2836749..a8019ff 100644 --- a/test/exercise_plan_test.dart +++ b/test/exercise_plan_test.dart @@ -5,7 +5,6 @@ import 'package:aitrainer_app/service/exercise_plan_service.dart'; import 'package:test/test.dart'; main() { - setUp(() { Cache().setTestBaseUrl(); }); @@ -14,24 +13,18 @@ main() { test('add new plan and plan details', () async { final client = ExercisePlanApi(); - ExercisePlan exercisePlan = ExercisePlan( - "Test plan " + DateTime.now().toIso8601String(), - 62 - ); + ExercisePlan exercisePlan = ExercisePlan("Test plan " + DateTime.now().toIso8601String(), 62); exercisePlan.dateAdd = DateTime.now(); ExercisePlan savedPlan = await client.saveExercisePlan(exercisePlan); expect(savedPlan.name.substring(0, 9), "Test plan"); expect(savedPlan.customerId, 62); - - - int newPlanId = savedPlan.exercisePlanId; + int newPlanId = savedPlan.exercisePlanId!; //savedPlan.exercisePlanId = newPlanId; - ExercisePlanDetail detail = ExercisePlanDetail( - 39 //exerciseTypeId - ); + ExercisePlanDetail detail = ExercisePlanDetail(39 //exerciseTypeId + ); detail.serie = 3; detail.repeats = 12; detail.weightEquation = "90"; @@ -43,30 +36,28 @@ main() { expect(savedDetail.repeats, 12); expect(savedDetail.exercisePlanId, newPlanId); - await client.deleteExercisePlanDetail(savedDetail.exercisePlanDetailId); - await client.deleteExercisePlan(savedPlan.exercisePlanId); - + await client.deleteExercisePlanDetail(savedDetail.exercisePlanDetailId!); + await client.deleteExercisePlan(savedPlan.exercisePlanId!); }); }); test('get the last plan and change plan details', () async { final client = ExercisePlanApi(); - ExercisePlan exercisePlan = await client.getLastExercisePlan(61); - List list = await client.getExercisePlanDetail(exercisePlan.exercisePlanId); + ExercisePlan? exercisePlan = await client.getLastExercisePlan(61); + List list = await client.getExercisePlanDetail(exercisePlan!.exercisePlanId!); expect(list.length, 2); ExercisePlanDetail detail = ExercisePlanDetail(3); detail.serie = 4; detail.repeats = 12; detail.weightEquation = "10"; - detail.exercisePlanId = exercisePlan.exercisePlanId; + detail.exercisePlanId = exercisePlan.exercisePlanId!; //list.add(detail); ExercisePlanDetail newObjectToSave = await client.saveExercisePlanDetail(detail); - List list2 = await client.getExercisePlanDetail(exercisePlan.exercisePlanId); + List list2 = await client.getExercisePlanDetail(exercisePlan.exercisePlanId!); expect(list2.length, 3); expect(list2.last.weightEquation, "10"); - await client.deleteExercisePlanDetail(newObjectToSave.exercisePlanDetailId); - + await client.deleteExercisePlanDetail(newObjectToSave.exercisePlanDetailId!); }); -} \ No newline at end of file +} diff --git a/test/mocks.dart b/test/mocks.dart index 4cdb1e8..97f7dae 100644 --- a/test/mocks.dart +++ b/test/mocks.dart @@ -16,8 +16,8 @@ class MockExercisePlanApi extends Mock implements ExercisePlanApi { MockExercisePlanApi._internal(); - final List memoryExercisePlan = List(); - final List memoryExercisePlanDetail = List(); + final List memoryExercisePlan = []; + final List memoryExercisePlanDetail = []; Future saveExercisePlan(ExercisePlan plan) async { memoryExercisePlan.add(plan); @@ -32,14 +32,14 @@ class MockExercisePlanApi extends Mock implements ExercisePlanApi { } Future updateExercisePlanDetail(ExercisePlanDetail detail, int planDetailId) async { - ExercisePlanDetail updated; + ExercisePlanDetail? updated; memoryExercisePlanDetail.forEach((element) { if (element.exercisePlanDetailId == planDetailId) { element = detail; } }); - return updated; + return updated!; } Future deleteExercisePlanDetail(int exercisePlanId) async { @@ -57,7 +57,7 @@ class MockExercisePlanApi extends Mock implements ExercisePlanApi { } Future> getExercisePlanDetail(int exercisePlanId) async { - List foundList = List(); + List foundList = []; memoryExercisePlanDetail.forEach((element) { if (element.exercisePlanId == exercisePlanId) { foundList.add(element); @@ -66,8 +66,8 @@ class MockExercisePlanApi extends Mock implements ExercisePlanApi { return foundList; } - Future getLastExercisePlan(int customerId) async { - ExercisePlan found; + Future getLastExercisePlan(int customerId) async { + ExercisePlan? found; memoryExercisePlan.forEach((element) { if (element.customerId == customerId) { found = element; @@ -80,20 +80,20 @@ class MockExercisePlanApi extends Mock implements ExercisePlanApi { class SimExercisePlanRepository with ExercisePlanRepository { Future getExercisePlanDetails() async { if (exercisePlan == null) { - ExercisePlan exercisePlan = await this.getLastExercisePlan(); + ExercisePlan? exercisePlan = await this.getLastExercisePlan(); if (exercisePlan == null) { exercisePlanDetails = LinkedHashMap(); return; } } - List list = List(); + List list = []; LinkedHashMap listCache = Cache().getMyExercisePlanDetails(); if (listCache.length > 0) { exercisePlanDetails = listCache; return; } else { - list = await MockExercisePlanApi().getExercisePlanDetail(exercisePlan.exercisePlanId); + list = await MockExercisePlanApi().getExercisePlanDetail(exercisePlan!.exercisePlanId!); } exercisePlanDetails = LinkedHashMap(); @@ -108,11 +108,11 @@ class SimExercisePlanRepository with ExercisePlanRepository { return; } - Future getLastExercisePlan() async { + Future getLastExercisePlan() async { if (customerId == 0) { return null; } - ExercisePlan myExercisePlan = Cache().getMyExercisePlan(); + ExercisePlan? myExercisePlan = Cache().getMyExercisePlan(); if (myExercisePlan != null) { newPlan = false; return myExercisePlan; @@ -120,7 +120,7 @@ class SimExercisePlanRepository with ExercisePlanRepository { exercisePlan = await MockExercisePlanApi().getLastExercisePlan(customerId); newPlan = (exercisePlan == null); - Cache().setMyExercisePlan(exercisePlan); + Cache().setMyExercisePlan(exercisePlan!); return exercisePlan; } @@ -131,23 +131,23 @@ class SimExercisePlanRepository with ExercisePlanRepository { } String exercisePlanName; - if (this.customerId == Cache().userLoggedIn.customerId) { - exercisePlanName = Cache().userLoggedIn.name + " private"; + if (this.customerId == Cache().userLoggedIn!.customerId) { + exercisePlanName = Cache().userLoggedIn!.name! + " private"; } else { - exercisePlanName = Cache().getTrainee().name + " " + Cache().getTrainee().firstname + " private"; + exercisePlanName = Cache().getTrainee()!.name! + " " + Cache().getTrainee()!.firstname! + " private"; } exercisePlan = ExercisePlan(exercisePlanName, this.customerId); } if (newPlan) { - exercisePlan.dateAdd = DateTime.now(); - exercisePlan.private = true; + exercisePlan!.dateAdd = DateTime.now(); + exercisePlan!.private = true; - ExercisePlan savedExercisePlan = await MockExercisePlanApi().saveExercisePlan(exercisePlan); + ExercisePlan savedExercisePlan = await MockExercisePlanApi().saveExercisePlan(exercisePlan!); LinkedHashMap savedExercisePlanDetails = LinkedHashMap(); exercisePlanDetails.forEach((exerciseTypeId, exercisePlanDetail) async { - exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId; + exercisePlanDetail.exercisePlanId = savedExercisePlan.exercisePlanId!; ExercisePlanDetail savedDetail = await MockExercisePlanApi().saveExercisePlanDetail(exercisePlanDetail); @@ -156,14 +156,14 @@ class SimExercisePlanRepository with ExercisePlanRepository { exercisePlan = savedExercisePlan; } else { - await MockExercisePlanApi().updateExercisePlan(exercisePlan, exercisePlan.exercisePlanId); + await MockExercisePlanApi().updateExercisePlan(exercisePlan!, exercisePlan!.exercisePlanId!); exercisePlanDetails.forEach((exerciseTypeId, exercisePlanDetail) async { if (exercisePlanDetail.change == ModelChange.delete) { - await MockExercisePlanApi().deleteExercisePlanDetail(exercisePlanDetail.exercisePlanDetailId); + await MockExercisePlanApi().deleteExercisePlanDetail(exercisePlanDetail.exercisePlanDetailId!); Cache().deleteMyExercisePlanDetail(exercisePlanDetail); } else if (exercisePlanDetail.change == ModelChange.update) { - await MockExercisePlanApi().updateExercisePlanDetail(exercisePlanDetail, exercisePlanDetail.exercisePlanDetailId); + await MockExercisePlanApi().updateExercisePlanDetail(exercisePlanDetail, exercisePlanDetail.exercisePlanDetailId!); Cache().updateMyExercisePlanDetail(exercisePlanDetail); } else if (exercisePlanDetail.change == ModelChange.add) { await MockExercisePlanApi().saveExercisePlanDetail(exercisePlanDetail); diff --git a/test/widget_test.db.dart b/test/widget_test.db.dart index 7c39e0d..b1f5d8f 100644 --- a/test/widget_test.db.dart +++ b/test/widget_test.db.dart @@ -15,7 +15,7 @@ import 'package:aitrainer_app/util/common.dart'; import 'package:aitrainer_app/view/login.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; + import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; diff --git a/test/widget_test.login.dart b/test/widget_test.login.dart index 042322b..8b30ee4 100644 --- a/test/widget_test.login.dart +++ b/test/widget_test.login.dart @@ -16,7 +16,7 @@ import 'package:aitrainer_app/util/common.dart'; import 'package:aitrainer_app/view/login.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_form_bloc/flutter_form_bloc.dart'; + import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; @@ -41,23 +41,19 @@ class MockUserRepository extends Mock implements UserRepository { } } -class MockLoginBloc extends MockBloc implements LoginBloc {} - class MockCommon with Common { String getEmailError() { - return EMAIL_ERROR; + return emailError; } } void main() { group('LoginScreen', () { - MockLoginBloc loginBloc; - Widget loginWidget; - MockCommon common; + late Widget loginWidget; + late MockCommon common; setUp(() async { await DB().initDb(); - loginBloc = MockLoginBloc(); common = MockCommon(); loginWidget = MaterialApp(home: LoginPage(), localizationsDelegates: [