127 Commits

Author SHA1 Message Date
52e9f59e6f Transaction Details Bug Fixed 2025-09-10 18:10:18 +05:30
e4e104837b Localization Changes #6 2025-09-10 11:43:15 +05:30
dd7b7a6f4c balance added in transaction 2025-09-09 17:20:01 +05:30
c322d1d2fd Change Password Implemented 2025-09-09 16:03:34 +05:30
b3fb387bdd Change PasswordIntegration #1 2025-09-09 12:34:45 +05:30
asif
b62b8a157d added account balance in statement. Fixed bank logo in statement pdf.
removed unwanted log generations
2025-09-08 20:50:24 +05:30
c729b775c9 Change Password UI #2 2025-09-08 18:12:57 +05:30
465065db57 Change Password UI 2025-09-08 17:58:15 +05:30
0a6dde9ead Download PDF #2 2025-09-08 17:57:11 +05:30
b513664a47 Download PDF #1 2025-09-08 16:10:56 +05:30
d8d87e8da4 Localization Changes #6 2025-09-08 13:07:35 +05:30
1204507375 Add Beneficiary bugs fixed #2 2025-09-05 18:15:19 +05:30
be9a6fc93f Add Beneficiary bugs fixed 2025-09-05 12:02:48 +05:30
b8337d1152 Theme UI #2 2025-09-04 17:58:16 +05:30
d3792a1a06 Theme UI According to Client 2025-09-04 17:57:12 +05:30
845ce1fe78 Logout Button Implemented 2025-09-04 15:40:18 +05:30
45dbf8464a Theme Mode-System Default, Minor Changes & Logout Button #1 2025-09-04 13:43:52 +05:30
asif
a1ea60841e changed minSdk to 29 and also turned off backup in android manifest 2025-09-04 02:17:19 +05:30
asif
2abc315af9 removed unwanted comments from themes.dart 2025-09-04 01:58:26 +05:30
asif
a44ac67842 removed print statements 2025-09-04 01:57:32 +05:30
asif
1b684af3a8 added root and frida detection 2025-09-04 01:56:59 +05:30
asif
aa5a7877e4 added proguard for code obfuscation in android 2025-09-04 01:24:44 +05:30
asif
d6a99ea295 removed the newline from title bar 2025-09-04 01:24:14 +05:30
asif
cf8964ca36 changed add beneficiary screen to to improve UI 2025-09-04 00:58:30 +05:30
asif
c489bf3895 added SafeArea and changed buttton color in Add Beneficiary Page 2025-09-04 00:33:33 +05:30
asif
ba819f51d7 added safearea to some screens. Also fixed some titlebars from wrap text 2025-09-04 00:16:02 +05:30
asif
48f169d10c applied animations and haptics to TPIN screen 2025-09-04 00:14:36 +05:30
asif
64e80148a3 changed primary color usage to fix the color bug in dark mode
Changed Theme.of(context).primaryColor to Theme.of(contex).colorScheme.primary to make dark mode work properly.
2025-09-03 23:49:30 +05:30
asif
85f58c1e25 added const modifier 2025-09-03 23:46:58 +05:30
asif
3b9b1e507c implemented correct colors and proper animations in mpin screen. 2025-09-03 23:45:52 +05:30
57439f2acb Theme Mode #3 2025-09-03 17:39:57 +05:30
52534f9210 Theme Mode #2 2025-09-03 15:51:44 +05:30
d9f78629d2 Theme Mode #1 2025-09-03 15:15:09 +05:30
3e3465d5e8 Optimization #2 2025-09-03 12:10:28 +05:30
be76465774 Optimization #1 2025-09-03 11:41:41 +05:30
de596aa138 Code Obfuscation #1 2025-09-02 16:05:50 +05:30
720c6ec03a View Cards static page 2025-09-02 15:48:23 +05:30
d081a5433c Localization Changes #5 2025-09-01 16:41:32 +05:30
90f4a6bb81 Removed bugs and duplicates 2025-09-01 12:32:17 +05:30
asif
f71c8d646b removed a bunch of print statements and added a few async checks 2025-08-31 21:44:56 +05:30
asif
6a8f091ac5 changed welcome_screen to splash_screen in app.dart 2025-08-31 21:44:56 +05:30
asif
596f0a96eb replaced print with log in theme_cubit.dart 2025-08-31 21:44:04 +05:30
asif
768d312066 refactored welcome string to splash screen 2025-08-31 21:44:04 +05:30
asif
4277ca9169 replaced print with log in neft_service.dart 2025-08-31 21:44:04 +05:30
asif
53caa5b7ae removed decorations from title bar and chaged constant colors to themes 2025-08-31 21:44:04 +05:30
asif
bfa0721e79 removed unnecessary bg color from avatar 2025-08-31 21:44:04 +05:30
asif
75bcce8201 removed unnecessary decorations from title bar 2025-08-31 21:44:04 +05:30
asif
99f4b1b735 UI changes in customer info screen
Removed unnecessary decorations from title bar.
2025-08-31 21:44:04 +05:30
asif
6ebc96d153 removed some unnecessary code and add some async guards 2025-08-31 21:44:04 +05:30
asif
6496aa95c0 changed greeting font and size 2025-08-31 21:44:04 +05:30
asif
e91efafa0e increased font weight of title bar 2025-08-31 21:44:04 +05:30
asif
61a6e356d9 increased font weight in dashboard card 2025-08-31 21:44:04 +05:30
asif
a48781ad1b changed some wordings in the card 2025-08-31 21:44:04 +05:30
asif
d425af184e updated android ndk version 2025-08-31 21:44:04 +05:30
asif
bc2c460f96 changed the font size of acc no in card 2025-08-31 21:44:04 +05:30
asif
ef3556f207 removed some print statements 2025-08-31 21:44:04 +05:30
asif
6724d8bed0 refactored the balacnce card to remove unnecessary things 2025-08-31 21:44:04 +05:30
asif
83ed973b44 fixed some async gaps warnings 2025-08-31 21:44:04 +05:30
asif
f7dd31fb93 added rubik text theme 2025-08-31 21:44:04 +05:30
asif
9c60dc1c1c changed debit and credit icons colors 2025-08-31 21:44:04 +05:30
asif
c369ad415d added weight and dim color to the dashboard QL icons 2025-08-31 21:44:04 +05:30
asif
f934f0bff6 fixed some warnings and colors in the dashboard screen 2025-08-31 21:44:04 +05:30
asif
da0287ef38 fixed some print, async context warnings in
fund_transfer_amount_screen.dart
2025-08-31 21:44:04 +05:30
asif
f65507a706 fixed a context used across async gap warning and removed comments 2025-08-31 21:41:09 +05:30
9f6b35d3eb Beneficiary Details alignment fixed 2025-08-29 15:08:14 +05:30
a33b4bc1e1 Localization changes #4 2025-08-28 13:28:21 +05:30
0d629226a8 Available Balance in Account Statement #2 2025-08-27 18:21:42 +05:30
6d502a0c81 Available Balance in Account Statement 2025-08-27 17:17:47 +05:30
96d1e37c42 Beneficiary Validation Changes #2 2025-08-27 16:13:49 +05:30
b0610ad84d Beneficiary Validation Changes 2025-08-27 16:08:47 +05:30
ceb29ee7fe Manage Beneficiary delete Confirm 2025-08-27 15:00:46 +05:30
57cb93c124 Fund Transfer page with Own Bank and Outside Bank modified 2025-08-27 14:39:51 +05:30
0ac9a1f319 Merge branch 'uat-2' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/kmobile into uat-2 2025-08-27 13:18:30 +05:30
d3ad68b25c Fund Transfer page with Own Bank and Outside Bank modified 2025-08-27 13:16:26 +05:30
asif
eb0e1c120e Changed font size in transaction detail screen 2025-08-26 21:03:28 +05:30
a64e68d642 NEFT and RTGS transaction error resolved, 2025-08-26 16:42:30 +05:30
80faa06272 Merge branch 'uat-2' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/kmobile into uat-2 2025-08-26 16:00:26 +05:30
0bab68a2e6 NEFT and RTGS transaction error resolved 2025-08-26 15:58:31 +05:30
asif
351ee84414 formatted some files 2025-08-25 19:47:19 +05:30
asif
f77549310a Changed some formatting issues 2025-08-25 19:45:20 +05:30
4b28a113d4 color Changes minor 2025-08-25 18:10:52 +05:30
bf35ec61d5 Merge branch 'uat-2' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/kmobile into uat-2 2025-08-25 17:48:40 +05:30
180d3a3a60 Theme Colour bugs fixed 2025-08-25 17:47:18 +05:30
asif
737ce6cce6 Fixed some errors and delted some commented codes 2025-08-24 01:11:29 +05:30
asif
e75f48aed5 changed backend URL to point to load balancer 2025-08-24 01:04:38 +05:30
asif
5ee88403dd fixed context usage async gaps warnings and deleted some comments 2025-08-24 00:32:06 +05:30
asif
7fe8e8f084 fixed warnings related to colors and deleted some commented code 2025-08-24 00:31:25 +05:30
asif
59eb509dda formatted some files 2025-08-23 23:51:53 +05:30
asif
5f41c6e7f4 pubspec.lock 2025-08-23 23:49:51 +05:30
asif
36474786c1 generated localizations file to be ignored by git 2025-08-23 23:49:45 +05:30
asif
df51c4f30b resolved many context usage across async gaps warnings
also removed some unused code blocks
2025-08-23 23:41:52 +05:30
asif
cf8588b336 removed the logo blinking animation in login page 2025-08-23 23:41:52 +05:30
04c992c934 IMPS implementation 2025-08-22 16:36:58 +05:30
fc76528206 Branch Locator static Screen 2025-08-20 12:46:28 +05:30
7527db3d2f Merge branch 'uat-2' of https://7o9o-lb-526275444.ap-south-1.elb.amazonaws.com/md.asif5/kmobile into uat-2 2025-08-20 11:44:58 +05:30
19d3487552 FORMAT TESTING #! 2025-08-20 11:43:35 +05:30
asif
60a5703c35 formatted the whole codebase 2025-08-20 01:36:59 +05:30
09618db28e New file created for bank logos 2025-08-19 16:11:54 +05:30
712553e49f Localization Changes #3 2025-08-19 11:20:32 +05:30
842eef2cc7 Localization Chamges #2 2025-08-19 11:13:05 +05:30
asif
e6ea764785 formatted the whole codebase 2025-08-18 03:32:51 +05:30
e2a809d363 Beneficiary Localization Chamges 2025-08-14 16:15:35 +05:30
f48bfabb4a Transaction Details page Localizations 2025-08-13 18:06:53 +05:30
76d5874e19 Transaction Details localized to Hindi 2025-08-13 11:42:11 +05:30
913e31a6ab Transaction Details page 2025-08-12 18:10:02 +05:30
7f5258b5b7 Minor Changes of const and bank logos 2025-08-12 13:19:24 +05:30
asif
82951b7919 code reformatting and adding const everywhere 2025-08-12 11:47:10 +05:30
8ae26e2f18 Payment Error Message and Beneficiary Page 2025-08-11 17:03:02 +05:30
e7bbab13ba Bank Logos in beneficiary list 2025-08-11 13:13:28 +05:30
72862492c0 Changed Substring to full UTR No. 2025-08-11 12:34:41 +05:30
asif
f91d0f739b feat: Implement major features and fix theming bug
This commit introduces several new features and a critical bug fix.

- Implemented a full "Quick Pay" flow for both within and outside the bank, including IFSC validation, beneficiary verification, and a TPIN-based payment process.
- Added a date range filter to the Account Statement screen and streamlined the UI by removing the amount filters.
- Fixed a major bug that prevented dynamic theme changes from being applied. The app now correctly switches between color themes.
- Refactored and improved beneficiary management, transaction models, and the fund transfer flow to support NEFT/RTGS.
2025-08-11 04:06:05 +05:30
3024ddef15 Manage Beneficiary Services 2 2025-08-10 11:18:00 +05:30
83609fb778 Manage Beneficiary Services 2025-08-09 22:10:26 +05:30
dbc61abf00 Manage Beneficiary UI 2025-08-08 23:37:16 +05:30
763c101f58 Manage Beneficiary 2025-08-08 15:43:08 +05:30
117e2d5786 Manage Beneficiary fetch 2025-08-08 08:40:38 +05:30
ae40f61c01 Add Beneficiary Animations and Localizations 2025-08-07 23:36:28 +05:30
a1365b19d5 Add Beneficiary Animations 2025-08-07 21:07:32 +05:30
2dd7f4079b Add Beneficiary Validation API integration 2025-08-07 20:32:04 +05:30
99e23bf21d IFSC Code Validation and Add Beneficiary Validation API integration 2025-08-07 18:12:31 +05:30
c4d4261afc Theme 2025-08-06 17:26:25 +05:30
Nilanjan Chakrabarti
2fdef7c850 Shared Preferences Update 2025-07-31 16:14:29 +05:30
Nilanjan Chakrabarti
618bd4a9b9 Shared Preferences implementation 2025-07-30 12:50:11 +05:30
ee3961215a Merge branch 'language-translation' of https://git.7o9o.net/md.asif5/kmobile into language-translation 2025-07-24 22:24:30 +05:30
787fcdc2e2 changed imports of AppLocalization
Also added beneficiary validation while quick pay within bank
2025-07-24 22:21:19 +05:30
Nilanjan Chakrabarti
20791432dd Welcome Screen for both Login and Mpin Page 2025-07-18 12:48:52 +05:30
Nilanjan Chakrabarti
23d742ace9 New Update with Account Number Dropdown in Account Info 2025-07-11 12:09:38 +05:30
112 changed files with 6920 additions and 3341 deletions

3
.gitignore vendored
View File

@@ -41,3 +41,6 @@ app.*.map.json
/android/app/debug /android/app/debug
/android/app/profile /android/app/profile
/android/app/release /android/app/release
lib/l10n/app_localizations.dart
lib/l10n/app_localizations_en.dart
lib/l10n/app_localizations_hi.dart

View File

@@ -7,6 +7,10 @@
# The following line activates a set of recommended lints for Flutter apps, # The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices. # packages, and plugins designed to encourage good coding practices.
analyzer:
errors:
dead_code: ignore
non_constant_identifier_names: ignore
include: package:flutter_lints/flutter.yaml include: package:flutter_lints/flutter.yaml
linter: linter:

View File

@@ -25,7 +25,7 @@ if (flutterVersionName == null) {
android { android {
namespace "com.example.kmobile" namespace "com.example.kmobile"
compileSdk flutter.compileSdkVersion compileSdk flutter.compileSdkVersion
ndkVersion flutter.ndkVersion ndkVersion "27.0.12077973"
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
@@ -45,7 +45,7 @@ android {
applicationId "com.example.kmobile" applicationId "com.example.kmobile"
// You can update the following values to match your application needs. // You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion flutter.minSdkVersion minSdkVersion 29
targetSdkVersion flutter.targetSdkVersion targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
versionName flutterVersionName versionName flutterVersionName
@@ -56,6 +56,10 @@ android {
// TODO: Add your own signing config for the release build. // TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works. // Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug signingConfig signingConfigs.debug
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
} }
} }
} }

21
android/app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.util.** { *; }
-keep class io.flutter.view.** { *; }
-keep class io.flutter.embedding.** { *; }
-keep class io.flutter.embedding.engine.plugins.** { *; }
-keep class com.google.firebase.** { *; }
-keep class com.google.android.gms.** { *; }
# Please add these rules to your existing keep rules in order to suppress warnings.
# This is generated automatically by the Android Gradle plugin.
-dontwarn com.google.android.play.core.splitcompat.SplitCompatApplication
-dontwarn com.google.android.play.core.splitinstall.SplitInstallException
-dontwarn com.google.android.play.core.splitinstall.SplitInstallManager
-dontwarn com.google.android.play.core.splitinstall.SplitInstallManagerFactory
-dontwarn com.google.android.play.core.splitinstall.SplitInstallRequest$Builder
-dontwarn com.google.android.play.core.splitinstall.SplitInstallRequest
-dontwarn com.google.android.play.core.splitinstall.SplitInstallSessionState
-dontwarn com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener
-dontwarn com.google.android.play.core.tasks.OnFailureListener
-dontwarn com.google.android.play.core.tasks.OnSuccessListener
-dontwarn com.google.android.play.core.tasks.Task

View File

@@ -6,6 +6,7 @@
android:label="kmobile" android:label="kmobile"
android:name="${applicationName}" android:name="${applicationName}"
android:usesCleartextTraffic="true" android:usesCleartextTraffic="true"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"> android:icon="@mipmap/ic_launcher">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
assets/images/boi_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

BIN
assets/images/hdfc_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
assets/images/ipos_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

BIN
assets/images/pnb_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
assets/images/sbi_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
assets/images/uco_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -3,7 +3,7 @@ template-arb-file: app_en.arb
output-localization-file: app_localizations.dart output-localization-file: app_localizations.dart
output-class: AppLocalizations output-class: AppLocalizations
use-deferred-loading: false use-deferred-loading: false
synthetic-package: false
use-maybe-of: true use-maybe-of: true
synthetic-package: true
nullable-getter : false nullable-getter : false
untranslated-message-file: l10n_missing_translations.json untranslated-message-file: l10n_missing_translations.json

View File

@@ -1,15 +1,17 @@
// ignore_for_file: unused_local_variable
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import '../../data/repositories/auth_repository.dart'; import '../../data/repositories/auth_repository.dart';
class AuthInterceptor extends Interceptor { class AuthInterceptor extends Interceptor {
final AuthRepository _authRepository; final AuthRepository _authRepository;
final Dio _dio; final Dio _dio;
AuthInterceptor(this._authRepository, this._dio); AuthInterceptor(this._authRepository, this._dio);
@override @override
Future<void> onRequest( Future<void> onRequest(
RequestOptions options, RequestOptions options,
RequestInterceptorHandler handler, RequestInterceptorHandler handler,
) async { ) async {
// Skip auth header for login and refresh endpoints // Skip auth header for login and refresh endpoints
@@ -17,31 +19,38 @@ class AuthInterceptor extends Interceptor {
options.path.contains('/auth/refresh')) { options.path.contains('/auth/refresh')) {
return handler.next(options); return handler.next(options);
} }
// Get token and add to request // Get token and add to request
final token = await _authRepository.getAccessToken(); final token = await _authRepository.getAccessToken();
if (token != null) { if (token != null) {
options.headers['Authorization'] = 'Bearer $token'; options.headers['Authorization'] = 'Bearer $token';
} }
return handler.next(options); return handler.next(options);
} }
@override @override
Future<void> onError( Future<void> onError(
DioException err, DioException err,
ErrorInterceptorHandler handler, ErrorInterceptorHandler handler,
) async { ) async {
// Handle 401 errors by refreshing token and retrying // Handle 401 errors by refreshing token and retrying
if (err.response?.statusCode == 401) { final response = err.response;
if (response?.statusCode == 401) {
final data = response?.data;
// Only refresh token if error is NOT INCORRECT_TPIN (or similar business error)
if (data is Map && data['error'] == 'INCORRECT_TPIN') {
// Pass the error through, do not retry
return handler.next(err);
}
// On 401, try to get a new token // On 401, try to get a new token
final token = await _authRepository.getAccessToken(); final token = await _authRepository.getAccessToken();
if (token != null) { if (token != null) {
// If we have a new token, retry the request // If we have a new token, retry the request
final opts = err.requestOptions; final opts = err.requestOptions;
opts.headers['Authorization'] = 'Bearer $token'; opts.headers['Authorization'] = 'Bearer $token';
try { try {
final response = await _dio.fetch(opts); final response = await _dio.fetch(opts);
return handler.resolve(response); return handler.resolve(response);
@@ -50,7 +59,7 @@ class AuthInterceptor extends Interceptor {
} }
} }
} }
return handler.next(err); return handler.next(err);
} }
} }

View File

@@ -4,7 +4,6 @@ import '../../features/auth/models/auth_token.dart';
import '../../features/auth/models/auth_credentials.dart'; import '../../features/auth/models/auth_credentials.dart';
import '../../core/errors/exceptions.dart'; import '../../core/errors/exceptions.dart';
class AuthService { class AuthService {
final Dio _dio; final Dio _dio;
AuthService(this._dio); AuthService(this._dio);
@@ -15,7 +14,7 @@ class AuthService {
'/api/auth/login', '/api/auth/login',
data: credentials.toJson(), data: credentials.toJson(),
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
return AuthToken.fromJson(response.data); return AuthToken.fromJson(response.data);
} else { } else {
@@ -30,7 +29,8 @@ class AuthService {
} }
throw NetworkException('Network error during login'); throw NetworkException('Network error during login');
} catch (e) { } catch (e) {
throw UnexpectedException('Unexpected error during login: ${e.toString()}'); throw UnexpectedException(
'Unexpected error during login: ${e.toString()}');
} }
} }
@@ -40,7 +40,7 @@ class AuthService {
'/auth/refresh', '/auth/refresh',
data: {'refresh_token': refreshToken}, data: {'refresh_token': refreshToken},
); );
if (response.statusCode == 200) { if (response.statusCode == 200) {
return AuthToken.fromJson(response.data); return AuthToken.fromJson(response.data);
} else { } else {
@@ -54,7 +54,7 @@ class AuthService {
Future<bool> checkTpin() async { Future<bool> checkTpin() async {
try { try {
final response = await _dio.get('/api/auth/tpin'); final response = await _dio.get('/api/auth/tpin');
if (response.statusCode == 200) { if (response.statusCode == 200) {
return response.data['tpinSet'] as bool; return response.data['tpinSet'] as bool;
} else { } else {
@@ -66,7 +66,8 @@ class AuthService {
} }
throw NetworkException('Network error during TPIN check'); throw NetworkException('Network error during TPIN check');
} catch (e) { } catch (e) {
throw UnexpectedException('Unexpected error during TPIN check: ${e.toString()}'); throw UnexpectedException(
'Unexpected error during TPIN check: ${e.toString()}');
} }
} }
@@ -76,7 +77,7 @@ class AuthService {
'/api/auth/tpin', '/api/auth/tpin',
data: {'tpin': tpin}, data: {'tpin': tpin},
); );
if (response.statusCode != 200) { if (response.statusCode != 200) {
throw AuthException('Failed to set TPIN'); throw AuthException('Failed to set TPIN');
} }
@@ -86,8 +87,8 @@ class AuthService {
} }
throw NetworkException('Network error during TPIN setup'); throw NetworkException('Network error during TPIN setup');
} catch (e) { } catch (e) {
throw UnexpectedException('Unexpected error during TPIN setup: ${e.toString()}'); throw UnexpectedException(
'Unexpected error during TPIN setup: ${e.toString()}');
} }
} }
}
}

View File

@@ -0,0 +1,126 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:kmobile/core/errors/exceptions.dart';
import 'package:kmobile/data/models/ifsc.dart';
import 'package:kmobile/data/models/beneficiary.dart';
class BeneficiaryService {
final Dio _dio;
BeneficiaryService(this._dio);
Future<String> validateBeneficiaryWithinBank(String accountNumber) async {
try {
final response = await _dio
.get('/api/beneficiary/validate/within-bank', queryParameters: {
'accountNumber': accountNumber,
});
if (response.statusCode == 200) {
return response.data['name'];
} else {
throw Exception(
response.data['error'] ?? 'Failed to validate beneficiary');
}
} on DioException catch (e) {
throw Exception('Network error: ${e.message}');
} catch (e) {
throw Exception('Unexpected error: ${e.toString()}');
}
}
Future<Ifsc> validateIFSC(String ifscCode) async {
try {
final response = await _dio.get('/api/beneficiary/ifsc-details',
queryParameters: {"ifscCode": ifscCode});
if (response.statusCode == 200) {
return Ifsc.fromJson(response.data);
}
} on DioException catch (e) {
if (e.response?.statusCode == 404) {
throw Exception('INVALID IFSC CODE');
}
else if (e.response?.statusCode == 401) {
throw Exception('INVALID IFSC CODE');
}
} catch (e) {
throw UnexpectedException(
'Unexpected error during login: ${e.toString()}');
}
return Ifsc.fromJson({});
}
Future<String> validateBeneficiary({
required String accountNo,
required String ifscCode,
required String remitterName,
}) async {
log('inside validate beneficiary service');
final response = await _dio.get(
'/api/beneficiary/validate/outside-bank',
queryParameters: {
'accountNo': accountNo,
'ifscCode': ifscCode,
'remitterName': remitterName,
},
);
if (response.statusCode != 200) {
throw Exception("Invalid Beneficiary Details");
}
return response.data['name'];
}
// Beneficiary Validate And ADD
Future<bool> sendForValidation(Beneficiary beneficiary) async {
try {
final response = await _dio.post(
'/api/beneficiary',
data: beneficiary.toJson(),
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
} catch (e) {
rethrow;
}
}
Future<List<Beneficiary>> fetchBeneficiaryList() async {
try {
final response = await _dio.get(
"/api/beneficiary",
options: Options(
headers: {
"Content-Type": "application/json",
},
),
);
if (response.statusCode == 200) {
return Beneficiary.listFromJson(response.data);
} else {
throw Exception("Failed to fetch beneficiaries");
}
} catch (e) {
return [];
}
}
Future<void> deleteBeneficiary(String accountNo) async {
try {
final response = await _dio.delete('/api/beneficiary/$accountNo');
if (response.statusCode != 204) {
throw Exception('Failed to delete beneficiary');
}
} on DioException catch (e) {
throw Exception('Network error: ${e.message}');
} catch (e) {
throw Exception('Unexpected error: ${e.toString()}');
}
}
}

View File

@@ -0,0 +1,60 @@
import 'package:dio/dio.dart';
class ChangePasswordService {
final Dio _dio;
ChangePasswordService(this._dio);
Future getOtp({
required String mobileNumber,
}) async {
final response = await _dio.post(
'/api/otp/send',
data: {
'mobileNumber': mobileNumber,
'type': "CHANGE_LPWORD"
},
);
if (response.statusCode != 200) {
throw Exception("Invalid Mobile Number/Type");
}
print(response.toString());
return response.toString();
}
Future validateOtp({
required String otp,
required String mobileNumber,
}) async {
final response = await _dio.post(
'/api/otp/verify?mobileNumber=$mobileNumber',
data: {
'otp' : otp,
},
);
if (response.statusCode != 200) {
throw Exception("Wrong OTP");
}
return response.toString();
}
Future validateChangePwd({
required String OldLPsw,
required String newLPsw,
required String confirmLPsw,
}) async {
final response = await _dio.post(
'/api/auth/change/login_password',
data: {
'OldLPsw': OldLPsw,
'newLPsw': newLPsw,
'confirmLPsw': confirmLPsw,
},
);
if (response.statusCode != 200) {
throw Exception("Wrong OTP");
}
return response.toString();
}
}

View File

@@ -0,0 +1,31 @@
import 'package:dio/dio.dart';
import 'package:kmobile/data/models/imps_response.dart';
import 'package:kmobile/data/models/imps_transaction.dart';
class ImpsService {
final Dio _dio;
ImpsService(this._dio);
Future<ImpsResponse> processImpsTransaction(
ImpsTransaction transaction) async {
try {
await Future.delayed(const Duration(seconds: 3));
final response = await _dio.post(
'/api/payment/imps',
data: transaction.toJson(),
);
if (response.statusCode == 200) {
return ImpsResponse.fromJson(response.data);
} else {
throw Exception(
'IMPS transaction failed with status code: ${response.statusCode}');
}
} on DioException {
rethrow;
} catch (e) {
throw Exception('An unexpected error occurred: ${e.toString()}');
}
}
}

View File

@@ -0,0 +1,34 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:kmobile/data/models/neft_response.dart';
import 'package:kmobile/data/models/neft_transaction.dart';
class NeftService {
final Dio _dio;
NeftService(this._dio);
Future<NeftResponse> processNeftTransaction(
NeftTransaction transaction) async {
try {
await Future.delayed(const Duration(seconds: 3));
final response = await _dio.post(
'/api/payment/neft',
data: transaction.toJson(),
);
if (response.statusCode == 200) {
return NeftResponse.fromJson(response.data);
} else {
throw Exception(
'NEFT transaction failed with status code: ${response.statusCode}');
}
} on DioException {
log('DioException Occured');
rethrow;
} catch (e) {
throw Exception('An unexpected error occurred: ${e.toString()}');
}
}
}

View File

@@ -1,5 +1,4 @@
import 'dart:developer'; import 'dart:developer';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:kmobile/data/models/payment_response.dart'; import 'package:kmobile/data/models/payment_response.dart';
import 'package:kmobile/data/models/transfer.dart'; import 'package:kmobile/data/models/transfer.dart';
@@ -11,8 +10,8 @@ class PaymentService {
Future<PaymentResponse> processQuickPayWithinBank(Transfer transfer) async { Future<PaymentResponse> processQuickPayWithinBank(Transfer transfer) async {
try { try {
await Future.delayed(const Duration(seconds: 3)); // Simulate delay await Future.delayed(const Duration(seconds: 3)); // Simulate delay
final response =
await _dio.post('/api/payment/transfer', data: transfer.toJson()); await _dio.post('/api/payment/transfer', data: transfer.toJson());
return PaymentResponse( return PaymentResponse(
isSuccess: true, isSuccess: true,
@@ -20,8 +19,6 @@ class PaymentService {
creditedAccount: transfer.toAccount, creditedAccount: transfer.toAccount,
amount: transfer.amount, amount: transfer.amount,
currency: "INR", currency: "INR",
errorMessage: response.data['errorMessage'],
errorCode: response.data['errorCode'],
); );
} on DioException catch (e) { } on DioException catch (e) {
log('DioException: ${e.toString()}'); log('DioException: ${e.toString()}');

View File

@@ -0,0 +1,31 @@
import 'package:dio/dio.dart';
import 'package:kmobile/data/models/rtgs_response.dart';
import 'package:kmobile/data/models/rtgs_transaction.dart';
class RtgsService {
final Dio _dio;
RtgsService(this._dio);
Future<RtgsResponse> processRtgsTransaction(
RtgsTransaction transaction) async {
try {
await Future.delayed(const Duration(seconds: 3));
final response = await _dio.post(
'/api/payment/rtgs',
data: transaction.toJson(),
);
if (response.statusCode == 200) {
return RtgsResponse.fromJson(response.data);
} else {
throw Exception(
'RTGS transaction failed with status code: ${response.statusCode}');
}
} on DioException {
rethrow;
} catch (e) {
throw Exception('An unexpected error occurred: ${e.toString()}');
}
}
}

View File

@@ -28,4 +28,4 @@ class UserService {
throw Exception('Unexpected error: ${e.toString()}'); throw Exception('Unexpected error: ${e.toString()}');
} }
} }
} }

View File

@@ -2,21 +2,24 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/features/auth/controllers/theme_mode_cubit.dart';
import 'package:kmobile/features/auth/controllers/theme_mode_state.dart';
import 'package:kmobile/security/secure_storage.dart'; import 'package:kmobile/security/secure_storage.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import './l10n/app_localizations.dart';
import 'config/themes.dart'; import 'package:kmobile/features/auth/controllers/theme_cubit.dart';
import 'package:kmobile/features/auth/controllers/theme_state.dart';
import 'config/routes.dart'; import 'config/routes.dart';
import 'di/injection.dart'; import 'di/injection.dart';
import 'features/auth/controllers/auth_cubit.dart'; import 'features/auth/controllers/auth_cubit.dart';
import 'features/card/screens/card_management_screen.dart'; import 'features/card/screens/card_management_screen.dart';
import 'features/auth/screens/welcome_screen.dart'; import 'features/auth/screens/splash_screen.dart';
import 'features/auth/screens/login_screen.dart'; import 'features/auth/screens/login_screen.dart';
import 'features/service/screens/service_screen.dart'; import 'features/service/screens/service_screen.dart';
import 'features/dashboard/screens/dashboard_screen.dart'; import 'features/dashboard/screens/dashboard_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'features/auth/screens/mpin_screen.dart'; import 'features/auth/screens/mpin_screen.dart';
import 'package:local_auth/local_auth.dart'; import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
class KMobile extends StatefulWidget { class KMobile extends StatefulWidget {
const KMobile({super.key}); const KMobile({super.key});
@@ -32,20 +35,31 @@ class KMobile extends StatefulWidget {
} }
class _KMobileState extends State<KMobile> { class _KMobileState extends State<KMobile> {
bool _showSplash = false; bool showSplash = true;
Locale? _locale;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Simulate a splash screen delay loadPreferences();
Future.delayed(const Duration(seconds: 2), () { Future.delayed(const Duration(seconds: 3), () {
setState(() { setState(() {
_showSplash = false; showSplash = false;
}); });
}); });
} }
Locale? _locale; Future<void> loadPreferences() async {
final prefs = await SharedPreferences.getInstance();
// Load Locale
final String? langCode = prefs.getString('locale');
if (langCode != null) {
setState(() {
_locale = Locale(langCode);
});
}
}
void setLocale(Locale locale) { void setLocale(Locale locale) {
setState(() { setState(() {
@@ -53,58 +67,8 @@ class _KMobileState extends State<KMobile> {
}); });
} }
/*
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Set status bar color
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark,
),
);
if (_showSplash) {
return MaterialApp(
debugShowCheckedModeBanner: false,
locale: _locale,
supportedLocales: const [
Locale('en'),
Locale('hi'),
],
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: const SplashScreen(),
);
}
return MultiBlocProvider(
providers: [
BlocProvider<AuthCubit>(create: (_) => getIt<AuthCubit>()),
],
child: MaterialApp(
title: 'kMobile',
// debugShowCheckedModeBanner: false,
theme: AppThemes.lightTheme,
// darkTheme: AppThemes.darkTheme,
themeMode: ThemeMode.system, // Use system theme by default
onGenerateRoute: AppRoutes.generateRoute,
initialRoute: AppRoutes.splash,
home: const AuthGate(),
),
);
}
*/
@override
Widget build(BuildContext context) {
// Set status bar color
SystemChrome.setSystemUIOverlayStyle( SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle( const SystemUiOverlayStyle(
statusBarColor: Colors.transparent, statusBarColor: Colors.transparent,
@@ -115,27 +79,37 @@ class _KMobileState extends State<KMobile> {
return MultiBlocProvider( return MultiBlocProvider(
providers: [ providers: [
BlocProvider<AuthCubit>(create: (_) => getIt<AuthCubit>()), BlocProvider<AuthCubit>(create: (_) => getIt<AuthCubit>()),
BlocProvider<ThemeCubit>(create: (_) => ThemeCubit()),
BlocProvider<ThemeModeCubit>(create: (_) => ThemeModeCubit()),
], ],
child: MaterialApp( child: BlocBuilder<ThemeCubit, ThemeState>(
debugShowCheckedModeBanner: false, builder: (context, themeState) {
locale: _locale, // Use your existing locale variable return BlocBuilder<ThemeModeCubit, ThemeModeState>(
supportedLocales: const [ builder: (context, modeState) {
Locale('en'), return MaterialApp(
Locale('hi'), debugShowCheckedModeBanner: false,
], locale: _locale ?? const Locale('en'),
localizationsDelegates: const [ supportedLocales: const [
AppLocalizations.delegate, Locale('en'),
GlobalMaterialLocalizations.delegate, Locale('hi'),
GlobalWidgetsLocalizations.delegate, ],
GlobalCupertinoLocalizations.delegate, localizationsDelegates: const [
], AppLocalizations.delegate,
title: 'kMobile', GlobalMaterialLocalizations.delegate,
theme: AppThemes.lightTheme, GlobalWidgetsLocalizations.delegate,
// darkTheme: AppThemes.darkTheme, GlobalCupertinoLocalizations.delegate,
themeMode: ThemeMode.system, // Use system theme by default ],
onGenerateRoute: AppRoutes.generateRoute, title: 'kMobile',
initialRoute: AppRoutes.splash, theme: themeState.getLightThemeData(),
home: _showSplash ? const SplashScreen() : const AuthGate(), darkTheme: themeState.getDarkThemeData(),
themeMode: context.watch<ThemeModeCubit>().state.mode,
onGenerateRoute: AppRoutes.generateRoute,
initialRoute: AppRoutes.splash,
home: showSplash ? const SplashScreen() : const AuthGate(),
);
},
);
},
), ),
); );
} }
@@ -151,7 +125,6 @@ class AuthGate extends StatefulWidget {
class _AuthGateState extends State<AuthGate> { class _AuthGateState extends State<AuthGate> {
bool _checking = true; bool _checking = true;
bool _isLoggedIn = false; bool _isLoggedIn = false;
bool _showWelcome = true;
bool _hasMPin = false; bool _hasMPin = false;
bool _biometricEnabled = false; bool _biometricEnabled = false;
bool _biometricTried = false; bool _biometricTried = false;
@@ -184,9 +157,13 @@ class _AuthGateState extends State<AuthGate> {
final localAuth = LocalAuthentication(); final localAuth = LocalAuthentication();
final canCheck = await localAuth.canCheckBiometrics; final canCheck = await localAuth.canCheckBiometrics;
if (!canCheck) return false; if (!canCheck) return false;
String localizedReason = "";
if (mounted) {
localizedReason = AppLocalizations.of(context).authenticateToAccess;
}
try { try {
final didAuth = await localAuth.authenticate( final didAuth = await localAuth.authenticate(
localizedReason: AppLocalizations.of(context).authenticateToAccess, localizedReason: localizedReason,
options: const AuthenticationOptions( options: const AuthenticationOptions(
stickyAuth: true, stickyAuth: true,
biometricOnly: true, biometricOnly: true,
@@ -198,106 +175,6 @@ class _AuthGateState extends State<AuthGate> {
} }
} }
/* @override
Widget build(BuildContext context) {
if (_checking) {
return const SplashScreen();
}
if (_isLoggedIn) {
if (_hasMPin) {
if (_biometricEnabled) {
return FutureBuilder<bool>(
future: _tryBiometric(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const SplashScreen();
}
if (snapshot.data == true) {
// Authenticated with biometrics, go to dashboard
return const NavigationScaffold();
}
// If not authenticated or user dismissed, show mPIN screen
return MPinScreen(
mode: MPinMode.enter,
onCompleted: (_) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => const NavigationScaffold()),
);
},
);
},
);
} else {
return MPinScreen(
mode: MPinMode.enter,
onCompleted: (_) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const NavigationScaffold()),
);
},
);
}
} else {
return MPinScreen(
mode: MPinMode.set,
onCompleted: (_) async {
final storage = getIt<SecureStorage>();
final localAuth = LocalAuthentication();
// 1) Prompt user to optin for biometric
final optIn = await showDialog<bool>(
context: context,
barrierDismissible: false, // force choice
builder: (ctx) => AlertDialog(
title: const Text('Enable Fingerprint Login?'),
content: const Text(
'Would you like to enable fingerprint authentication for faster login?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('No'),
),
TextButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Yes'),
),
],
),
);
// 2) If opted in, perform biometric auth
if (optIn == true) {
final canCheck = await localAuth.canCheckBiometrics;
bool didAuth = false;
if (canCheck) {
didAuth = await localAuth.authenticate(
localizedReason: 'Authenticate to enable fingerprint login',
options: const AuthenticationOptions(
stickyAuth: true,
biometricOnly: true,
),
);
}
await storage.write(
'biometric_enabled', didAuth ? 'true' : 'false');
} else {
await storage.write('biometric_enabled', 'false');
}
// 3) Finally go to your main scaffold
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const NavigationScaffold()),
);
},
);
}
}
return const LoginScreen();
}
}*/
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (_checking) { if (_checking) {
@@ -318,7 +195,6 @@ class _AuthGateState extends State<AuthGate> {
return const NavigationScaffold(); // Authenticated return const NavigationScaffold(); // Authenticated
} }
// Failed or dismissed biometric → Show MPIN
return MPinScreen( return MPinScreen(
mode: MPinMode.enter, mode: MPinMode.enter,
onCompleted: (_) { onCompleted: (_) {
@@ -349,15 +225,15 @@ class _AuthGateState extends State<AuthGate> {
onCompleted: (_) async { onCompleted: (_) async {
final storage = getIt<SecureStorage>(); final storage = getIt<SecureStorage>();
final localAuth = LocalAuthentication(); final localAuth = LocalAuthentication();
final optin = await showDialog<bool>(
final optIn = await showDialog<bool>(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
builder: (ctx) => AlertDialog( builder: (ctx) => AlertDialog(
title: title:
Text(AppLocalizations.of(context).enableFingerprintLogin), Text(AppLocalizations.of(context).enableFingerprintLogin),
content: Text( content:
AppLocalizations.of(context).enableFingerprintMessage, Text(AppLocalizations.of(context).enableFingerprintMessage),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.of(ctx).pop(false), onPressed: () => Navigator.of(ctx).pop(false),
@@ -371,49 +247,40 @@ class _AuthGateState extends State<AuthGate> {
), ),
); );
if (optin == true) { if (optIn == true) {
final canCheck = await localAuth.canCheckBiometrics; final canCheck = await localAuth.canCheckBiometrics;
bool didAuth = false; bool didAuth = false;
String authEnable = "";
if (context.mounted) {
authEnable = AppLocalizations.of(context).authenticateToEnable;
}
if (canCheck) { if (canCheck) {
didAuth = await localAuth.authenticate( didAuth = await localAuth.authenticate(
localizedReason: localizedReason: authEnable,
AppLocalizations.of(context).authenticateToEnable,
options: const AuthenticationOptions( options: const AuthenticationOptions(
stickyAuth: true, stickyAuth: true,
biometricOnly: true, biometricOnly: true,
), ),
); );
await storage.write(
'biometric_enabled', didAuth ? 'true' : 'false');
} else {
await storage.write('biometric_enabled', 'false');
} }
await storage.write(
'biometric_enabled',
didAuth ? 'true' : 'false',
);
} else {
await storage.write('biometric_enabled', 'false');
} }
Navigator.of(context).pushReplacement( if (context.mounted) {
MaterialPageRoute( Navigator.of(context).pushReplacement(
builder: (_) => const NavigationScaffold(), MaterialPageRoute(
), builder: (_) => const NavigationScaffold(),
); ),
);
}
}, },
); );
} }
} }
// 🔻 Show Welcome screen before login if not logged in
if (_showWelcome) {
return WelcomeScreen(
onContinue: () {
setState(() {
_showWelcome = false;
});
},
);
}
return const LoginScreen(); return const LoginScreen();
} }
} }
@@ -435,13 +302,6 @@ class _NavigationScaffoldState extends State<NavigationScaffold> {
const ServiceScreen(), const ServiceScreen(),
]; ];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
_pageController.jumpToPage(index);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return PopScope( return PopScope(
@@ -480,45 +340,31 @@ class _NavigationScaffoldState extends State<NavigationScaffold> {
children: _pages, children: _pages,
), ),
bottomNavigationBar: BottomNavigationBar( bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex, currentIndex: _selectedIndex,
type: BottomNavigationBarType.fixed, type: BottomNavigationBarType.fixed,
backgroundColor: const Color(0xFFE0F7FA), // Light blue background backgroundColor: const Color(0XFF1E58AD),
selectedItemColor: Colors.blue[800], selectedItemColor: Theme.of(context).colorScheme.onPrimary,
unselectedItemColor: Colors.black54, unselectedItemColor:
onTap: _onItemTapped, Theme.of(context).colorScheme.onSecondary,
items: [ onTap: (index) {
BottomNavigationBarItem( setState(() {
icon: const Icon(Icons.home_filled), _selectedIndex = index;
label: AppLocalizations.of(context).home, });
), _pageController.jumpToPage(index);
BottomNavigationBarItem( },
icon: const Icon(Icons.credit_card), items: [
label: AppLocalizations.of(context).card, BottomNavigationBarItem(
), icon: const Icon(Icons.home_filled),
BottomNavigationBarItem( label: AppLocalizations.of(context).home,
icon: const Icon(Icons.miscellaneous_services), ),
label: AppLocalizations.of(context).services, BottomNavigationBarItem(
), icon: const Icon(Icons.credit_card),
]), label: AppLocalizations.of(context).card,
), ),
); BottomNavigationBarItem(
} icon: const Icon(Icons.miscellaneous_services),
} label: AppLocalizations.of(context).services,
),
class SplashScreen extends StatelessWidget {
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 20),
Text(AppLocalizations.of(context).loading,
style: Theme.of(context).textTheme.headlineMedium),
], ],
), ),
), ),
@@ -538,8 +384,12 @@ class BiometricPromptScreen extends StatelessWidget {
onCompleted(); onCompleted();
return; return;
} }
String localizedReason = "";
if (context.mounted) {
localizedReason = AppLocalizations.of(context).enableFingerprintQuick;
}
final didAuth = await localAuth.authenticate( final didAuth = await localAuth.authenticate(
localizedReason: AppLocalizations.of(context).enableFingerprintQuick, localizedReason: localizedReason,
options: const AuthenticationOptions( options: const AuthenticationOptions(
stickyAuth: true, stickyAuth: true,
biometricOnly: true, biometricOnly: true,
@@ -583,6 +433,9 @@ class BiometricPromptScreen extends StatelessWidget {
], ],
), ),
); );
if (!context.mounted) {
return;
}
if (result == true) { if (result == true) {
await _handleBiometric(context); await _handleBiometric(context);
} else { } else {

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/features/auth/screens/mpin_screen.dart'; import 'package:kmobile/features/auth/screens/mpin_screen.dart';
import 'package:kmobile/features/auth/screens/splash_screen.dart';
import '../app.dart'; import '../app.dart';
import '../features/auth/screens/login_screen.dart'; import '../features/auth/screens/login_screen.dart';
// import '../features/auth/screens/forgot_password_screen.dart'; // import '../features/auth/screens/forgot_password_screen.dart';
@@ -13,7 +14,7 @@ import '../features/dashboard/screens/dashboard_screen.dart';
class AppRoutes { class AppRoutes {
// Private constructor to prevent instantiation // Private constructor to prevent instantiation
AppRoutes._(); AppRoutes._();
// Route names // Route names
static const String splash = '/'; static const String splash = '/';
static const String login = '/login'; static const String login = '/login';
@@ -25,7 +26,7 @@ class AppRoutes {
static const String accounts = '/accounts'; static const String accounts = '/accounts';
static const String transactions = '/transactions'; static const String transactions = '/transactions';
static const String payments = '/payments'; static const String payments = '/payments';
// Route generator // Route generator
static Route<dynamic> generateRoute(RouteSettings settings) { static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) { switch (settings.name) {
@@ -35,13 +36,16 @@ class AppRoutes {
return MaterialPageRoute(builder: (_) => const LoginScreen()); return MaterialPageRoute(builder: (_) => const LoginScreen());
case mPin: case mPin:
return MaterialPageRoute(builder: (_) => const MPinScreen(mode: MPinMode.enter,)); return MaterialPageRoute(
builder: (_) => const MPinScreen(
mode: MPinMode.enter,
));
case register: case register:
// Placeholder - create the RegisterScreen class and uncomment // Placeholder - create the RegisterScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const RegisterScreen()); // return MaterialPageRoute(builder: (_) => const RegisterScreen());
return _errorRoute(); return _errorRoute();
case forgotPassword: case forgotPassword:
// Placeholder - create the ForgotPasswordScreen class and uncomment // Placeholder - create the ForgotPasswordScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const ForgotPasswordScreen()); // return MaterialPageRoute(builder: (_) => const ForgotPasswordScreen());
@@ -49,31 +53,30 @@ class AppRoutes {
case navigationScaffold: case navigationScaffold:
return MaterialPageRoute(builder: (_) => const NavigationScaffold()); return MaterialPageRoute(builder: (_) => const NavigationScaffold());
case dashboard: case dashboard:
return MaterialPageRoute(builder: (_) => const DashboardScreen()); return MaterialPageRoute(builder: (_) => const DashboardScreen());
case accounts: case accounts:
// Placeholder - create the AccountsScreen class and uncomment // Placeholder - create the AccountsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const AccountsScreen()); // return MaterialPageRoute(builder: (_) => const AccountsScreen());
return _errorRoute(); return _errorRoute();
case transactions: case transactions:
// Placeholder - create the TransactionsScreen class and uncomment // Placeholder - create the TransactionsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const TransactionsScreen()); // return MaterialPageRoute(builder: (_) => const TransactionsScreen());
return _errorRoute(); return _errorRoute();
case payments: case payments:
// Placeholder - create the PaymentsScreen class and uncomment // Placeholder - create the PaymentsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const PaymentsScreen()); // return MaterialPageRoute(builder: (_) => const PaymentsScreen());
return _errorRoute(); return _errorRoute();
default: default:
return _errorRoute(); return _errorRoute();
} }
} }
// Error route // Error route
static Route<dynamic> _errorRoute() { static Route<dynamic> _errorRoute() {
return MaterialPageRoute(builder: (_) { return MaterialPageRoute(builder: (_) {
@@ -87,4 +90,4 @@ class AppRoutes {
); );
}); });
} }
} }

View File

@@ -0,0 +1,7 @@
enum ThemeType {
violet,
green,
orange,
blue,
yellow,
}

View File

@@ -1,266 +1,52 @@
import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'theme_type.dart';
import 'package:google_fonts/google_fonts.dart';
class AppThemes { class AppThemes {
// Private constructor to prevent instantiation static ThemeData getLightTheme(ThemeType type) {
AppThemes._(); final Color seedColor = _getSeedColor(type);
final colorScheme = ColorScheme.fromSeed(
// Light theme colors seedColor: seedColor,
static const Color _primaryColorLight = Color(0xFF1E88E5); // Blue 600
static const Color _secondaryColorLight = Color(0xFF26A69A); // Teal 400
static const Color _errorColorLight = Color(0xFFE53935); // Red 600
static const Color _surfaceColorLight = Colors.white;
// Dark theme colors
static const Color _primaryColorDark = Color(0xFF42A5F5); // Blue 400
static const Color _secondaryColorDark = Color(0xFF4DB6AC); // Teal 300
static const Color _errorColorDark = Color(0xFFEF5350); // Red 400
static const Color _surfaceColorDark = Color(0xFF1E1E1E);
// Text themes
static const TextTheme _textThemeLight = TextTheme(
displayLarge: TextStyle(
fontSize: 96,
fontWeight: FontWeight.w300,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
displayMedium: TextStyle(
fontSize: 60,
fontWeight: FontWeight.w300,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
displaySmall: TextStyle(
fontSize: 48,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
headlineMedium: TextStyle(
fontSize: 34,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
headlineSmall: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
titleLarge: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
bodyLarge: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
bodyMedium: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
bodySmall: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: Color(0xFF757575),
fontFamily: 'Rubik',
),
labelLarge: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Color(0xFF212121),
fontFamily: 'Rubik',
),
);
static final TextTheme _textThemeDark = _textThemeLight.copyWith(
displayLarge: _textThemeLight.displayLarge?.copyWith(color: Colors.white),
displayMedium: _textThemeLight.displayMedium?.copyWith(color: Colors.white),
displaySmall: _textThemeLight.displaySmall?.copyWith(color: Colors.white),
headlineMedium:
_textThemeLight.headlineMedium?.copyWith(color: Colors.white),
headlineSmall: _textThemeLight.headlineSmall?.copyWith(color: Colors.white),
titleLarge: _textThemeLight.titleLarge?.copyWith(color: Colors.white),
bodyLarge: _textThemeLight.bodyLarge?.copyWith(color: Colors.white),
bodyMedium: _textThemeLight.bodyMedium?.copyWith(color: Colors.white),
bodySmall: _textThemeLight.bodySmall?.copyWith(color: Colors.white70),
labelLarge: _textThemeLight.labelLarge?.copyWith(color: Colors.white),
);
// Light theme
static final ThemeData lightTheme = ThemeData(
useMaterial3: true,
fontFamily: 'Rubik',
colorScheme: const ColorScheme.light(
primary: _primaryColorLight,
secondary: _secondaryColorLight,
error: _errorColorLight,
surface: _surfaceColorLight,
onPrimary: Colors.white,
onSecondary: Colors.white,
onSurface: Colors.black87,
onError: Colors.white,
brightness: Brightness.light, brightness: Brightness.light,
), );
textTheme: _textThemeLight, return ThemeData.from(
appBarTheme: const AppBarTheme( colorScheme: colorScheme,
elevation: 0, useMaterial3: true,
backgroundColor: _surfaceColorLight, textTheme: GoogleFonts.rubikTextTheme(),
foregroundColor: Color(0xFF212121), );
centerTitle: true, }
),
cardTheme: CardTheme(
//Earlier CardThemeData
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: _primaryColorLight,
elevation: 2,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
foregroundColor: _primaryColorLight,
side: const BorderSide(color: _primaryColorLight),
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: _primaryColorLight,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Colors.grey[100],
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide(color: Colors.grey[300]!),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: _primaryColorLight, width: 2),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: _errorColorLight, width: 2),
),
labelStyle: const TextStyle(color: Colors.grey),
),
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
selectedItemColor: _primaryColorLight,
unselectedItemColor: Colors.grey,
),
);
// Dark theme static ThemeData getDarkTheme(ThemeType type) {
static final ThemeData darkTheme = ThemeData( final Color seedColor = _getSeedColor(type);
fontFamily: 'Rubik', log(seedColor.toString());
useMaterial3: true, final colorScheme = ColorScheme.fromSeed(
colorScheme: const ColorScheme.dark( seedColor: seedColor,
primary: _primaryColorDark,
secondary: _secondaryColorDark,
error: _errorColorDark,
surface: _surfaceColorDark,
onPrimary: Colors.black,
onSecondary: Colors.black,
onSurface: Colors.white,
onError: Colors.black,
brightness: Brightness.dark, brightness: Brightness.dark,
), );
textTheme: _textThemeDark,
appBarTheme: const AppBarTheme( return ThemeData.from(
elevation: 0, colorScheme: colorScheme,
backgroundColor: _surfaceColorDark, useMaterial3: true,
foregroundColor: Colors.white, textTheme: GoogleFonts.rubikTextTheme(
centerTitle: true, ThemeData(brightness: Brightness.dark).textTheme,
),
cardTheme: CardTheme(
//Earlier was CardThemeData
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
), ),
color: const Color(0xFF2C2C2C), );
), }
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom( static Color _getSeedColor(ThemeType type) {
foregroundColor: Colors.black, switch (type) {
backgroundColor: _primaryColorDark, case ThemeType.green:
elevation: 2, return Colors.green;
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), case ThemeType.orange:
shape: RoundedRectangleBorder( return Colors.orange;
borderRadius: BorderRadius.circular(8), case ThemeType.blue:
), return Colors.blue;
), case ThemeType.violet:
), return Colors.deepPurple;
outlinedButtonTheme: OutlinedButtonThemeData( case ThemeType.yellow:
style: OutlinedButton.styleFrom( return Colors.yellow;
foregroundColor: _primaryColorDark, }
side: const BorderSide(color: _primaryColorDark), }
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: _primaryColorDark,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: const Color(0xFF2A2A2A),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: Color(0xFF3A3A3A)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: _primaryColorDark, width: 2),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: _errorColorDark, width: 2),
),
labelStyle: const TextStyle(color: Colors.grey),
),
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
selectedItemColor: _primaryColorDark,
unselectedItemColor: Colors.grey,
backgroundColor: _surfaceColorDark,
),
);
} }

View File

@@ -1,8 +1,8 @@
class AppException implements Exception { class AppException implements Exception {
final String message; final String message;
AppException(this.message); AppException(this.message);
@override @override
String toString() => message; String toString() => message;
} }
@@ -11,7 +11,7 @@ class NetworkException extends AppException {
NetworkException(super.message); NetworkException(super.message);
} }
class AuthException implements Exception{ class AuthException implements Exception {
final String message; final String message;
AuthException(this.message); AuthException(this.message);
@@ -21,4 +21,4 @@ class AuthException implements Exception{
class UnexpectedException extends AppException { class UnexpectedException extends AppException {
UnexpectedException(super.message); UnexpectedException(super.message);
} }

View File

@@ -0,0 +1,61 @@
class Beneficiary {
final String accountNo;
final String accountType;
final String name;
final String ifscCode;
final String? bankName;
final String? branchName;
final String? tpin;
Beneficiary({
required this.accountNo,
required this.accountType,
required this.name,
required this.ifscCode,
this.bankName,
this.branchName,
this.tpin,
});
factory Beneficiary.fromJson(Map<String, dynamic> json) {
return Beneficiary(
accountNo: json['account_no'] ?? json['accountNo'] ?? '',
accountType: json['account_type'] ?? json['accountType'] ?? '',
name: json['name'] ?? '',
ifscCode: json['ifsc_code'] ?? json['ifscCode'] ?? '',
bankName: json['bank_name'] ?? json['bankName'] ?? '',
branchName: json['branch_name'] ?? json['branchName'] ?? '',
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = {
'accountNo': accountNo,
'accountType': accountType,
'name': name,
'ifscCode': ifscCode,
};
if (bankName != null && bankName!.isNotEmpty) {
json['bankName'] = bankName;
}
if (branchName != null && branchName!.isNotEmpty) {
json['branchName'] = branchName;
}
if (tpin != null && tpin!.isNotEmpty) {
json['tpin'] = tpin;
}
return json;
}
static List<Beneficiary> listFromJson(List<dynamic> jsonList) {
final beneficiaryList = jsonList
.map((beneficiary) => Beneficiary.fromJson(beneficiary))
.toList();
return beneficiaryList;
}
@override
String toString() {
return 'Beneficiary(accountNo: $accountNo, accountType: $accountType, ifscCode: $ifscCode, name: $name)';
}
}

32
lib/data/models/ifsc.dart Normal file
View File

@@ -0,0 +1,32 @@
class Ifsc {
final String ifscCode;
final String bankName;
final String branchName;
Ifsc({
required this.ifscCode,
required this.bankName,
required this.branchName,
});
factory Ifsc.fromJson(Map<String, dynamic> json) {
return Ifsc(
ifscCode: json['ifsc_code'] ?? '',
bankName: json['bank_name'] ?? '',
branchName: json['branch_name'] ?? '',
);
}
Map<String, dynamic> toJson() {
return {
'ifsc_code': ifscCode,
'bank_name': bankName,
'branch_name': branchName,
};
}
@override
String toString() {
return 'IFSC(ifscCode: $ifscCode, bankName: $bankName, branchName: $branchName)';
}
}

View File

@@ -0,0 +1,16 @@
class ImpsResponse {
final String message;
final String utr;
ImpsResponse({
required this.message,
required this.utr,
});
factory ImpsResponse.fromJson(Map<String, dynamic> json) {
return ImpsResponse(
message: json['message'] ?? '',
utr: json['utr'] ?? '',
);
}
}

View File

@@ -0,0 +1,31 @@
class ImpsTransaction {
final String fromAccount;
final String toAccount;
final String amount;
final String ifscCode;
final String? remitterName;
final String beneficiaryName;
final String tpin;
ImpsTransaction({
required this.fromAccount,
required this.toAccount,
required this.amount,
required this.ifscCode,
this.remitterName,
required this.beneficiaryName,
required this.tpin,
});
Map<String, dynamic> toJson() {
return {
'fromAccount': fromAccount,
'toAccount': toAccount,
'amount': amount,
'ifscCode': ifscCode,
'remitterName': remitterName,
'beneficiaryName': beneficiaryName,
'tpin': tpin,
};
}
}

View File

@@ -0,0 +1,16 @@
class NeftResponse {
final String message;
final String utr;
NeftResponse({
required this.message,
required this.utr,
});
factory NeftResponse.fromJson(Map<String, dynamic> json) {
return NeftResponse(
message: json['message'] ?? '',
utr: json['utr'] ?? '',
);
}
}

View File

@@ -0,0 +1,31 @@
class NeftTransaction {
final String fromAccount;
final String toAccount;
final String amount;
final String ifscCode;
final String remitterName;
final String beneficiaryName;
final String tpin;
NeftTransaction({
required this.fromAccount,
required this.toAccount,
required this.amount,
required this.ifscCode,
required this.remitterName,
required this.beneficiaryName,
required this.tpin,
});
Map<String, dynamic> toJson() {
return {
'fromAccount': fromAccount,
'toAccount': toAccount,
'amount': amount,
'ifscCode': ifscCode,
'remitterName': remitterName,
'beneficiaryName': beneficiaryName,
'tpin': tpin,
};
}
}

View File

@@ -6,6 +6,7 @@ class PaymentResponse {
final String? currency; final String? currency;
final String? errorMessage; final String? errorMessage;
final String? errorCode; final String? errorCode;
final String? utr;
PaymentResponse({ PaymentResponse({
required this.isSuccess, required this.isSuccess,
@@ -15,5 +16,6 @@ class PaymentResponse {
this.currency, this.currency,
this.errorMessage, this.errorMessage,
this.errorCode, this.errorCode,
this.utr,
}); });
} }

View File

@@ -0,0 +1,16 @@
class RtgsResponse {
final String message;
final String utr;
RtgsResponse({
required this.message,
required this.utr,
});
factory RtgsResponse.fromJson(Map<String, dynamic> json) {
return RtgsResponse(
message: json['message'] ?? '',
utr: json['utr'] ?? '',
);
}
}

View File

@@ -0,0 +1,31 @@
class RtgsTransaction {
final String fromAccount;
final String toAccount;
final String amount;
final String ifscCode;
final String remitterName;
final String beneficiaryName;
final String tpin;
RtgsTransaction({
required this.fromAccount,
required this.toAccount,
required this.amount,
required this.ifscCode,
required this.remitterName,
required this.beneficiaryName,
required this.tpin,
});
Map<String, dynamic> toJson() {
return {
'fromAccount': fromAccount,
'toAccount': toAccount,
'amount': amount,
'ifscCode': ifscCode,
'remitterName': remitterName,
'beneficiaryName': beneficiaryName,
'tpin': tpin,
};
}
}

View File

@@ -4,8 +4,18 @@ class Transaction {
final String? date; final String? date;
final String? amount; final String? amount;
final String? type; final String? type;
final String? balance;
final String? balanceType;
Transaction(
{this.id,
this.name,
this.date,
this.amount,
this.type,
this.balance,
this.balanceType});
Transaction({this.id, this.name, this.date, this.amount, this.type});
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {
'id': id, 'id': id,
@@ -13,16 +23,19 @@ class Transaction {
'date': date, 'date': date,
'amount': amount, 'amount': amount,
'type': type, 'type': type,
'balance': balance,
'balanceType': balanceType
}; };
} }
factory Transaction.fromJson(Map<String, dynamic> json) { factory Transaction.fromJson(Map<String, dynamic> json) {
return Transaction( return Transaction(
id: json['id'] as String?, id: json['id'] as String?,
name: json['name'] as String?, name: json['name'] as String?,
date: json['date'] as String?, date: json['date'] as String?,
amount: json['amount'] as String?, amount: json['amount'] as String?,
type: json['type'] as String?, type: json['type'] as String?,
); balance: json['balance'] as String?,
balanceType: json['balanceType'] as String?);
} }
} }

View File

@@ -32,7 +32,7 @@ class TransferResponse {
TransferResponse({ TransferResponse({
required this.status, required this.status,
required this.message, required this.message,
required this.error, required this.error,
}); });
factory TransferResponse.fromJson(Map<String, dynamic> json) { factory TransferResponse.fromJson(Map<String, dynamic> json) {
@@ -42,4 +42,4 @@ class TransferResponse {
error: json['error'] as String?, error: json['error'] as String?,
); );
} }
} }

View File

@@ -10,7 +10,7 @@ class AuthRepository {
final AuthService _authService; final AuthService _authService;
final UserService _userService; final UserService _userService;
final SecureStorage _secureStorage; final SecureStorage _secureStorage;
static const _accessTokenKey = 'access_token'; static const _accessTokenKey = 'access_token';
static const _tokenExpiryKey = 'token_expiry'; static const _tokenExpiryKey = 'token_expiry';
@@ -18,35 +18,43 @@ class AuthRepository {
Future<List<User>> login(String customerNo, String password) async { Future<List<User>> login(String customerNo, String password) async {
// Create credentials and call service // Create credentials and call service
final credentials = AuthCredentials(customerNo: customerNo, password: password); final credentials =
AuthCredentials(customerNo: customerNo, password: password);
final authToken = await _authService.login(credentials); final authToken = await _authService.login(credentials);
// Save token securely // Save token securely
await _saveAuthToken(authToken); await _saveAuthToken(authToken);
// Get and save user profile // Get and save user profile
final users = await _userService.getUserDetails(); final users = await _userService.getUserDetails();
return users; return users;
} }
Future<bool> isLoggedIn() async { Future<bool> isLoggedIn() async {
final token = await _getAuthToken(); final token = await _getAuthToken();
return token != null && !token.isExpired; return token != null && !token.isExpired;
} }
Future<String?> getAccessToken() async { Future<String?> getAccessToken() async {
final token = await _getAuthToken(); final token = await _getAuthToken();
if (token == null) return null; if (token == null) return null;
return token.accessToken; return token.accessToken;
} }
// Private helper methods // Private helper methods
Future<void> _saveAuthToken(AuthToken token) async { Future<void> _saveAuthToken(AuthToken token) async {
await _secureStorage.write(_accessTokenKey, token.accessToken); await _secureStorage.write(_accessTokenKey, token.accessToken);
await _secureStorage.write(_tokenExpiryKey, token.expiresAt.toIso8601String()); await _secureStorage.write(
_tokenExpiryKey, token.expiresAt.toIso8601String());
} }
Future<void> clearAuthTokens() async {
await _secureStorage.deleteAll();
}
Future<AuthToken?> _getAuthToken() async { Future<AuthToken?> _getAuthToken() async {
final accessToken = await _secureStorage.read(_accessTokenKey); final accessToken = await _secureStorage.read(_accessTokenKey);
final expiryString = await _secureStorage.read(_tokenExpiryKey); final expiryString = await _secureStorage.read(_tokenExpiryKey);
@@ -59,4 +67,4 @@ class AuthRepository {
} }
return null; return null;
} }
} }

View File

@@ -1,8 +1,12 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:kmobile/data/models/transaction.dart'; import 'package:kmobile/data/models/transaction.dart';
abstract class TransactionRepository { abstract class TransactionRepository {
Future<List<Transaction>> fetchTransactions(String accountNo); Future<List<Transaction>> fetchTransactions(String accountNo,
{DateTime? fromDate, DateTime? toDate});
} }
class TransactionRepositoryImpl implements TransactionRepository { class TransactionRepositoryImpl implements TransactionRepository {
@@ -10,9 +14,21 @@ class TransactionRepositoryImpl implements TransactionRepository {
TransactionRepositoryImpl(this._dio); TransactionRepositoryImpl(this._dio);
@override @override
Future<List<Transaction>> fetchTransactions(String accountNo) async { Future<List<Transaction>> fetchTransactions(String accountNo,
{DateTime? fromDate, DateTime? toDate}) async {
final queryParameters = <String, String>{};
final resp = await _dio.get('/api/transactions/account/$accountNo'); if (fromDate != null) {
queryParameters['fromDate'] = DateFormat('ddMMyyyy').format(fromDate);
}
if (toDate != null) {
queryParameters['toDate'] = DateFormat('ddMMyyyy').format(toDate);
}
final resp = await _dio.get(
'/api/transactions/account/$accountNo',
queryParameters: queryParameters.isNotEmpty ? queryParameters : null,
);
if (resp.statusCode != 200) { if (resp.statusCode != 200) {
throw Exception( throw Exception(
@@ -25,4 +41,4 @@ class TransactionRepositoryImpl implements TransactionRepository {
.map((e) => Transaction.fromJson(e as Map<String, dynamic>)) .map((e) => Transaction.fromJson(e as Map<String, dynamic>))
.toList(); .toList();
} }
} }

View File

@@ -1,7 +1,6 @@
import 'package:kmobile/data/models/transfer.dart'; import 'package:kmobile/data/models/transfer.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
abstract class TransferRepository { abstract class TransferRepository {
Future<TransferResponse> transfer(Transfer transfer); Future<TransferResponse> transfer(Transfer transfer);
} }
@@ -25,4 +24,4 @@ class TransferRepositoryImpl implements TransferRepository {
return TransferResponse.fromJson(resp.data as Map<String, dynamic>); return TransferResponse.fromJson(resp.data as Map<String, dynamic>);
} }
} }

View File

@@ -1,10 +1,17 @@
import 'package:kmobile/api/services/rtgs_service.dart';
import 'package:kmobile/api/services/neft_service.dart';
import 'package:kmobile/api/services/imps_service.dart';
import 'package:get_it/get_it.dart'; import 'package:get_it/get_it.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/api/services/payment_service.dart'; import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/api/services/user_service.dart'; import 'package:kmobile/api/services/user_service.dart';
import 'package:kmobile/data/repositories/transaction_repository.dart'; import 'package:kmobile/data/repositories/transaction_repository.dart';
import 'package:kmobile/features/auth/controllers/theme_cubit.dart';
import 'package:kmobile/features/auth/controllers/theme_mode_cubit.dart';
import '../api/services/auth_service.dart'; import '../api/services/auth_service.dart';
import '../api/interceptors/auth_interceptor.dart'; import '../api/interceptors/auth_interceptor.dart';
import '../api/services/change_password_service.dart';
import '../data/repositories/auth_repository.dart'; import '../data/repositories/auth_repository.dart';
import '../features/auth/controllers/auth_cubit.dart'; import '../features/auth/controllers/auth_cubit.dart';
import '../security/secure_storage.dart'; import '../security/secure_storage.dart';
@@ -12,6 +19,11 @@ import '../security/secure_storage.dart';
final getIt = GetIt.instance; final getIt = GetIt.instance;
Future<void> setupDependencies() async { Future<void> setupDependencies() async {
//getIt.registerLazySingleton<ThemeController>(() => ThemeController());
//getIt.registerLazySingleton<ThemeModeController>(() => ThemeModeController());
getIt.registerSingleton<ThemeCubit>(ThemeCubit());
getIt.registerSingleton<ThemeModeCubit>(ThemeModeCubit());
// Register Dio client // Register Dio client
getIt.registerSingleton<Dio>(_createDioClient()); getIt.registerSingleton<Dio>(_createDioClient());
@@ -33,6 +45,11 @@ Future<void> setupDependencies() async {
TransactionRepositoryImpl(getIt<Dio>())); TransactionRepositoryImpl(getIt<Dio>()));
getIt.registerSingleton<PaymentService>(PaymentService(getIt<Dio>())); getIt.registerSingleton<PaymentService>(PaymentService(getIt<Dio>()));
getIt.registerSingleton<BeneficiaryService>(BeneficiaryService(getIt<Dio>()));
getIt.registerSingleton<NeftService>(NeftService(getIt<Dio>()));
getIt.registerSingleton<RtgsService>(RtgsService(getIt<Dio>()));
getIt.registerSingleton<ImpsService>(ImpsService(getIt<Dio>()));
getIt.registerLazySingleton<ChangePasswordService>(() => ChangePasswordService(getIt<Dio>()),);
// Add auth interceptor after repository is available // Add auth interceptor after repository is available
getIt<Dio>().interceptors.add( getIt<Dio>().interceptors.add(
@@ -49,8 +66,10 @@ Dio _createDioClient() {
BaseOptions( BaseOptions(
baseUrl: baseUrl:
'http://lb-test-mobile-banking-app-192209417.ap-south-1.elb.amazonaws.com:8080', 'http://lb-test-mobile-banking-app-192209417.ap-south-1.elb.amazonaws.com:8080',
//'http://localhost:8081',
// 'http://localhost:8082',
connectTimeout: const Duration(seconds: 5), connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 3), receiveTimeout: const Duration(seconds: 10),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Accept': 'application/json', 'Accept': 'application/json',

View File

@@ -4,7 +4,7 @@ class Account {
final String accountType; final String accountType;
final double balance; final double balance;
final String currency; final String currency;
Account({ Account({
required this.id, required this.id,
required this.accountNumber, required this.accountNumber,
@@ -12,4 +12,4 @@ class Account {
required this.balance, required this.balance,
required this.currency, required this.currency,
}); });
} }

View File

@@ -1,80 +1,91 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:kmobile/data/models/user.dart'; import 'package:kmobile/data/models/user.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class AccountInfoScreen extends StatefulWidget { class AccountInfoScreen extends StatefulWidget {
final User user; final List<User> users;
final int selectedIndex;
const AccountInfoScreen({super.key, required this.user}); const AccountInfoScreen({
super.key,
required this.users,
required this.selectedIndex,
});
@override @override
State<AccountInfoScreen> createState() => _AccountInfoScreen(); State<AccountInfoScreen> createState() => _AccountInfoScreen();
} }
class _AccountInfoScreen extends State<AccountInfoScreen> { class _AccountInfoScreen extends State<AccountInfoScreen> {
late User selectedUser;
@override
void initState() {
super.initState();
selectedUser = widget.users[widget.selectedIndex];
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = widget.user; final users = widget.users;
int selectedIndex = widget.selectedIndex;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(AppLocalizations.of(context)
icon: const Icon(Symbols.arrow_back_ios_new), .accountInfo
onPressed: () { .replaceFirst(RegExp('\n'), '')),
Navigator.pop(context);
},
),
title: Text(
AppLocalizations.of(context).accountInfo,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
),
centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: ListView( body: ListView(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
children: [ children: [
InfoRow( Text(
title: AppLocalizations.of(context).accountNumber, AppLocalizations.of(context).accountNumber,
value: user.accountNo ?? 'N/A'), style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 14),
// InfoRow(title: 'Nominee Customer No', value: user.nomineeCustomerNo), ),
// InfoRow(title: 'SMS Service', value: user.smsService),
// InfoRow(title: 'Missed Call Service', value: user.missedCallService),
InfoRow(
title: AppLocalizations.of(context).customerNumber,
value: user.cifNumber ?? 'N/A'),
InfoRow(
title: AppLocalizations.of(context).productName,
value: user.productType ?? 'N/A'),
// InfoRow(title: 'Account Opening Date', value: user.accountOpeningDate ?? 'N/A'),
InfoRow(
title: AppLocalizations.of(context).accountStatus, value: 'OPEN'),
InfoRow(
title: AppLocalizations.of(context).availableBalance,
value: user.availableBalance ?? 'N/A'),
InfoRow(
title: AppLocalizations.of(context).currentBalance,
value: user.currentBalance ?? 'N/A'),
user.approvedAmount != null DropdownButton<User>(
value: selectedUser,
onChanged: (User? newUser) {
if (newUser != null) {
setState(() {
selectedUser = newUser;
});
}
},
items: widget.users.map((user) {
return DropdownMenuItem<User>(
value: user,
child: Text(user.accountNo.toString()),
);
}).toList(),
),
InfoRow(
title: AppLocalizations.of(context).customerNumber,
value: selectedUser.cifNumber ?? 'N/A',
),
InfoRow(
title: AppLocalizations.of(context).productName,
value: selectedUser.productType ?? 'N/A',
),
// InfoRow(title: 'Account Opening Date', value: users[selectedIndex].accountOpeningDate ?? 'N/A'),
InfoRow(
title: AppLocalizations.of(context).accountStatus,
value: 'OPEN',
),
InfoRow(
title: AppLocalizations.of(context).availableBalance,
value: selectedUser.availableBalance ?? 'N/A',
),
InfoRow(
title: AppLocalizations.of(context).currentBalance,
value: selectedUser.currentBalance ?? 'N/A',
),
users[selectedIndex].approvedAmount != null
? InfoRow( ? InfoRow(
title: AppLocalizations.of(context).approvedAmount, title: AppLocalizations.of(context).approvedAmount,
value: user.approvedAmount ?? 'N/A') value: selectedUser.approvedAmount ?? 'N/A',
)
: const SizedBox.shrink(), : const SizedBox.shrink(),
], ],
), ),
@@ -90,6 +101,7 @@ class InfoRow extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container( return Container(
width: double.infinity, width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8), margin: const EdgeInsets.symmetric(vertical: 8),
@@ -98,19 +110,16 @@ class InfoRow extends StatelessWidget {
children: [ children: [
Text( Text(
title, title,
style: const TextStyle( style: TextStyle(
fontSize: 15, fontSize: 15,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
color: Colors.black87, color: theme.colorScheme.onSurfaceVariant,
), ),
), ),
const SizedBox(height: 3), const SizedBox(height: 3),
Text( Text(
value, value,
style: const TextStyle( style: TextStyle(fontSize: 16, color: theme.colorScheme.onSurface),
fontSize: 16,
color: Colors.black,
),
), ),
], ],
), ),

View File

@@ -1,17 +1,26 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter/services.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:shimmer/shimmer.dart'; import 'package:shimmer/shimmer.dart';
import 'package:kmobile/data/models/transaction.dart'; import 'package:kmobile/data/models/transaction.dart';
import 'package:kmobile/data/repositories/transaction_repository.dart'; import 'package:kmobile/data/repositories/transaction_repository.dart';
import 'package:kmobile/di/injection.dart'; import 'package:kmobile/di/injection.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'transaction_details_screen.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';
class AccountStatementScreen extends StatefulWidget { class AccountStatementScreen extends StatefulWidget {
final String accountNo; final String accountNo;
final String balance;
final String accountType;
const AccountStatementScreen({ const AccountStatementScreen({
super.key, super.key,
required this.accountNo, required this.accountNo,
required this.balance,
required this.accountType,
}); });
@override @override
@@ -25,6 +34,7 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
List<Transaction> _transactions = []; List<Transaction> _transactions = [];
final _minAmountController = TextEditingController(); final _minAmountController = TextEditingController();
final _maxAmountController = TextEditingController(); final _maxAmountController = TextEditingController();
//Future<Map<String, dynamic>?>? accountStatementsFuture;
@override @override
void initState() { void initState() {
@@ -39,14 +49,20 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
}); });
try { try {
final repo = getIt<TransactionRepository>(); final repo = getIt<TransactionRepository>();
final txs = await repo.fetchTransactions(widget.accountNo); final txs = await repo.fetchTransactions(
widget.accountNo,
fromDate: fromDate,
toDate: toDate,
);
setState(() => _transactions = txs); setState(() => _transactions = txs);
} catch (e) { } catch (e) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
'${AppLocalizations.of(context).failedToLoadTransactions} $e')), '${AppLocalizations.of(context).failedToLoadTransactions} $e',
),
),
); );
} finally { } finally {
setState(() => _txLoading = false); setState(() => _txLoading = false);
@@ -73,7 +89,8 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
if (fromDate == null) { if (fromDate == null) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text(AppLocalizations.of(context).pleaseSelectDateFirst)), content: Text(AppLocalizations.of(context).pleaseSelectDateFirst),
),
); );
return; return;
} }
@@ -109,38 +126,46 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () => Navigator.pop(context),
),
title: Text( title: Text(
AppLocalizations.of(context).accountStatement, AppLocalizations.of(context).accountStatement,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(12.0), padding: const EdgeInsets.all(12.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(AppLocalizations.of(context).filters, Row(
style: TextStyle(fontSize: 17)), children: [
Text(
"${AppLocalizations.of(context).accountNumber}: ",
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
Text(widget.accountNo, style: const TextStyle(fontSize: 17)),
],
),
const SizedBox(height: 15),
Row(
children: [
Text(
"${AppLocalizations.of(context).availableBalance}: ",
style: const TextStyle(
fontSize: 17,
),
),
Text('${widget.balance}',
style: const TextStyle(fontSize: 17)),
],
),
const SizedBox(height: 15),
Text(
AppLocalizations.of(context).filters,
style: const TextStyle(fontSize: 17),
),
const SizedBox(height: 15), const SizedBox(height: 15),
Row( Row(
children: [ children: [
@@ -148,7 +173,9 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
child: GestureDetector( child: GestureDetector(
onTap: () => _selectFromDate(context), onTap: () => _selectFromDate(context),
child: buildDateBox( child: buildDateBox(
AppLocalizations.of(context).fromDate, fromDate), AppLocalizations.of(context).fromDate,
fromDate,
),
), ),
), ),
const SizedBox(width: 10), const SizedBox(width: 10),
@@ -156,62 +183,37 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
child: GestureDetector( child: GestureDetector(
onTap: () => _selectToDate(context), onTap: () => _selectToDate(context),
child: buildDateBox( child: buildDateBox(
AppLocalizations.of(context).toDate, toDate), AppLocalizations.of(context).toDate,
toDate,
),
), ),
), ),
], ],
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
Row( SizedBox(
children: [ width: double.infinity,
Expanded( child: ElevatedButton(
child: TextFormField( onPressed: _loadTransactions,
controller: _minAmountController, style: ElevatedButton.styleFrom(
decoration: InputDecoration( backgroundColor:
labelText: AppLocalizations.of(context).minAmount, Theme.of(context).colorScheme.primaryContainer,
border: OutlineInputBorder(), padding: const EdgeInsets.symmetric(vertical: 16),
isDense: true, ),
filled: true, child: Text(
fillColor: Colors.white, AppLocalizations.of(context).search,
), style: TextStyle(
keyboardType: TextInputType.number, color: Theme.of(context).colorScheme.onPrimaryContainer,
textInputAction: TextInputAction.next, fontSize: 16,
), ),
), ),
const SizedBox(width: 8), ),
Expanded(
child: TextFormField(
controller: _maxAmountController,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).maxAmount,
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
),
),
const SizedBox(width: 8),
SizedBox(
width: 70,
child: ElevatedButton(
onPressed: _loadTransactions,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColor,
),
child: const Icon(
Symbols.arrow_forward,
color: Colors.white,
size: 30,
),
),
),
],
), ),
const SizedBox(height: 35), const SizedBox(height: 15),
if (!_txLoading && _transactions.isNotEmpty) if (!_txLoading &&
_transactions.isNotEmpty &&
fromDate == null &&
toDate == null)
Padding( Padding(
padding: const EdgeInsets.only(bottom: 12.0), padding: const EdgeInsets.only(bottom: 12.0),
child: Text( child: Text(
@@ -219,7 +221,7 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
color: Colors.grey[700], color: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
), ),
), ),
@@ -231,81 +233,279 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
leading: Shimmer.fromColors( leading: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: const CircleAvatar( child: CircleAvatar(
radius: 12, backgroundColor: Colors.white), radius: 12,
backgroundColor:
Theme.of(context).scaffoldBackgroundColor,
),
), ),
title: Shimmer.fromColors( title: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: Container( child: Container(
height: 10, width: 100, color: Colors.white), height: 10,
width: 100,
color: Theme.of(context).scaffoldBackgroundColor,
),
), ),
subtitle: Shimmer.fromColors( subtitle: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: Container( child: Container(
height: 8, width: 60, color: Colors.white), height: 8,
width: 60,
color: Theme.of(context).scaffoldBackgroundColor,
),
), ),
), ),
) )
: _transactions.isEmpty : _transactions.isEmpty
? Center( ? Center(
child: Text( child: Text(
AppLocalizations.of(context).noTransactions, AppLocalizations.of(context).noTransactions,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: Colors.grey[600], color: Theme.of(context).colorScheme.onSurface,
), )),
),
) )
: ListView.builder( : ListView.separated(
itemCount: _transactions.length, itemCount: _transactions.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final txn = _transactions[index]; final tx = _transactions[index];
final isCredit = txn.type == 'CR'; return ListTile(
return Column( leading: Icon(
crossAxisAlignment: CrossAxisAlignment.start, tx.type == 'CR'
children: [ ? Symbols.call_received
Text(txn.date ?? '', : Symbols.call_made,
style: const TextStyle(color: Colors.grey)), color: tx.type == 'CR'
const SizedBox(height: 4), ? Colors.green
Row( : Theme.of(context).colorScheme.error,
mainAxisAlignment: ),
MainAxisAlignment.spaceBetween, title: Text(
children: [ tx.date ?? '',
Expanded( style: const TextStyle(fontSize: 15),
child: Text(txn.name ?? '', ),
style: const TextStyle(fontSize: 16)), subtitle: Text(
), tx.name != null
Text( ? (tx.name!.length > 18
"${isCredit ? '+' : '-'}${txn.amount}", ? tx.name!.substring(0, 22)
style: TextStyle( : tx.name!)
color: isCredit : '',
? Colors.green style: const TextStyle(fontSize: 12),
: Colors.red, ),
// fontWeight: FontWeight.bold, trailing: Column(
fontSize: 16, crossAxisAlignment: CrossAxisAlignment.end,
), mainAxisAlignment: MainAxisAlignment.center,
), children: [
], Text(
), "${tx.amount}",
const SizedBox(height: 25), style: const TextStyle(fontSize: 17),
], ),
Text(
"Bal: ₹${tx.balance}",
style: const TextStyle(fontSize: 12), // Style matches tx.name
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TransactionDetailsScreen(
transaction: tx),
),
);
},
); );
}, },
separatorBuilder: (context, index) {
return const Divider();
},
), ),
), ),
], ],
), ),
), ),
floatingActionButton: FloatingActionButton(
onPressed: () {
_exportToPdf();
},
child: const Icon(Icons.download),
),
); );
} }
Future<void> _exportToPdf() async {
// Step 1: Check if there are any transactions to export.
if (_transactions.isEmpty) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No transactions to export.'),
),
);
}
return;
}
var logo = await rootBundle.load('assets/images/logo.png');
var rubik = await rootBundle.load("assets/fonts/Rubik-Regular.ttf");
final pdf = pw.Document();
pdf.addPage(pw.MultiPage(
margin: const pw.EdgeInsets.all(20),
build: (pw.Context context) {
return [
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.start,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
pw.Image(pw.MemoryImage(logo.buffer.asUint8List()),
width: 50, height: 50),
pw.SizedBox(width: 20),
pw.Text('Account Statement - KCCB',
style: pw.TextStyle(
fontSize: 24, fontWeight: pw.FontWeight.bold)),
]),
pw.SizedBox(height: 20),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Text('Account Number: ${widget.accountNo}',
style:
pw.TextStyle(font: pw.Font.ttf(rubik), fontSize: 15)),
pw.Text('Account Type: ${widget.accountType}',
style: pw.TextStyle(
fontSize: 15,
font: pw.Font.ttf(rubik),
)),
]),
pw.SizedBox(height: 20),
pw.Table(border: pw.TableBorder.all(), columnWidths: {
0: const pw.FractionColumnWidth(0.2),
1: const pw.FractionColumnWidth(0.45),
2: const pw.FractionColumnWidth(0.15),
3: const pw.FractionColumnWidth(0.20),
}, children: [
pw.TableRow(
children: [
pw.Padding(
padding: const pw.EdgeInsets.all(4),
child: pw.Text('Date')),
pw.Padding(
padding: const pw.EdgeInsets.all(4),
child: pw.Text('Description', softWrap: true)),
pw.Padding(
padding: const pw.EdgeInsets.all(4),
child: pw.Text('Amount')),
pw.Padding(
padding: const pw.EdgeInsets.all(4),
child: pw.Text('Balance')),
],
),
..._transactions.map<pw.TableRow>((tx) {
return pw.TableRow(children: [
pw.Padding(
padding: const pw.EdgeInsets.all(10),
child: pw.Text(tx.date ?? '',
style: pw.TextStyle(
fontSize: 12,
font: pw.Font.ttf(rubik),
))),
pw.Padding(
padding: const pw.EdgeInsets.all(10),
child: pw.Text(tx.name ?? '',
style: pw.TextStyle(
fontSize: 12, font: pw.Font.ttf(rubik)))),
pw.Padding(
padding: const pw.EdgeInsets.all(10),
child: pw.Text("${tx.amount} ${tx.type}",
style: pw.TextStyle(
fontSize: 12,
font: pw.Font.ttf(rubik),
))),
pw.Padding(
padding: const pw.EdgeInsets.all(10),
child: pw.Text("${tx.balance} ${tx.balanceType}",
style: pw.TextStyle(
fontSize: 12,
font: pw.Font.ttf(rubik),
))),
]);
}),
])
];
},
footer: (pw.Context context) {
return pw.Container(
alignment: pw.Alignment.centerRight,
margin: const pw.EdgeInsets.only(top: 10),
child: pw.Text(
'Kangra Central Co-Operative Bank Pvt Ltd. ©. All rights reserved.',
style: pw.TextStyle(
font: pw.Font.ttf(rubik),
fontSize: 8,
),
),
);
}));
//Logic For all platforms
try {
final Uint8List pdfBytes = await pdf.save();
final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
final String fileName = 'account_statement_$timestamp.pdf';
// For Android
if (Platform.isAndroid) {
final androidInfo = await DeviceInfoPlugin().androidInfo;
if (androidInfo.version.sdkInt < 29) {
final status = await Permission.storage.status;
if (status.isDenied) {
final result = await Permission.storage.request();
if (result.isDenied) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Storage permission is required to save PDF'),
),
);
}
return;
}
}
}
final directory = Directory('/storage/emulated/0/Download');
final file = File('${directory.path}/$fileName');
await file.writeAsBytes(pdfBytes);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('PDF saved to: ${file.path}'),
),
);
}
}
// Add for IOS
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error saving PDF: $e'),
),
);
}
}
}
Widget buildDateBox(String label, DateTime? date) { Widget buildDateBox(String label, DateTime? date) {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
decoration: BoxDecoration( decoration: BoxDecoration(
border: Border.all(color: Colors.grey), border:
Border.all(color: Theme.of(context).colorScheme.onSurfaceVariant),
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
), ),
child: Row( child: Row(
@@ -315,7 +515,9 @@ class _AccountStatementScreen extends State<AccountStatementScreen> {
date != null ? _formatDate(date) : label, date != null ? _formatDate(date) : label,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: date != null ? Colors.black : Colors.grey, color: date != null
? Theme.of(context).colorScheme.onSurface
: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
), ),
const Icon(Icons.arrow_drop_down), const Icon(Icons.arrow_drop_down),

View File

@@ -0,0 +1,112 @@
import 'package:flutter/material.dart';
import 'package:kmobile/l10n/app_localizations.dart';
import 'package:material_symbols_icons/symbols.dart';
class TransactionDetailsScreen extends StatelessWidget {
final dynamic transaction;
const TransactionDetailsScreen({super.key, required this.transaction});
@override
Widget build(BuildContext context) {
final bool isCredit = transaction.type?.toUpperCase() == 'CR';
return Scaffold(
appBar:
AppBar(title: Text(AppLocalizations.of(context).transactionDetails)),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Expanded(
flex: 3,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Amount + icon + Share Button
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"${transaction.amount}",
style: const TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 8),
Icon(
isCredit ? Symbols.call_received : Symbols.call_made,
color: isCredit ? Colors.green : Colors.red,
size: 28,
),
],
),
const SizedBox(height: 8),
// Date centered
Text(
transaction.date ?? "",
style: const TextStyle(
fontSize: 16,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
],
),
),
),
const Divider(),
Expanded(
flex: 5,
child: ListView(
children: [
_buildDetailRow(AppLocalizations.of(context).transactionType,
transaction.type ?? ""),
_buildDetailRow(AppLocalizations.of(context).transferType,
transaction.name.split("/").first ?? ""),
// if (transaction.name.length > 12) ...[
// _buildDetailRow(AppLocalizations.of(context).utrNo,
// transaction.name.split("= ")[1].split(" ")[0] ?? ""),
// _buildDetailRow(
// AppLocalizations.of(context).beneficiaryAccountNo,
// transaction.name.split("A/C ").last ?? "")
// ]
_buildDetailRow(AppLocalizations.of(context).details,
transaction.name),
],
),
),
],
),
),
);
}
Widget _buildDetailRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"$label: ",
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
const SizedBox(height: 30),
Expanded(
child: Text(
value,
style: const TextStyle(fontSize: 16),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,27 @@
import 'dart:developer';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/config/theme_type.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'theme_state.dart';
class ThemeCubit extends Cubit<ThemeState> {
ThemeCubit() : super(const ThemeState(themeType: ThemeType.violet)) {
loadTheme();
}
Future<void> loadTheme() async {
final prefs = await SharedPreferences.getInstance();
final themeIndex = prefs.getInt('theme_type') ?? 0;
final type = ThemeType.values[themeIndex];
emit(ThemeState(themeType: type));
}
Future<void> changeTheme(ThemeType type) async {
log("Attempting to change theme...");
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('theme_type', type.index);
emit(ThemeState(themeType: type));
}
}

View File

@@ -0,0 +1,23 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'theme_mode_state.dart';
class ThemeModeCubit extends Cubit<ThemeModeState> {
ThemeModeCubit() : super(const ThemeModeState(mode: ThemeMode.system)) {
loadThemeMode();
}
Future<void> loadThemeMode() async {
final prefs = await SharedPreferences.getInstance();
final modeIndex = prefs.getInt('theme_mode') ?? 0; // default system
final mode = ThemeMode.values[modeIndex];
emit(ThemeModeState(mode: mode));
}
Future<void> changeThemeMode(ThemeMode mode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('theme_mode', mode.index);
emit(ThemeModeState(mode: mode));
}
}

View File

@@ -0,0 +1,11 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
class ThemeModeState extends Equatable {
final ThemeMode mode;
const ThemeModeState({required this.mode});
@override
List<Object?> get props => [mode];
}

View File

@@ -0,0 +1,41 @@
/*import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/config/theme_type.dart';
import 'package:kmobile/config/themes.dart';
class ThemeState extends Equatable {
final ThemeType themeType;
const ThemeState({required this.themeType});
ThemeData getThemeData() {
return AppThemes.getLightTheme(themeType);
}
@override
List<Object?> get props => [themeType];
}*/
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/config/theme_type.dart';
import 'package:kmobile/config/themes.dart';
class ThemeState extends Equatable {
final ThemeType themeType;
const ThemeState({required this.themeType});
ThemeData getLightThemeData() {
return AppThemes.getLightTheme(themeType);
}
ThemeData getDarkThemeData() {
return AppThemes.getDarkTheme(themeType);
}
@override
List<Object?> get props => [themeType];
}

View File

@@ -6,12 +6,12 @@ import 'package:equatable/equatable.dart';
class AuthToken extends Equatable { class AuthToken extends Equatable {
final String accessToken; final String accessToken;
final DateTime expiresAt; final DateTime expiresAt;
const AuthToken({ const AuthToken({
required this.accessToken, required this.accessToken,
required this.expiresAt, required this.expiresAt,
}); });
factory AuthToken.fromJson(Map<String, dynamic> json) { factory AuthToken.fromJson(Map<String, dynamic> json) {
return AuthToken( return AuthToken(
accessToken: json['token'], accessToken: json['token'],
@@ -29,7 +29,8 @@ class AuthToken extends Equatable {
// Pad the payload if necessary // Pad the payload if necessary
String normalized = base64Url.normalize(payload); String normalized = base64Url.normalize(payload);
final payloadMap = json.decode(utf8.decode(base64Url.decode(normalized))); final payloadMap = json.decode(utf8.decode(base64Url.decode(normalized)));
if (payloadMap is! Map<String, dynamic> || !payloadMap.containsKey('exp')) { if (payloadMap is! Map<String, dynamic> ||
!payloadMap.containsKey('exp')) {
throw Exception('Invalid payload'); throw Exception('Invalid payload');
} }
final exp = payloadMap['exp']; final exp = payloadMap['exp'];
@@ -40,9 +41,9 @@ class AuthToken extends Equatable {
return DateTime.now().add(const Duration(hours: 1)); return DateTime.now().add(const Duration(hours: 1));
} }
} }
bool get isExpired => DateTime.now().isAfter(expiresAt); bool get isExpired => DateTime.now().isAfter(expiresAt);
@override @override
List<Object> get props => [accessToken, expiresAt]; List<Object> get props => [accessToken, expiresAt];
} }

View File

@@ -1,4 +1,4 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@@ -23,23 +23,9 @@ class LoginScreenState extends State<LoginScreen>
final _passwordController = TextEditingController(); final _passwordController = TextEditingController();
bool _obscurePassword = true; bool _obscurePassword = true;
//bool _showWelcome = true; //bool _showWelcome = true;
late AnimationController _logoController;
late Animation<double> _logoAnimation;
@override
void initState() {
super.initState();
_logoController = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..repeat(reverse: true);
_logoAnimation = Tween<double>(begin: 0.2, end: 1).animate(_logoController);
}
@override @override
void dispose() { void dispose() {
_logoController.dispose();
_customerNumberController.dispose(); _customerNumberController.dispose();
_passwordController.dispose(); _passwordController.dispose();
super.dispose(); super.dispose();
@@ -63,16 +49,20 @@ class LoginScreenState extends State<LoginScreen>
if (state is Authenticated) { if (state is Authenticated) {
final storage = getIt<SecureStorage>(); final storage = getIt<SecureStorage>();
final mpin = await storage.read('mpin'); final mpin = await storage.read('mpin');
if (!context.mounted) return;
if (mpin == null) { if (mpin == null) {
Navigator.of(context).pushReplacement( Navigator.of(context).pushReplacement(
MaterialPageRoute( MaterialPageRoute(
builder: (_) => MPinScreen( builder: (_) => MPinScreen(
mode: MPinMode.set, mode: MPinMode.set,
onCompleted: (_) { onCompleted: (_) {
Navigator.of(context, rootNavigator: true) Navigator.of(
.pushReplacement( context,
rootNavigator: true,
).pushReplacement(
MaterialPageRoute( MaterialPageRoute(
builder: (_) => const NavigationScaffold()), builder: (_) => const NavigationScaffold(),
),
); );
}, },
), ),
@@ -84,9 +74,9 @@ class LoginScreenState extends State<LoginScreen>
); );
} }
} else if (state is AuthError) { } else if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(
SnackBar(content: Text(state.message)), context,
); ).showSnackBar(SnackBar(content: Text(state.message)));
} }
}, },
builder: (context, state) { builder: (context, state) {
@@ -97,27 +87,27 @@ class LoginScreenState extends State<LoginScreen>
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
// 🔁 Animated Blinking Logo Image.asset(
FadeTransition( 'assets/images/logo.png',
opacity: _logoAnimation, width: 150,
child: Image.asset( height: 150,
'assets/images/logo.png', errorBuilder: (context, error, stackTrace) {
width: 150, return Icon(
height: 150, Icons.account_balance,
errorBuilder: (context, error, stackTrace) { size: 100,
return const Icon(Icons.account_balance, color: Theme.of(context).primaryColor,
size: 100, color: Colors.blue); );
}, },
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Title // Title
Text( Text(
AppLocalizations.of(context).kccb, AppLocalizations.of(context).kccb,
style: TextStyle( style: TextStyle(
fontSize: 32, fontSize: 32,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.blue), color: Theme.of(context).primaryColor,
),
), ),
const SizedBox(height: 48), const SizedBox(height: 48),
@@ -126,15 +116,15 @@ class LoginScreenState extends State<LoginScreen>
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).customerNumber, labelText: AppLocalizations.of(context).customerNumber,
// prefixIcon: Icon(Icons.person), // prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
@@ -147,24 +137,23 @@ class LoginScreenState extends State<LoginScreen>
}, },
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
// Password // Password
TextFormField( TextFormField(
controller: _passwordController, controller: _passwordController,
obscureText: _obscurePassword, obscureText: _obscurePassword,
textInputAction: TextInputAction.done, textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => onFieldSubmitted: (_) => _submitForm(),
_submitForm(), // ⌨️ Enter key submits
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).password, labelText: AppLocalizations.of(context).password,
border: const OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: const OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: const OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Theme.of(context).colorScheme.primary, width: 2),
), ),
suffixIcon: IconButton( suffixIcon: IconButton(
icon: Icon( icon: Icon(
@@ -195,51 +184,54 @@ class LoginScreenState extends State<LoginScreen>
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.white, backgroundColor:
foregroundColor: Colors.blueAccent, Theme.of(context).scaffoldBackgroundColor,
side: const BorderSide(color: Colors.black, width: 1), foregroundColor: Theme.of(context).primaryColorDark,
side: BorderSide(color: Theme.of(context).colorScheme.outline, width: 1),
elevation: 0, elevation: 0,
), ),
child: state is AuthLoading child: state is AuthLoading
? const CircularProgressIndicator() ? const CircularProgressIndicator()
: Text( : Text(
AppLocalizations.of(context).login, AppLocalizations.of(context).login,
style: TextStyle(fontSize: 16), style: TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
), ),
), ),
), ),
const SizedBox(height: 15), const SizedBox(height: 15),
Padding( // Padding(
padding: EdgeInsets.symmetric(vertical: 16), // padding: const EdgeInsets.symmetric(vertical: 16),
child: Row( // child: Row(
children: [ // children: [
Expanded(child: Divider()), // const Expanded(child: Divider()),
Padding( // Padding(
padding: EdgeInsets.symmetric(horizontal: 8), // padding: const EdgeInsets.symmetric(horizontal: 8),
child: Text(AppLocalizations.of(context).or), // child: Text(AppLocalizations.of(context).or),
), // ),
Expanded(child: Divider()), // //const Expanded(child: Divider()),
], // ],
), // ),
), // ),
const SizedBox(height: 25), const SizedBox(height: 25),
// Register Button // Register Button
SizedBox( // SizedBox(
width: 250, // width: 250,
child: ElevatedButton( // child: ElevatedButton(
//disable until registration is implemented // //disable until registration is implemented
onPressed: null, // onPressed: null,
style: OutlinedButton.styleFrom( // style: OutlinedButton.styleFrom(
shape: const StadiumBorder(), // shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), // padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.lightBlue[100], // backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.black), // foregroundColor: Theme.of(context).colorScheme.onPrimary,
child: Text(AppLocalizations.of(context).register), // ),
), // child: Text(AppLocalizations.of(context).register,
), // style: TextStyle(color: Theme.of(context).colorScheme.onPrimary),),
// ),
// ),
], ],
), ),
), ),
@@ -249,228 +241,3 @@ class LoginScreenState extends State<LoginScreen>
); );
} }
} }
/*import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/auth/screens/mpin_screen.dart';
import 'package:kmobile/security/secure_storage.dart';
import '../../../app.dart';
import '../controllers/auth_cubit.dart';
import '../controllers/auth_state.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
LoginScreenState createState() => LoginScreenState();
}
class LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _customerNumberController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
@override
void dispose() {
_customerNumberController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
context.read<AuthCubit>().login(
_customerNumberController.text.trim(),
_passwordController.text,
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
// appBar: AppBar(title: const Text('Login')),
body: BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) async {
if (state is Authenticated) {
final storage = getIt<SecureStorage>();
final mpin = await storage.read('mpin');
if (mpin == null) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => MPinScreen(
mode: MPinMode.set,
onCompleted: (_) {
Navigator.of(context, rootNavigator: true)
.pushReplacement(
MaterialPageRoute(
builder: (_) => const NavigationScaffold()),
);
},
),
),
);
} else {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const NavigationScaffold()),
);
}
} else if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.message)),
);
}
},
builder: (context, state) {
return Padding(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/logo.png', width: 150, height: 150,
errorBuilder: (context, error, stackTrace) {
return const Icon(Icons.account_balance,
size: 100, color: Colors.blue);
}),
const SizedBox(height: 16),
// Title
const Text(
'KCCB',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: Colors.blue),
),
const SizedBox(height: 48),
TextFormField(
controller: _customerNumberController,
decoration: const InputDecoration(
labelText: 'Customer Number',
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your username';
}
return null;
},
),
const SizedBox(height: 24),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(
labelText: 'Password',
// prefixIcon: const Icon(Icons.lock),
border: const OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
),
textInputAction: TextInputAction.done,
obscureText: _obscurePassword,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
const SizedBox(height: 24),
SizedBox(
width: 250,
child: ElevatedButton(
onPressed: state is AuthLoading ? null : _submitForm,
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.white,
foregroundColor: Colors.blueAccent,
side: const BorderSide(color: Colors.black, width: 1),
elevation: 0),
child: state is AuthLoading
? const CircularProgressIndicator()
: const Text(
'Login',
style: TextStyle(fontSize: 16),
),
),
),
const SizedBox(height: 15),
const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Row(
children: [
Expanded(child: Divider()),
Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Text('OR'),
),
Expanded(child: Divider()),
],
),
),
const SizedBox(height: 25),
// Register Button
SizedBox(
width: 250,
child: ElevatedButton(
//disable until registration is implemented
onPressed: null,
style: OutlinedButton.styleFrom(
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.lightBlue[100],
foregroundColor: Colors.black),
child: const Text('Register'),
),
),
],
),
),
);
},
),
);
}
}
*/

View File

@@ -1,12 +1,14 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'dart:math';
import 'dart:developer'; // import 'dart:developer';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/app.dart'; import 'package:kmobile/app.dart';
import 'package:kmobile/di/injection.dart'; import 'package:kmobile/di/injection.dart';
import 'package:kmobile/security/secure_storage.dart'; import 'package:kmobile/security/secure_storage.dart';
import 'package:local_auth/local_auth.dart'; import 'package:local_auth/local_auth.dart';
import 'package:flutter/services.dart';
enum MPinMode { enter, set, confirm } enum MPinMode { enter, set, confirm }
@@ -26,26 +28,78 @@ class MPinScreen extends StatefulWidget {
State<MPinScreen> createState() => _MPinScreenState(); State<MPinScreen> createState() => _MPinScreenState();
} }
class _MPinScreenState extends State<MPinScreen> { class _MPinScreenState extends State<MPinScreen> with TickerProviderStateMixin {
List<String> mPin = []; List<String> mPin = [];
String? errorText; String? errorText;
// Animation controllers
late final AnimationController _bounceController;
late final Animation<double> _bounceAnimation;
late final AnimationController _shakeController;
late final AnimationController _waveController;
late final Animation<double> _waveAnimation;
// State flags for animations
bool _isError = false;
bool _isSuccess = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Bounce animation for single dot entry
_bounceController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 150),
);
_bounceAnimation = Tween<double>(begin: 1.0, end: 1.2).animate(
CurvedAnimation(
parent: _bounceController,
curve: Curves.elasticIn,
reverseCurve: Curves.elasticOut,
),
)..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_bounceController.reverse();
}
});
// Shake animation for error
_shakeController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
// Wave animation for success
_waveController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800),
);
_waveAnimation = Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(parent: _waveController, curve: Curves.easeInOut),
);
if (widget.mode == MPinMode.enter) { if (widget.mode == MPinMode.enter) {
_tryBiometricBeforePin(); _tryBiometricBeforePin();
} }
} }
@override
void dispose() {
_bounceController.dispose();
_shakeController.dispose();
_waveController.dispose();
super.dispose();
}
Future<void> _tryBiometricBeforePin() async { Future<void> _tryBiometricBeforePin() async {
final storage = getIt<SecureStorage>(); final storage = getIt<SecureStorage>();
final enabled = await storage.read('biometric_enabled'); final enabled = await storage.read('biometric_enabled');
log('biometric_enabled: $enabled'); // log('biometric_enabled: $enabled');
if (enabled != null && enabled) { if (enabled != null && enabled) {
final auth = LocalAuthentication(); final auth = LocalAuthentication();
if (await auth.canCheckBiometrics) { if (await auth.canCheckBiometrics) {
final didAuth = await auth.authenticate( final didAuth = await auth.authenticate(
// ignore: use_build_context_synchronously
localizedReason: AppLocalizations.of(context).authenticateToAccess, localizedReason: AppLocalizations.of(context).authenticateToAccess,
options: const AuthenticationOptions(biometricOnly: true), options: const AuthenticationOptions(biometricOnly: true),
); );
@@ -61,11 +115,13 @@ class _MPinScreenState extends State<MPinScreen> {
} }
void addDigit(String digit) { void addDigit(String digit) {
if (_shakeController.isAnimating || _waveController.isAnimating) return;
if (mPin.length < 4) { if (mPin.length < 4) {
setState(() { setState(() {
mPin.add(digit); mPin.add(digit);
errorText = null; errorText = null;
}); });
_bounceController.forward(from: 0);
if (mPin.length == 4) { if (mPin.length == 4) {
_handleComplete(); _handleComplete();
} }
@@ -73,6 +129,7 @@ class _MPinScreenState extends State<MPinScreen> {
} }
void deleteDigit() { void deleteDigit() {
if (_shakeController.isAnimating || _waveController.isAnimating) return;
if (mPin.isNotEmpty) { if (mPin.isNotEmpty) {
setState(() { setState(() {
mPin.removeLast(); mPin.removeLast();
@@ -82,19 +139,36 @@ class _MPinScreenState extends State<MPinScreen> {
} }
Future<void> _handleComplete() async { Future<void> _handleComplete() async {
if (_shakeController.isAnimating || _waveController.isAnimating) return;
final pin = mPin.join(); final pin = mPin.join();
final storage = SecureStorage(); final storage = SecureStorage();
switch (widget.mode) { switch (widget.mode) {
case MPinMode.enter: case MPinMode.enter:
final storedPin = await storage.read('mpin'); final storedPin = await storage.read('mpin');
log('storedPin: $storedPin'); // log('storedPin: $storedPin');
if (storedPin == int.tryParse(pin)) { if (storedPin == int.tryParse(pin)) {
widget.onCompleted?.call(pin); // Correct PIN
} else {
setState(() { setState(() {
_isSuccess = true;
errorText = null;
});
await Future.delayed(const Duration(milliseconds: 100));
_waveController.forward(from: 0).whenComplete(() {
widget.onCompleted?.call(pin);
});
} else {
// Incorrect PIN
setState(() {
_isError = true;
errorText = AppLocalizations.of(context).incorrectMPIN; errorText = AppLocalizations.of(context).incorrectMPIN;
});
await _shakeController.forward(from: 0);
setState(() {
mPin.clear(); mPin.clear();
_isError = false;
// Keep error text until next digit is entered
}); });
} }
break; break;
@@ -125,28 +199,81 @@ class _MPinScreenState extends State<MPinScreen> {
} }
} else { } else {
setState(() { setState(() {
_isError = true;
errorText = AppLocalizations.of(context).pinsDoNotMatch; errorText = AppLocalizations.of(context).pinsDoNotMatch;
});
await _shakeController.forward(from: 0);
setState(() {
mPin.clear(); mPin.clear();
_isError = false;
}); });
} }
break; break;
} }
} }
Widget buildMPinDots() { Widget buildMPinDots(BuildContext context) {
return Row( return AnimatedBuilder(
mainAxisAlignment: MainAxisAlignment.center, animation: Listenable.merge(
children: List.generate(4, (index) { [_bounceController, _shakeController, _waveController]),
return Container( builder: (context, child) {
margin: const EdgeInsets.all(8), double shakeOffset = 0;
width: 15, if (_shakeController.isAnimating) {
height: 15, // 4 cycles of sine wave for shake
decoration: BoxDecoration( shakeOffset = sin(_shakeController.value * 4 * pi) * 12;
shape: BoxShape.circle, }
color: index < mPin.length ? Colors.black : Colors.grey[400],
return Transform.translate(
offset: Offset(shakeOffset, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(4, (index) {
final isFilled = index < mPin.length;
// Bounce animation for single dot
final isAnimatingBounce =
index == mPin.length - 1 && _bounceController.isAnimating;
double bounceScale =
isAnimatingBounce ? _bounceAnimation.value : 1.0;
// Success wave animation
double waveScale = 1.0;
if (_isSuccess) {
final waveDelay = index * 0.15;
final waveValue =
(_waveAnimation.value - waveDelay).clamp(0.0, 1.0);
// Grow and shrink
waveScale = 1.0 + sin(waveValue * pi) * 0.4;
}
// Determine dot color
Color dotColor;
if (_isError) {
dotColor = Theme.of(context).colorScheme.error;
} else if (_isSuccess) {
dotColor = Colors.green.shade600;
} else {
dotColor = isFilled
? Theme.of(context).colorScheme.onSurfaceVariant
: Theme.of(context).colorScheme.surfaceContainerHighest;
}
return Transform.scale(
scale: bounceScale * waveScale,
child: Container(
margin: const EdgeInsets.all(8),
width: 25,
height: 25,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: dotColor,
),
),
);
}),
), ),
); );
}), },
); );
} }
@@ -155,7 +282,7 @@ class _MPinScreenState extends State<MPinScreen> {
['1', '2', '3'], ['1', '2', '3'],
['4', '5', '6'], ['4', '5', '6'],
['7', '8', '9'], ['7', '8', '9'],
['Enter', '0', '<'] ['Enter', '0', '<'],
]; ];
return Column( return Column(
@@ -164,9 +291,10 @@ class _MPinScreenState extends State<MPinScreen> {
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: row.map((key) { children: row.map((key) {
return Padding( return Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(1.0),
child: GestureDetector( child: GestureDetector(
onTap: () { onTap: () {
HapticFeedback.lightImpact();
if (key == '<') { if (key == '<') {
deleteDigit(); deleteDigit();
} else if (key == 'Enter') { } else if (key == 'Enter') {
@@ -174,8 +302,9 @@ class _MPinScreenState extends State<MPinScreen> {
_handleComplete(); _handleComplete();
} else { } else {
setState(() { setState(() {
errorText = errorText = AppLocalizations.of(
AppLocalizations.of(context).pleaseEnter4Digits; context,
).pleaseEnter4Digits;
}); });
} }
} else if (key.isNotEmpty) { } else if (key.isNotEmpty) {
@@ -183,11 +312,10 @@ class _MPinScreenState extends State<MPinScreen> {
} }
}, },
child: Container( child: Container(
width: 70, width: 80,
height: 70, height: 80,
decoration: BoxDecoration( decoration: const BoxDecoration(
shape: BoxShape.circle, shape: BoxShape.circle,
color: Colors.grey[200],
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: key == 'Enter' child: key == 'Enter'
@@ -195,8 +323,10 @@ class _MPinScreenState extends State<MPinScreen> {
: Text( : Text(
key == '<' ? '' : key, key == '<' ? '' : key,
style: TextStyle( style: TextStyle(
fontSize: 20, fontSize: 30,
color: key == 'Enter' ? Colors.blue : Colors.black, color: key == 'Enter'
? Theme.of(context).primaryColor
: Theme.of(context).colorScheme.onSurface,
), ),
), ),
), ),
@@ -225,7 +355,7 @@ class _MPinScreenState extends State<MPinScreen> {
body: SafeArea( body: SafeArea(
child: Column( child: Column(
children: [ children: [
const Spacer(), const SizedBox(height: 50),
// Logo // Logo
Image.asset('assets/images/logo.png', height: 100), Image.asset('assets/images/logo.png', height: 100),
const SizedBox(height: 20), const SizedBox(height: 20),
@@ -233,17 +363,18 @@ class _MPinScreenState extends State<MPinScreen> {
getTitle(), getTitle(),
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
), ),
const SizedBox(height: 20), const Spacer(),
buildMPinDots(), buildMPinDots(context),
if (errorText != null) if (errorText != null)
Padding( Padding(
padding: const EdgeInsets.only(top: 8.0), padding: const EdgeInsets.only(top: 8.0),
child: child: Text(
Text(errorText!, style: const TextStyle(color: Colors.red)), errorText!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
), ),
const Spacer(), const Spacer(),
buildNumberPad(), buildNumberPad(),
const Spacer(),
], ],
), ),
), ),

View File

@@ -0,0 +1,62 @@
import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned.fill(
child: Image.asset(
'assets/images/kconnect2.webp',
fit: BoxFit.cover,
),
),
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
AppLocalizations.of(context).kconnect,
style: const TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
color: Color(0xFFFFFFFF),
),
),
const SizedBox(height: 12),
Text(
AppLocalizations.of(context).kccBankFull,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 18,
color: Color(0xFFFFFFFF),
letterSpacing: 1.2,
),
),
],
),
),
const Positioned(
bottom: 40,
left: 0,
right: 0,
child: Center(
child: CircularProgressIndicator(
color: Color(0xFFFFFFFF)),
),
),
],
),
);
}
}

View File

@@ -1,143 +0,0 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'dart:async';
class WelcomeScreen extends StatefulWidget {
final VoidCallback onContinue;
const WelcomeScreen({super.key, required this.onContinue});
@override
State<WelcomeScreen> createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
@override
void initState() {
super.initState();
// Automatically go to login after 6 seconds
Timer(const Duration(seconds: 6), () {
widget.onContinue();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
/// 🔹 Background Image
Positioned.fill(
child: Image.asset(
'assets/images/kconnect2.webp',
fit: BoxFit.cover,
),
),
/// 🔹 Centered Text Overlay
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
AppLocalizations.of(context).kconnect,
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 1.5,
),
),
SizedBox(height: 12),
Text(
AppLocalizations.of(context).kccBankFull,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.white,
letterSpacing: 1.2,
),
),
],
),
),
/// 🔹 Loading Spinner at Bottom
const Positioned(
bottom: 40,
left: 0,
right: 0,
child: Center(
child: CircularProgressIndicator(
color: Colors.white,
),
),
),
],
),
);
}
}
/*import 'package:flutter/material.dart';
class WelcomeScreen extends StatelessWidget {
final VoidCallback onContinue;
const WelcomeScreen({super.key, required this.onContinue});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(),
const Text(
'Welcome to',
style: TextStyle(fontSize: 28, color: Colors.black87),
),
const SizedBox(height: 10),
const Text(
'KCCB',
style: TextStyle(
fontSize: 42,
fontWeight: FontWeight.bold,
color: Colors.indigo,
),
),
const SizedBox(height: 40),
Image.asset(
'assets/images/logo.png',
width: 150,
height: 150,
),
const Spacer(),
ElevatedButton(
onPressed: onContinue,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.indigo,
foregroundColor: Colors.white,
padding:
const EdgeInsets.symmetric(horizontal: 28, vertical: 20),
),
child: const Text('Proceed to Login'),
),
const SizedBox(height: 24),
],
),
),
),
);
}
}
*/

View File

@@ -1,10 +1,21 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter/services.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/data/models/beneficiary.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'beneficiary_result_page.dart';
import '../../../di/injection.dart';
import '../../../l10n/app_localizations.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart';
class AddBeneficiaryScreen extends StatefulWidget { class AddBeneficiaryScreen extends StatefulWidget {
const AddBeneficiaryScreen({super.key}); final String customerName;
const AddBeneficiaryScreen({
super.key,
required this.customerName,
});
@override @override
State<AddBeneficiaryScreen> createState() => _AddBeneficiaryScreen(); State<AddBeneficiaryScreen> createState() => _AddBeneficiaryScreen();
@@ -12,7 +23,9 @@ class AddBeneficiaryScreen extends StatefulWidget {
class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> { class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
final _accountNumberFieldKey = GlobalKey<FormFieldState>();
final _confirmAccountNumberFieldKey = GlobalKey<FormFieldState>();
final _ifscFieldKey = GlobalKey<FormFieldState>();
final TextEditingController accountNumberController = TextEditingController(); final TextEditingController accountNumberController = TextEditingController();
final TextEditingController confirmAccountNumberController = final TextEditingController confirmAccountNumberController =
TextEditingController(); TextEditingController();
@@ -21,7 +34,12 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
final TextEditingController branchNameController = TextEditingController(); final TextEditingController branchNameController = TextEditingController();
final TextEditingController ifscController = TextEditingController(); final TextEditingController ifscController = TextEditingController();
final TextEditingController phoneController = TextEditingController(); final TextEditingController phoneController = TextEditingController();
final service = getIt<BeneficiaryService>();
bool _isValidating = false;
bool _isBeneficiaryValidated = false;
// ignore: unused_field
String? _validationError;
late String accountType; late String accountType;
@override @override
@@ -29,131 +47,184 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
super.initState(); super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() { setState(() {
accountType = AppLocalizations.of(context).savings; accountType = 'Savings';
}); });
}); });
} }
void _submitForm() { void _validateIFSC() async {
if (_formKey.currentState!.validate()) { var beneficiaryService = getIt<BeneficiaryService>();
// Handle successful submission final ifsc = ifscController.text.trim().toUpperCase();
ScaffoldMessenger.of(context).showSnackBar( if (ifsc.isEmpty) return;
SnackBar(
backgroundColor: Colors.grey[900], final result = await beneficiaryService.validateIFSC(ifsc);
behavior: SnackBarBehavior.floating,
margin: const EdgeInsets.all(12), if (mounted) {
duration: const Duration(seconds: 5), if (result.bankName == '') {
content: Row( ScaffoldMessenger.of(context).showSnackBar(
mainAxisAlignment: MainAxisAlignment.spaceBetween, SnackBar(content: Text(AppLocalizations.of(context).invalidIfsc)),
children: [ );
Expanded( bankNameController.clear();
child: Text( branchNameController.clear();
AppLocalizations.of(context).beneficiaryAdded, } else {
style: TextStyle(color: Colors.white), bankNameController.text = result.bankName;
), branchNameController.text = result.branchName;
), }
TextButton(
onPressed: () {
// Navigate to Payment Screen or do something
},
style: TextButton.styleFrom(
foregroundColor: Colors.blue[200],
),
child: Text(AppLocalizations.of(context).payNow),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
],
),
),
);
} }
} }
void _validateIFSC() async { void _validateBeneficiary() async {
final ifsc = ifscController.text.trim().toUpperCase(); FocusScope.of(context).unfocus();
setState(() {
_isValidating = true;
_validationError = null;
_isBeneficiaryValidated = false;
nameController.text = ''; // clear previous name
});
// 🔹 Format check final String accountNo = accountNumberController.text.trim();
final isValidFormat = RegExp(r'^[A-Z]{4}0[A-Z0-9]{6}$').hasMatch(ifsc); final String ifsc = ifscController.text.trim();
if (!isValidFormat) { final String remitter = widget.customerName;
bankNameController.clear();
branchNameController.clear(); final service = getIt<BeneficiaryService>();
try {
String beneficiaryName;
if (ifsc.toLowerCase().contains('kace')) {
beneficiaryName =
await service.validateBeneficiaryWithinBank(accountNo);
} else {
beneficiaryName = await service.validateBeneficiary(
accountNo: accountNo,
ifscCode: ifsc,
remitterName: remitter,
);
}
setState(() {
nameController.text = beneficiaryName;
_isBeneficiaryValidated = true;
_validationError = null;
});
} catch (e) {
setState(() {
_validationError = e.toString();
_isBeneficiaryValidated = false;
});
} finally {
if (mounted) {
setState(() {
_isValidating = false;
});
}
}
}
void validateAndAddBeneficiary() async {
// First, validate the form fields (account number, confirm account, ifsc, etc.)
if (!_formKey.currentState!.validate()) {
return;
}
// Ensure beneficiary is validated before proceeding to TPIN
if (!_isBeneficiaryValidated) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context).invalidIfscFormat)), SnackBar(
content: Text(AppLocalizations.of(context)
.pleaseValidateBeneficiaryDetailsFirst)),
); );
return; return;
} }
await Future.delayed(
const Duration(seconds: 2)); //Mock delay for 2 sec to imitate api call
// 🔹 Mock IFSC lookup (you can replace this with API)
const mockIfscData = {
'KCCB0001234': {
'bank': 'Kangra Central Co-operative Bank',
'branch': 'Dharamshala',
},
'SBIN0004567': {
'bank': 'State Bank of India',
'branch': 'Connaught Place',
},
};
if (mockIfscData.containsKey(ifsc)) { // Create the beneficiary object without TPIN for now
final data = mockIfscData[ifsc]!; final beneficiaryWithoutTpin = Beneficiary(
bankNameController.text = data['bank']!; accountNo: accountNumberController.text.trim(),
branchNameController.text = data['branch']!; accountType: accountType,
} else { name: nameController.text.trim(),
bankNameController.clear(); ifscCode: ifscController.text.trim(),
branchNameController.clear(); bankName: bankNameController.text.trim(),
ScaffoldMessenger.of(context).showSnackBar( branchName: branchNameController.text.trim(),
SnackBar(content: Text(AppLocalizations.of(context).noIfscDetails)), );
);
}
/* // Navigate to TPIN screen
🔸 Optional: Use real IFSC API like: Navigator.push(
final response = await http.get(Uri.parse('https://ifsc.razorpay.com/$ifsc')); context,
if (response.statusCode == 200) { MaterialPageRoute(
final data = jsonDecode(response.body); builder: (context) => TransactionPinScreen(
bankNameController.text = data['BANK']; onPinCompleted: (pinScreenContext, tpin) async {
branchNameController.text = data['BRANCH']; // Show loading spinner while processing
} showDialog(
*/ context: pinScreenContext,
barrierDismissible: false,
builder: (BuildContext ctx) {
// ignore: deprecated_member_use
return WillPopScope(
onWillPop: () async => false,
child: const Center(
child: CircularProgressIndicator(),
),
);
},
);
// Create a new Beneficiary object with the TPIN
final beneficiaryWithTpin = Beneficiary(
accountNo: beneficiaryWithoutTpin.accountNo,
accountType: beneficiaryWithoutTpin.accountType,
name: beneficiaryWithoutTpin.name,
ifscCode: beneficiaryWithoutTpin.ifscCode,
bankName: beneficiaryWithoutTpin.bankName,
branchName: beneficiaryWithoutTpin.branchName,
tpin: tpin,
);
try {
final isSuccess =
await service.sendForValidation(beneficiaryWithTpin);
if (pinScreenContext.mounted) {
Navigator.pop(pinScreenContext); // Close the spinner
Navigator.pushReplacement(
pinScreenContext,
MaterialPageRoute(
builder: (ctx) =>
BeneficiaryResultPage(isSuccess: isSuccess),
),
);
}
} on DioException catch (e) {
if (pinScreenContext.mounted) {
Navigator.pop(pinScreenContext); // Close the spinner
ScaffoldMessenger.of(pinScreenContext).showSnackBar(
SnackBar(
content: Text(e.response?.statusCode == 409
? 'Beneficiary already exists'
: 'Something went Wrong')),
);
}
} catch (e) {
if (pinScreenContext.mounted) {
Navigator.pop(pinScreenContext); // Close the spinner
ScaffoldMessenger.of(pinScreenContext).showSnackBar(
SnackBar(
content: Text(
AppLocalizations.of(context).somethingWentWrong)),
);
}
}
},
),
),
);
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).addBeneficiary, AppLocalizations.of(context).addBeneficiary,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: SafeArea( body: SafeArea(
child: Form( child: Form(
@@ -168,30 +239,30 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
child: Column( child: Column(
children: [ children: [
TextFormField( TextFormField(
key: _accountNumberFieldKey,
controller: accountNumberController, controller: accountNumberController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: labelText: AppLocalizations.of(
AppLocalizations.of(context).accountNumber, context,
).accountNumber,
// prefixIcon: Icon(Icons.person), // prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
obscureText: true, obscureText: true,
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
textInputAction: TextInputAction.next, textInputAction: TextInputAction.next,
onChanged: (value) {
nameController.clear();
setState(() {
_isBeneficiaryValidated = false;
});
},
validator: (value) { validator: (value) {
if (value == null || value.length < 10) { if (value == null || value.length < 10) {
return AppLocalizations.of(context) return AppLocalizations.of(
.enterValidAccountNumber; context,
).enterValidAccountNumber;
} }
return null; return null;
}, },
@@ -199,181 +270,42 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
const SizedBox(height: 24), const SizedBox(height: 24),
// Confirm Account Number // Confirm Account Number
TextFormField( TextFormField(
key: _confirmAccountNumberFieldKey,
controller: confirmAccountNumberController, controller: confirmAccountNumberController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context) labelText: AppLocalizations.of(
.confirmAccountNumber, context,
).confirmAccountNumber,
// prefixIcon: Icon(Icons.person), // prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
textInputAction: TextInputAction.next, textInputAction: TextInputAction.next,
validator: (value) { validator: (value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return AppLocalizations.of(context) return AppLocalizations.of(
.reenterAccountNumber; context,
).reenterAccountNumber;
} }
if (value != accountNumberController.text) { if (value != accountNumberController.text) {
return AppLocalizations.of(context) return AppLocalizations.of(context,).accountMismatch;
.accountMismatch;
} }
return null; return null;
}, },
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
TextFormField( TextFormField(
controller: nameController, key: _ifscFieldKey,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).name,
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
),
textInputAction: TextInputAction.next,
validator: (value) => value == null || value.isEmpty
? AppLocalizations.of(context).nameRequired
: null,
),
/*const SizedBox(height: 24),
TextFormField(
controller: bankNameController,
decoration: const InputDecoration(
labelText: 'Beneficiary Bank Name',
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
textInputAction: TextInputAction.next,
validator: (value) =>
value == null || value.isEmpty ? "Bank name is required" : null,
),
const SizedBox(height: 24),
TextFormField(
controller: branchNameController,
decoration: const InputDecoration(
labelText: 'Branch Name',
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
textInputAction: TextInputAction.next,
validator: (value) =>
value == null || value.isEmpty ? "Branch name is required" : null,
),
const SizedBox(height: 24),
Row(
children: [
Expanded(
flex: 2,
child: TextFormField(
controller: ifscController,
decoration: const InputDecoration(
labelText: 'IFSC Code',
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
textInputAction: TextInputAction.next,
validator: (value) => value == null || value.length < 5
? "Enter a valid IFSC"
: null,
),
),
const SizedBox(width: 16),
Expanded(
flex: 2,
child: DropdownButtonFormField<String>(
value: accountType,
decoration: const InputDecoration(
labelText: 'Account Type',
// prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
items: ['Savings', 'Current']
.map((type) => DropdownMenuItem(
value: type,
child: Text(type),
))
.toList(),
onChanged: (value) {
setState(() {
accountType = value!;
});
},
),
),
],
),*/
const SizedBox(height: 24),
// 🔹 IFSC Code Field
TextFormField(
controller: ifscController, controller: ifscController,
maxLength: 11,
inputFormatters: [
LengthLimitingTextInputFormatter(11),
],
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).ifscCode, labelText: AppLocalizations.of(context).ifscCode,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
textCapitalization: TextCapitalization.characters, textCapitalization: TextCapitalization.characters,
textInputAction: TextInputAction.next, textInputAction: TextInputAction.next,
@@ -392,15 +324,16 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
final pattern = RegExp(r'^[A-Z]{4}0[A-Z0-9]{6}$'); final pattern = RegExp(r'^[A-Z]{4}0[A-Z0-9]{6}$');
if (value == null || value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return AppLocalizations.of(context).enterIfsc; return AppLocalizations.of(context).enterIfsc;
} else if (!pattern } else if (!pattern.hasMatch(
.hasMatch(value.trim().toUpperCase())) { value.trim().toUpperCase(),
return AppLocalizations.of(context) )) {
.invalidIfscFormat; return AppLocalizations.of(
context,
).invalidIfscFormat;
} }
return null; return null;
}, },
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
// 🔹 Bank Name (Disabled) // 🔹 Bank Name (Disabled)
TextFormField( TextFormField(
@@ -408,20 +341,10 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
enabled: false, // changed from readOnly to disabled enabled: false, // changed from readOnly to disabled
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).bankName, labelText: AppLocalizations.of(context).bankName,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white, // disabled color
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
// 🔹 Branch Name (Disabled) // 🔹 Branch Name (Disabled)
TextFormField( TextFormField(
@@ -429,46 +352,92 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
enabled: false, // changed from readOnly to disabled enabled: false, // changed from readOnly to disabled
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).branchName, labelText: AppLocalizations.of(context).branchName,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
), ),
if (_isBeneficiaryValidated)
Column(
children: [
const SizedBox(height: 24),
TextFormField(
controller: nameController,
enabled: false,
decoration: InputDecoration(
suffixIcon: _isBeneficiaryValidated
? const Icon(
Symbols.verified,
size: 25,
fill: 1,
)
: null,
suffixIconColor:
Theme.of(context).colorScheme.primary,
labelText: AppLocalizations.of(context)
.beneficiaryName,
border: const OutlineInputBorder(),
isDense: true,
),
textInputAction: TextInputAction.next,
validator: (value) => value == null ||
value.isEmpty
? AppLocalizations.of(context).nameRequired
: null,
),
],
),
const SizedBox(height: 24), const SizedBox(height: 24),
if (!_isBeneficiaryValidated)
Padding(
padding: const EdgeInsets.only(bottom: 24),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isValidating
? null
: () {
final isAccountValid =
_accountNumberFieldKey.currentState!.validate();
final isConfirmAccountValid =
_confirmAccountNumberFieldKey.currentState!.validate();
final isIfscValid = _ifscFieldKey.currentState!.validate();
if (isAccountValid && isConfirmAccountValid && isIfscValid) {
_validateBeneficiary();
}
},
child: _isValidating
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2),
)
: Text(AppLocalizations.of(context)
.validateBeneficiary),
),
),
),
//Beneficiary Name (Disabled)
// 🔹 Account Type Dropdown // 🔹 Account Type Dropdown
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
value: accountType, value: accountType,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).accountType, labelText: AppLocalizations.of(context).accountType,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
items: [ items: [
AppLocalizations.of(context).savings, 'Savings',
AppLocalizations.of(context).current 'Current',
] ]
.map((type) => DropdownMenuItem( .map(
value: type, (type) => DropdownMenuItem(
child: Text(type), value: type,
)) child: Text(type),
),
)
.toList(), .toList(),
onChanged: (value) { onChanged: (value) {
setState(() { setState(() {
@@ -483,18 +452,9 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
keyboardType: TextInputType.phone, keyboardType: TextInputType.phone,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).phone, labelText: AppLocalizations.of(context).phone,
prefixIcon: Icon(Icons.phone), prefixIcon: const Icon(Icons.phone),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black, width: 2),
),
), ),
textInputAction: TextInputAction.done, textInputAction: TextInputAction.done,
validator: (value) => validator: (value) =>
@@ -509,18 +469,22 @@ class _AddBeneficiaryScreen extends State<AddBeneficiaryScreen> {
), ),
), ),
Padding( Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.symmetric(vertical: 10),
child: SizedBox( child: SizedBox(
width: 250, width: 250,
child: ElevatedButton( child: ElevatedButton(
onPressed: _submitForm, onPressed: validateAndAddBeneficiary,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.blue[900], backgroundColor:
foregroundColor: Colors.white, Theme.of(context).colorScheme.primaryContainer,
foregroundColor:
Theme.of(context).colorScheme.onPrimaryContainer),
child: Text(
AppLocalizations.of(context).validateAndAdd,
style: const TextStyle(fontSize: 16),
), ),
child: Text(AppLocalizations.of(context).validateAndAdd),
), ),
), ),
), ),

View File

@@ -0,0 +1,163 @@
import 'package:flutter/material.dart';
import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/widgets/bank_logos.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import '../../../l10n/app_localizations.dart';
class BeneficiaryDetailsScreen extends StatelessWidget {
final Beneficiary beneficiary;
BeneficiaryDetailsScreen({super.key, required this.beneficiary});
final service = getIt<BeneficiaryService>();
void _deleteBeneficiary(BuildContext context) async {
try {
await service.deleteBeneficiary(beneficiary.accountNo);
if (!context.mounted) {
return;
}
_showSuccessDialog(context);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to delete beneficiary: $e')),
);
}
}
void _showSuccessDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Success'),
content: const Text('Beneficiary deleted successfully.'),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).popUntil((route) => route.isFirst);
},
),
],
);
},
);
}
void _showDeleteConfirmationDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Delete Beneficiary'),
content:
const Text('Are you sure you want to delete this beneficiary?'),
actions: <Widget>[
TextButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('Delete'),
onPressed: () {
//Navigator.of(context).pop();
_deleteBeneficiary(context);
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).beneficiarydetails),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 24,
backgroundColor: Colors.transparent,
child: getBankLogo(beneficiary.bankName, context),
),
const SizedBox(width: 16),
Text(
beneficiary.name,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 24),
_buildDetailRow('${AppLocalizations.of(context).bankName} ',
beneficiary.bankName ?? 'N/A'),
_buildDetailRow('${AppLocalizations.of(context).accountNumber} ',
beneficiary.accountNo),
_buildDetailRow('${AppLocalizations.of(context).accountType} ',
beneficiary.accountType),
_buildDetailRow('${AppLocalizations.of(context).ifscCode} ',
beneficiary.ifscCode),
_buildDetailRow('${AppLocalizations.of(context).branchName} ',
beneficiary.branchName ?? 'N/A'),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// ElevatedButton.icon(
// onPressed: () {
// // Set Transaction Limit for this beneficiary
// },
// icon: const Icon(Icons.currency_rupee),
// label: const Text('Set Limit'),
// ),
ElevatedButton.icon(
onPressed: () {
// Delete beneficiary option
_showDeleteConfirmationDialog(context);
},
icon: const Icon(Icons.delete),
label: Text(AppLocalizations.of(context).delete),
),
],
),
],
),
),
),
);
}
Widget _buildDetailRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(width: 16),
Flexible(
child: Text(
value,
textAlign: TextAlign.end,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,116 @@
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:confetti/confetti.dart';
import 'dart:math';
import '../../../app.dart';
import '../../../l10n/app_localizations.dart';
class BeneficiaryResultPage extends StatefulWidget {
final bool isSuccess;
const BeneficiaryResultPage({super.key, required this.isSuccess});
@override
State<BeneficiaryResultPage> createState() => _BeneficiaryResultPageState();
}
class _BeneficiaryResultPageState extends State<BeneficiaryResultPage> {
late ConfettiController _confettiController;
@override
void initState() {
super.initState();
_confettiController =
ConfettiController(duration: const Duration(seconds: 3));
if (widget.isSuccess) {
_confettiController.play();
}
}
@override
void dispose() {
_confettiController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
const successAnimation = 'assets/animations/done.json';
const errorAnimation = 'assets/animations/error.json';
return Scaffold(
backgroundColor: widget.isSuccess ? Colors.green[50] : Colors.red[50],
body: Stack(
alignment: Alignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Lottie.asset(
widget.isSuccess ? successAnimation : errorAnimation,
width: 150,
height: 150,
repeat: false,
),
const SizedBox(height: 20),
Text(
widget.isSuccess
? AppLocalizations.of(context).beneficiaryAddedSuccess
: AppLocalizations.of(context).beneficiaryAdditionFailed,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: widget.isSuccess ? Colors.green : Colors.red,
),
textAlign: TextAlign.center,
),
],
),
Positioned(
bottom: 20, // keep it slightly above the very bottom
left: 16,
right: 16,
child: SizedBox(
height: 56, // larger button height
child: ElevatedButton(
onPressed: () {
Navigator.pushReplacement(
// ensures back goes to ScaffoldScreen
context,
MaterialPageRoute(
builder: (context) => const NavigationScaffold(),
),
);
},
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 12),
backgroundColor: Theme.of(context).primaryColorDark,
foregroundColor: Theme.of(context).scaffoldBackgroundColor,
),
child: Text(
AppLocalizations.of(context).done,
style: TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer), // slightly bigger text
),
),
),
),
if (widget.isSuccess)
Align(
alignment: Alignment.topCenter,
child: ConfettiWidget(
confettiController: _confettiController,
blastDirection: pi / 2,
maxBlastForce: 10,
minBlastForce: 5,
emissionFrequency: 0.05,
numberOfParticles: 20,
gravity: 0.2,
shouldLoop: false,
),
),
],
),
);
}
}

View File

@@ -1,11 +1,16 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/features/beneficiaries/screens/add_beneficiary_screen.dart'; import 'package:kmobile/features/beneficiaries/screens/add_beneficiary_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:kmobile/features/beneficiaries/screens/beneficiary_details_screen.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import '../../../di/injection.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:shimmer/shimmer.dart';
import 'package:kmobile/widgets/bank_logos.dart';
class ManageBeneficiariesScreen extends StatefulWidget { class ManageBeneficiariesScreen extends StatefulWidget {
const ManageBeneficiariesScreen({super.key}); final String customerName;
const ManageBeneficiariesScreen({super.key, required this.customerName});
@override @override
State<ManageBeneficiariesScreen> createState() => State<ManageBeneficiariesScreen> createState() =>
@@ -13,88 +18,110 @@ class ManageBeneficiariesScreen extends StatefulWidget {
} }
class _ManageBeneficiariesScreen extends State<ManageBeneficiariesScreen> { class _ManageBeneficiariesScreen extends State<ManageBeneficiariesScreen> {
final List<Map<String, String>> beneficiaries = [ var service = getIt<BeneficiaryService>();
{ bool _isLoading = true;
'bank': 'State Bank Of India', List<Beneficiary> _beneficiaries = [];
'name': 'Trina Bakshi',
},
{
'bank': 'State Bank Of India',
'name': 'Sheetal Rao',
},
{
'bank': 'Punjab National Bank',
'name': 'Manoj Kumar',
},
{
'bank': 'State Bank Of India',
'name': 'Rohit Mehra',
},
];
@override @override
Widget build(BuildContext context) { void initState() {
return Scaffold( super.initState();
appBar: AppBar( _loadBeneficiaries();
leading: IconButton( }
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () { Future<void> _loadBeneficiaries() async {
Navigator.pop(context); final data = await service.fetchBeneficiaryList();
}, setState(() {
), _beneficiaries = data;
title: Text( _isLoading = false;
AppLocalizations.of(context).beneficiaries, });
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), }
),
centerTitle: false, Widget _buildShimmerList() {
actions: [ return ListView.builder(
Padding( itemCount: 6,
padding: const EdgeInsets.only(right: 10.0), itemBuilder: (context, index) => Shimmer.fromColors(
child: CircleAvatar( baseColor: Colors.grey.shade300,
backgroundColor: Colors.grey[200], highlightColor: Colors.grey.shade100,
radius: 20, child: ListTile(
child: SvgPicture.asset( leading: const CircleAvatar(
'assets/images/avatar_male.svg', radius: 24,
width: 40, backgroundColor: Colors.white,
height: 40,
fit: BoxFit.cover,
),
),
), ),
], title: Container(
height: 16,
color: Colors.white,
margin: const EdgeInsets.symmetric(vertical: 4),
),
subtitle: Container(
height: 14,
color: Colors.white,
margin: const EdgeInsets.symmetric(vertical: 4),
),
),
), ),
body: Padding( );
padding: const EdgeInsets.all(8.0), }
child: ListView.builder(
itemCount: beneficiaries.length, Widget _buildBeneficiaryList() {
itemBuilder: (context, index) { if (_beneficiaries.isEmpty) {
final beneficiary = beneficiaries[index]; return Center(
return ListTile( child: Text(AppLocalizations.of(context).noBeneficiaryFound));
leading: const CircleAvatar( }
backgroundColor: Colors.blue, child: Text('A')), return ListView.builder(
title: Text(beneficiary['name']!), itemCount: _beneficiaries.length,
subtitle: Text(beneficiary['bank']!), itemBuilder: (context, index) {
trailing: IconButton( final item = _beneficiaries[index];
icon: const Icon(Symbols.delete_forever, color: Colors.red), return ListTile(
onPressed: () { leading: CircleAvatar(
// Delete action radius: 24,
}, backgroundColor: Colors.transparent,
child: getBankLogo(item.bankName, context),
),
title: Text(item.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(item.accountNo),
if (item.bankName != null && item.bankName!.isNotEmpty)
Text(
item.bankName!,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => BeneficiaryDetailsScreen(beneficiary: item),
), ),
); );
}, },
), );
},
);
}
@override
Widget build(BuildContext context) {
String customerName = widget.customerName;
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).beneficiaries),
), ),
body: _isLoading ? _buildShimmerList() : _buildBeneficiaryList(),
floatingActionButton: Padding( floatingActionButton: Padding(
padding: const EdgeInsets.only(bottom: 8.0), padding: const EdgeInsets.only(bottom: 8.0),
child: FloatingActionButton( child: FloatingActionButton(
onPressed: () { onPressed: () {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => const AddBeneficiaryScreen())); builder: (context) =>
AddBeneficiaryScreen(customerName: customerName),
),
);
}, },
backgroundColor: Colors.grey[300],
foregroundColor: Colors.blue[900],
elevation: 5, elevation: 5,
child: const Icon(Icons.add), child: const Icon(Icons.add),
), ),

View File

@@ -1,8 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
class BlockCardScreen extends StatefulWidget { class BlockCardScreen extends StatefulWidget {
const BlockCardScreen({super.key}); const BlockCardScreen({super.key});
@@ -42,7 +40,7 @@ class _BlockCardScreen extends State<BlockCardScreen> {
onPressed: () { onPressed: () {
// Just close the SnackBar // Just close the SnackBar
}, },
textColor: Colors.white, textColor: Theme.of(context).dialogBackgroundColor,
), ),
backgroundColor: Colors.black, backgroundColor: Colors.black,
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
@@ -56,32 +54,12 @@ class _BlockCardScreen extends State<BlockCardScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).blockCard, AppLocalizations.of(context).blockCard,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(10.0), padding: const EdgeInsets.all(10.0),
@@ -94,14 +72,14 @@ class _BlockCardScreen extends State<BlockCardScreen> {
controller: _cardController, controller: _cardController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).cardNumber, labelText: AppLocalizations.of(context).cardNumber,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -119,14 +97,14 @@ class _BlockCardScreen extends State<BlockCardScreen> {
controller: _cvvController, controller: _cvvController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).cvv, labelText: AppLocalizations.of(context).cvv,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -146,15 +124,15 @@ class _BlockCardScreen extends State<BlockCardScreen> {
onTap: _pickExpiryDate, onTap: _pickExpiryDate,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).expiryDate, labelText: AppLocalizations.of(context).expiryDate,
suffixIcon: Icon(Icons.calendar_today), suffixIcon: const Icon(Icons.calendar_today),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -170,15 +148,15 @@ class _BlockCardScreen extends State<BlockCardScreen> {
controller: _phoneController, controller: _phoneController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).phone, labelText: AppLocalizations.of(context).phone,
prefixIcon: Icon(Icons.phone), prefixIcon: const Icon(Icons.phone),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -198,8 +176,9 @@ class _BlockCardScreen extends State<BlockCardScreen> {
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.blue[900], backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white, foregroundColor:
Theme.of(context).scaffoldBackgroundColor,
), ),
child: Text(AppLocalizations.of(context).block), child: Text(AppLocalizations.of(context).block),
), ),

View File

@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
class CardDetailsScreen extends StatelessWidget {
const CardDetailsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My Cards"),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: const [
CardTile(
cardNumber: "**** **** **** 1234",
cardNetwork: "VISA",
cardType: "Debit Card",
validFrom: "01/22",
validTo: "01/27",
),
SizedBox(height: 16),
CardTile(
cardNumber: "**** **** **** 5678",
cardNetwork: "Mastercard",
cardType: "Debit Card",
validFrom: "07/21",
validTo: "07/26",
),
],
),
),
);
}
}
class CardTile extends StatelessWidget {
final String cardNumber;
final String cardNetwork;
final String cardType;
final String validFrom;
final String validTo;
const CardTile({
super.key,
required this.cardNumber,
required this.cardNetwork,
required this.cardType,
required this.validFrom,
required this.validTo,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
gradient: const LinearGradient(
colors: [Colors.blue, Colors.indigo],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: const [
BoxShadow(
color: Colors.black26,
blurRadius: 8,
spreadRadius: 2,
offset: Offset(2, 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Top row: Logo + Bank name
Row(
children: [
Image.asset(
'assets/images/logo.png',
width: 40,
height: 40,
),
const SizedBox(width: 8),
const Text(
"Kangra Central Co-operative Bank",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
),
const SizedBox(height: 24),
// Card number (masked)
Text(
cardNumber,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
letterSpacing: 3,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 16),
// Validity
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("VALID FROM",
style: TextStyle(color: Colors.white70, fontSize: 10)),
Text(
validFrom,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("VALID UPTO",
style: TextStyle(color: Colors.white70, fontSize: 10)),
Text(
validTo,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
cardNetwork,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
Text(
cardType,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
),
),
],
),
],
),
],
),
);
}
}

View File

@@ -1,9 +1,11 @@
// ignore_for_file: unused_import
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:kmobile/features/card/screens/block_card_screen.dart'; import 'package:kmobile/features/card/screens/block_card_screen.dart';
import 'package:kmobile/features/card/screens/card_details_screen.dart';
import 'package:kmobile/features/card/screens/card_pin_change_details_screen.dart'; import 'package:kmobile/features/card/screens/card_pin_change_details_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class CardManagementScreen extends StatefulWidget { class CardManagementScreen extends StatefulWidget {
const CardManagementScreen({super.key}); const CardManagementScreen({super.key});
@@ -15,92 +17,105 @@ class CardManagementScreen extends StatefulWidget {
class _CardManagementScreen extends State<CardManagementScreen> { class _CardManagementScreen extends State<CardManagementScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
title: Text( title: Text(
AppLocalizations.of(context).cardManagement, AppLocalizations.of(context).cardManagement,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), ),
centerTitle: false,
),
body: ListView(
children: [
CardManagementTile(
icon: Symbols.add,
label: AppLocalizations.of(context).applyDebitCard,
onTap: () {},
disabled: true, // Add this
), ),
centerTitle: false, const Divider(height: 1),
actions: [ CardManagementTile(
Padding( icon: Symbols.remove_moderator,
padding: const EdgeInsets.only(right: 10.0), label: AppLocalizations.of(context).blockUnblockCard,
child: CircleAvatar( onTap: () {
backgroundColor: Colors.grey[200], Navigator.push(
radius: 20, context,
child: SvgPicture.asset( MaterialPageRoute(
'assets/images/avatar_male.svg', builder: (context) => const BlockCardScreen(),
width: 40, ),
height: 40, );
fit: BoxFit.cover, },
), disabled: true,
), ),
), const Divider(height: 1),
], CardManagementTile(
), icon: Symbols.password_2,
body: ListView( label: AppLocalizations.of(context).changeCardPin,
children: [ onTap: () {
CardManagementTile( Navigator.push(
icon: Symbols.add, context,
label: AppLocalizations.of(context).applyDebitCard, MaterialPageRoute(
onTap: () {}, builder: (context) => const CardPinChangeDetailsScreen(),
), ),
const Divider( );
height: 1, },
), disabled: true,
CardManagementTile( ),
icon: Symbols.remove_moderator, const Divider(height: 1),
label: AppLocalizations.of(context).blockUnblockCard, CardManagementTile(
onTap: () { icon: Symbols.payment_card,
Navigator.push( label: AppLocalizations.of(context).viewCardDeatils,
context, onTap: () {
MaterialPageRoute( Navigator.push(
builder: (context) => const BlockCardScreen())); context,
}, MaterialPageRoute(
), builder: (context) => const CardDetailsScreen(),
const Divider( ),
height: 1, );
), },
CardManagementTile( disabled: true,
icon: Symbols.password_2, ),
label: AppLocalizations.of(context).changeCardPin, const Divider(height: 1),
onTap: () { ],
Navigator.push( ),
context, );
MaterialPageRoute( }
builder: (context) =>
const CardPinChangeDetailsScreen()));
},
),
const Divider(
height: 1,
),
],
),
);
}
} }
class CardManagementTile extends StatelessWidget { class CardManagementTile extends StatelessWidget {
final IconData icon; final IconData icon;
final String label; final String label;
final VoidCallback onTap; final VoidCallback onTap;
final bool disabled;
const CardManagementTile({ const CardManagementTile({
super.key, super.key,
required this.icon, required this.icon,
required this.label, required this.label,
required this.onTap, required this.onTap,
this.disabled = false,
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListTile( return ListTile(
leading: Icon(icon), leading: Icon(
title: Text(label), icon,
trailing: const Icon(Symbols.arrow_right, size: 20), color: disabled ? theme.disabledColor : null,
onTap: onTap, ),
title: Text(
label,
style: TextStyle(
color: disabled ? theme.disabledColor : null,
),
),
trailing: Icon(
Symbols.arrow_right,
size: 20,
color: disabled ? theme.disabledColor : null,
),
onTap: disabled ? null : onTap,
); );
} }
} }

View File

@@ -1,9 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:kmobile/features/card/screens/card_pin_set_screen.dart'; import 'package:kmobile/features/card/screens/card_pin_set_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class CardPinChangeDetailsScreen extends StatefulWidget { class CardPinChangeDetailsScreen extends StatefulWidget {
const CardPinChangeDetailsScreen({super.key}); const CardPinChangeDetailsScreen({super.key});
@@ -46,32 +44,12 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).cardDetails, AppLocalizations.of(context).cardDetails,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(10.0), padding: const EdgeInsets.all(10.0),
@@ -84,14 +62,14 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
controller: _cardController, controller: _cardController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).cardNumber, labelText: AppLocalizations.of(context).cardNumber,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -109,14 +87,14 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
controller: _cvvController, controller: _cvvController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).cvv, labelText: AppLocalizations.of(context).cvv,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -136,15 +114,15 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
onTap: _pickExpiryDate, onTap: _pickExpiryDate,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).expiryDate, labelText: AppLocalizations.of(context).expiryDate,
suffixIcon: Icon(Icons.calendar_today), suffixIcon: const Icon(Icons.calendar_today),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -160,15 +138,15 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
controller: _phoneController, controller: _phoneController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).phone, labelText: AppLocalizations.of(context).phone,
prefixIcon: Icon(Icons.phone), prefixIcon: const Icon(Icons.phone),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -188,8 +166,9 @@ class _CardPinChangeDetailsScreen extends State<CardPinChangeDetailsScreen> {
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.blue[900], backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white, foregroundColor:
Theme.of(context).scaffoldBackgroundColor,
), ),
child: Text(AppLocalizations.of(context).next), child: Text(AppLocalizations.of(context).next),
), ),

View File

@@ -1,7 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import '../../../l10n/app_localizations.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class CardPinSetScreen extends StatefulWidget { class CardPinSetScreen extends StatefulWidget {
const CardPinSetScreen({super.key}); const CardPinSetScreen({super.key});
@@ -25,7 +23,7 @@ class _CardPinSetScreen extends State<CardPinSetScreen> {
onPressed: () { onPressed: () {
// Just close the SnackBar // Just close the SnackBar
}, },
textColor: Colors.white, textColor: Theme.of(context).dialogBackgroundColor,
), ),
backgroundColor: Colors.black, backgroundColor: Colors.black,
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
@@ -46,32 +44,12 @@ class _CardPinSetScreen extends State<CardPinSetScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).cardPin, AppLocalizations.of(context).cardPin,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
@@ -84,14 +62,14 @@ class _CardPinSetScreen extends State<CardPinSetScreen> {
obscureText: true, obscureText: true,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).enterNewPin, labelText: AppLocalizations.of(context).enterNewPin,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -113,14 +91,14 @@ class _CardPinSetScreen extends State<CardPinSetScreen> {
obscureText: true, obscureText: true,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).enterAgain, labelText: AppLocalizations.of(context).enterAgain,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Colors.black),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(color: Colors.black, width: 2),
), ),
), ),
@@ -143,8 +121,9 @@ class _CardPinSetScreen extends State<CardPinSetScreen> {
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.blue[900], backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white, foregroundColor:
Theme.of(context).scaffoldBackgroundColor,
), ),
child: Text(AppLocalizations.of(context).submit), child: Text(AppLocalizations.of(context).submit),
), ),

View File

@@ -1,8 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:kmobile/features/enquiry/screens/enquiry_screen.dart'; import 'package:kmobile/features/enquiry/screens/enquiry_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class ChequeManagementScreen extends StatefulWidget { class ChequeManagementScreen extends StatefulWidget {
const ChequeManagementScreen({super.key}); const ChequeManagementScreen({super.key});
@@ -16,32 +15,12 @@ class _ChequeManagementScreen extends State<ChequeManagementScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).chequeManagement, AppLocalizations.of(context).chequeManagement,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), style:
const TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: ListView( body: ListView(
children: [ children: [
@@ -51,54 +30,42 @@ class _ChequeManagementScreen extends State<ChequeManagementScreen> {
label: AppLocalizations.of(context).requestChequeBook, label: AppLocalizations.of(context).requestChequeBook,
onTap: () {}, onTap: () {},
), ),
const Divider( const Divider(height: 1),
height: 1,
),
ChequeManagementTile( ChequeManagementTile(
icon: Symbols.data_alert, icon: Symbols.data_alert,
label: AppLocalizations.of(context).enquiry, label: AppLocalizations.of(context).enquiry,
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(builder: (context) => const EnquiryScreen()),
builder: (context) => const EnquiryScreen())); );
}, },
), ),
const Divider( const Divider(height: 1),
height: 1,
),
ChequeManagementTile( ChequeManagementTile(
icon: Symbols.approval_delegation, icon: Symbols.approval_delegation,
label: AppLocalizations.of(context).chequeDeposit, label: AppLocalizations.of(context).chequeDeposit,
onTap: () {}, onTap: () {},
), ),
const Divider( const Divider(height: 1),
height: 1,
),
ChequeManagementTile( ChequeManagementTile(
icon: Symbols.front_hand, icon: Symbols.front_hand,
label: AppLocalizations.of(context).stopCheque, label: AppLocalizations.of(context).stopCheque,
onTap: () {}, onTap: () {},
), ),
const Divider( const Divider(height: 1),
height: 1,
),
ChequeManagementTile( ChequeManagementTile(
icon: Symbols.cancel_presentation, icon: Symbols.cancel_presentation,
label: AppLocalizations.of(context).revokeStop, label: AppLocalizations.of(context).revokeStop,
onTap: () {}, onTap: () {},
), ),
const Divider( const Divider(height: 1),
height: 1,
),
ChequeManagementTile( ChequeManagementTile(
icon: Symbols.payments, icon: Symbols.payments,
label: AppLocalizations.of(context).positivePay, label: AppLocalizations.of(context).positivePay,
onTap: () {}, onTap: () {},
), ),
const Divider( const Divider(height: 1),
height: 1,
),
], ],
), ),
); );

View File

@@ -1,8 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:kmobile/data/models/user.dart'; import 'package:kmobile/data/models/user.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class CustomerInfoScreen extends StatefulWidget { class CustomerInfoScreen extends StatefulWidget {
final User user; final User user;
@@ -16,97 +15,85 @@ class _CustomerInfoScreenState extends State<CustomerInfoScreen> {
late final User user = widget.user; late final User user = widget.user;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(
icon: const Icon(Symbols.arrow_back_ios_new), AppLocalizations.of(context)
onPressed: () { .customerInfo
Navigator.pop(context); .replaceFirst(RegExp('\n'), ''),
}, ),
), ),
title: Text( body: SingleChildScrollView(
AppLocalizations.of(context).kMobile, physics: const AlwaysScrollableScrollPhysics(),
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), child: Padding(
), padding: const EdgeInsets.all(16.0),
actions: [ child: SafeArea(
Padding( child: Center(
padding: const EdgeInsets.only(right: 10.0), child: Column(
child: CircleAvatar( children: [
backgroundColor: Colors.grey[200], const SizedBox(height: 30),
radius: 20, CircleAvatar(
child: SvgPicture.asset( radius: 50,
'assets/images/avatar_male.svg', child: SvgPicture.asset(
width: 100, 'assets/images/avatar_male.svg',
height: 100, width: 150,
fit: BoxFit.cover, height: 150,
), fit: BoxFit.cover,
),
),
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Text(
user.name ?? '',
style: TextStyle(
fontSize: 20,
color: theme.colorScheme.onSurface,
fontWeight: FontWeight.w500,
),
),
),
Text(
'${AppLocalizations.of(context).cif}: ${user.cifNumber ?? 'N/A'}',
style: TextStyle(
fontSize: 16,
color: theme.colorScheme.onSurfaceVariant),
),
const SizedBox(height: 30),
InfoField(
label: AppLocalizations.of(context).activeAccounts,
value: user.activeAccounts?.toString() ?? '6',
),
InfoField(
label: AppLocalizations.of(context).mobileNumber,
value: user.mobileNo ?? 'N/A',
),
InfoField(
label: AppLocalizations.of(context).dateOfBirth,
value: (user.dateOfBirth != null &&
user.dateOfBirth!.length == 8)
? '${user.dateOfBirth!.substring(0, 2)}-${user.dateOfBirth!.substring(2, 4)}-${user.dateOfBirth!.substring(4, 8)}'
: 'N/A',
), // Replace with DOB if available
InfoField(
label: AppLocalizations.of(context).branchCode,
value: user.branchId ?? 'N/A',
),
InfoField(
label: AppLocalizations.of(context).branchAddress,
value: user.address ?? 'N/A',
), // Replace with Aadhar if available
InfoField(
label: AppLocalizations.of(context).primaryId,
value: user.primaryId ?? 'N/A',
), // Replace with PAN if available
],
), ),
), ),
], ),
), ),
body: SingleChildScrollView( ),
physics: const AlwaysScrollableScrollPhysics(), );
child: Padding(
padding: const EdgeInsets.all(16.0),
child: SafeArea(
child: Center(
child: Column(
children: [
const SizedBox(height: 30),
CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 50,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 150,
height: 150,
fit: BoxFit.cover,
),
),
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Text(
user.name ?? '',
style: const TextStyle(
fontSize: 20,
color: Colors.black,
fontWeight: FontWeight.w500),
),
),
Text(
'${AppLocalizations.of(context).cif}: ${user.cifNumber ?? 'N/A'}',
style:
const TextStyle(fontSize: 16, color: Colors.grey),
),
SizedBox(height: 30),
InfoField(
label: AppLocalizations.of(context).activeAccounts,
value: user.activeAccounts?.toString() ?? '6'),
InfoField(
label: AppLocalizations.of(context).mobileNumber,
value: user.mobileNo ?? 'N/A'),
InfoField(
label: AppLocalizations.of(context).dateOfBirth,
value: (user.dateOfBirth != null &&
user.dateOfBirth!.length == 8)
? '${user.dateOfBirth!.substring(0, 2)}-${user.dateOfBirth!.substring(2, 4)}-${user.dateOfBirth!.substring(4, 8)}'
: 'N/A'), // Replace with DOB if available
InfoField(
label: AppLocalizations.of(context).branchCode,
value: user.branchId ?? 'N/A'),
InfoField(
label: AppLocalizations.of(context).branchAddress,
value: user.address ??
'N/A'), // Replace with Aadhar if available
InfoField(
label: AppLocalizations.of(context).primaryId,
value: user.primaryId ??
'N/A'), // Replace with PAN if available
],
),
),
),
)));
} }
} }
@@ -118,6 +105,7 @@ class InfoField extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container( return Container(
width: double.infinity, width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8), margin: const EdgeInsets.symmetric(vertical: 8),
@@ -126,19 +114,16 @@ class InfoField extends StatelessWidget {
children: [ children: [
Text( Text(
label, label,
style: const TextStyle( style: TextStyle(
fontSize: 15, fontSize: 15,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
color: Colors.black87, color: theme.colorScheme.onSurfaceVariant,
), ),
), ),
const SizedBox(height: 3), const SizedBox(height: 3),
Text( Text(
value, value,
style: const TextStyle( style: TextStyle(fontSize: 16, color: theme.colorScheme.onSurface),
fontSize: 16,
color: Colors.black,
),
), ),
], ],
), ),

View File

@@ -6,12 +6,13 @@ import 'package:kmobile/data/repositories/transaction_repository.dart';
import 'package:kmobile/di/injection.dart'; import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/accounts/screens/account_info_screen.dart'; import 'package:kmobile/features/accounts/screens/account_info_screen.dart';
import 'package:kmobile/features/accounts/screens/account_statement_screen.dart'; import 'package:kmobile/features/accounts/screens/account_statement_screen.dart';
import 'package:kmobile/features/accounts/screens/transaction_details_screen.dart';
import 'package:kmobile/features/auth/controllers/auth_cubit.dart'; import 'package:kmobile/features/auth/controllers/auth_cubit.dart';
import 'package:kmobile/features/auth/controllers/auth_state.dart'; import 'package:kmobile/features/auth/controllers/auth_state.dart';
import 'package:kmobile/features/customer_info/screens/customer_info_screen.dart'; import 'package:kmobile/features/customer_info/screens/customer_info_screen.dart';
import 'package:kmobile/features/beneficiaries/screens/manage_beneficiaries_screen.dart'; import 'package:kmobile/features/beneficiaries/screens/manage_beneficiaries_screen.dart';
import 'package:kmobile/features/enquiry/screens/enquiry_screen.dart'; import 'package:kmobile/features/enquiry/screens/enquiry_screen.dart';
import 'package:kmobile/features/fund_transfer/screens/fund_transfer_beneficiary_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/fund_transfer_screen.dart';
import 'package:kmobile/features/profile/profile_screen.dart'; import 'package:kmobile/features/profile/profile_screen.dart';
import 'package:kmobile/features/quick_pay/screens/quick_pay_screen.dart'; import 'package:kmobile/features/quick_pay/screens/quick_pay_screen.dart';
import 'package:kmobile/security/secure_storage.dart'; import 'package:kmobile/security/secure_storage.dart';
@@ -20,7 +21,7 @@ import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'package:shimmer/shimmer.dart'; import 'package:shimmer/shimmer.dart';
import 'package:kmobile/data/models/transaction.dart'; import 'package:kmobile/data/models/transaction.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class DashboardScreen extends StatefulWidget { class DashboardScreen extends StatefulWidget {
const DashboardScreen({super.key}); const DashboardScreen({super.key});
@@ -57,11 +58,18 @@ class _DashboardScreenState extends State<DashboardScreen> {
setState(() => _transactions = fiveTxns); setState(() => _transactions = fiveTxns);
} catch (e) { } catch (e) {
log(accountNo, error: e); log(accountNo, error: e);
ScaffoldMessenger.of(context).showSnackBar(SnackBar( if (!mounted) return;
content: ScaffoldMessenger.of(context).showSnackBar(
Text(AppLocalizations.of(context).failedToLoad(e.toString())))); SnackBar(
content: Text(
AppLocalizations.of(context).failedToLoad(e.toString()),
),
),
);
} finally { } finally {
setState(() => _txLoading = false); if (mounted) {
setState(() => _txLoading = false);
}
} }
} }
@@ -73,9 +81,13 @@ class _DashboardScreenState extends State<DashboardScreen> {
// Call your AuthCubit or repository to refresh user/accounts data // Call your AuthCubit or repository to refresh user/accounts data
await context.read<AuthCubit>().refreshUserData(); await context.read<AuthCubit>().refreshUserData();
} catch (e) { } catch (e) {
if (!context.mounted) {
return;
}
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
/*const*/ SnackBar( SnackBar(
content: Text(AppLocalizations.of(context).failedToRefresh)), content: Text(AppLocalizations.of(context).failedToRefresh),
),
); );
} }
setState(() { setState(() {
@@ -84,14 +96,12 @@ class _DashboardScreenState extends State<DashboardScreen> {
} }
Widget _buildBalanceShimmer() { Widget _buildBalanceShimmer() {
final theme = Theme.of(context);
return Shimmer.fromColors( return Shimmer.fromColors(
baseColor: Colors.white.withOpacity(0.7), baseColor: theme.colorScheme.primary,
highlightColor: Colors.white.withOpacity(0.3), highlightColor: theme.colorScheme.onPrimary,
child: Container( child: Container(
width: 100, width: 200, height: 42, color: theme.scaffoldBackgroundColor),
height: 32,
color: Colors.white,
),
); );
} }
@@ -106,7 +116,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
'dr.', 'dr.',
'shri', 'shri',
'smt.', 'smt.',
'kumari' 'kumari',
]; ];
String processed = name.trim().toLowerCase(); String processed = name.trim().toLowerCase();
for (final title in titles) { for (final title in titles) {
@@ -128,6 +138,8 @@ class _DashboardScreenState extends State<DashboardScreen> {
switch (accountType.toLowerCase()) { switch (accountType.toLowerCase()) {
case 'sa': case 'sa':
return AppLocalizations.of(context).savingsAccount; return AppLocalizations.of(context).savingsAccount;
case 'sb':
return AppLocalizations.of(context).savingsAccount;
case 'ln': case 'ln':
return AppLocalizations.of(context).loanAccount; return AppLocalizations.of(context).loanAccount;
case 'td': case 'td':
@@ -151,6 +163,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
TextButton( TextButton(
onPressed: () async { onPressed: () async {
await storage.write('biometric_prompt_shown', 'true'); await storage.write('biometric_prompt_shown', 'true');
if (!mounted) return;
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
child: Text(AppLocalizations.of(context).later), child: Text(AppLocalizations.of(context).later),
@@ -159,6 +172,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
onPressed: () async { onPressed: () async {
final auth = LocalAuthentication(); final auth = LocalAuthentication();
final canCheck = await auth.canCheckBiometrics; final canCheck = await auth.canCheckBiometrics;
if (!mounted) return;
bool ok = false; bool ok = false;
if (canCheck) { if (canCheck) {
ok = await auth.authenticate( ok = await auth.authenticate(
@@ -169,6 +183,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
await storage.write('biometric_enabled', 'true'); await storage.write('biometric_enabled', 'true');
} }
await storage.write('biometric_prompt_shown', 'true'); await storage.write('biometric_prompt_shown', 'true');
if (!mounted) return;
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
child: Text(AppLocalizations.of(context).enable), child: Text(AppLocalizations.of(context).enable),
@@ -180,6 +195,7 @@ class _DashboardScreenState extends State<DashboardScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return BlocListener<AuthCubit, AuthState>( return BlocListener<AuthCubit, AuthState>(
listener: (context, state) async { listener: (context, state) async {
if (state is Authenticated && !_biometricPromptShown) { if (state is Authenticated && !_biometricPromptShown) {
@@ -192,16 +208,18 @@ class _DashboardScreenState extends State<DashboardScreen> {
} }
}, },
child: Scaffold( child: Scaffold(
backgroundColor: const Color(0xfff5f9fc), backgroundColor: theme.scaffoldBackgroundColor,
appBar: AppBar( appBar: AppBar(
backgroundColor: const Color(0xfff5f9fc), backgroundColor: theme.scaffoldBackgroundColor,
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
title: Text( title: Text(
AppLocalizations.of(context).kMobile, AppLocalizations.of(context).kconnect,
style: TextStyle( style: TextStyle(
color: Theme.of(context).primaryColor, color: theme.colorScheme.primary,
fontWeight: FontWeight.w500), fontWeight: FontWeight.w700,
),
), ),
centerTitle: true,
actions: [ actions: [
Padding( Padding(
padding: const EdgeInsets.only(right: 10.0), padding: const EdgeInsets.only(right: 10.0),
@@ -211,7 +229,8 @@ class _DashboardScreenState extends State<DashboardScreen> {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => const ProfileScreen()), builder: (context) => const ProfileScreen(),
),
); );
}, },
child: CircleAvatar( child: CircleAvatar(
@@ -228,345 +247,437 @@ class _DashboardScreenState extends State<DashboardScreen> {
), ),
], ],
), ),
body: BlocBuilder<AuthCubit, AuthState>(builder: (context, state) { body: BlocBuilder<AuthCubit, AuthState>(
if (state is AuthLoading || state is AuthInitial) { builder: (context, state) {
return const Center(child: CircularProgressIndicator()); if (state is AuthLoading || state is AuthInitial) {
} return const Center(child: CircularProgressIndicator());
if (state is Authenticated) {
final users = state.users;
final currAccount = users[selectedAccountIndex];
// firsttime load
if (!_txInitialized) {
_txInitialized = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadTransactions(currAccount.accountNo!);
});
} }
final firstName = getProcessedFirstName(currAccount.name); if (state is Authenticated) {
final users = state.users;
final currAccount = users[selectedAccountIndex];
// firsttime load
if (!_txInitialized) {
_txInitialized = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadTransactions(currAccount.accountNo!);
});
}
final firstName = getProcessedFirstName(currAccount.name);
return SingleChildScrollView( return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0), padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.only(left: 8.0), padding: const EdgeInsets.only(left: 8.0),
child: Text( child: Text(
"${AppLocalizations.of(context).hi} $firstName", "${AppLocalizations.of(context).hi} $firstName!",
style: GoogleFonts.montserrat().copyWith( style: GoogleFonts.baumans().copyWith(
fontSize: 25, fontSize: 20,
color: Theme.of(context).primaryColorDark, color: theme.colorScheme.primary,
fontWeight: FontWeight.w700), fontWeight: FontWeight.w700,
),
),
), ),
), const SizedBox(height: 16),
const SizedBox(height: 16),
// Account Info Card // Account Info Card
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 18, vertical: 10), horizontal: 18,
decoration: BoxDecoration( vertical: 10,
color: Theme.of(context).primaryColor, ),
borderRadius: BorderRadius.circular(16), decoration: BoxDecoration(
), color: Color(0xFF01A04C),
child: Column( borderRadius: BorderRadius.circular(16),
crossAxisAlignment: CrossAxisAlignment.start, ),
children: [ child: Column(
Row( crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(AppLocalizations.of(context).accountNumber, Row(
children: [
Text(
"${getFullAccountType(currAccount.accountType)}: ",
style: TextStyle( style: TextStyle(
color: Colors.white, fontSize: 12)), color: theme.colorScheme.onPrimary,
DropdownButton<int>( fontSize: 18,
value: selectedAccountIndex, fontWeight: FontWeight.w700,
dropdownColor: Theme.of(context).primaryColor, ),
underline: const SizedBox(), ),
icon: const Icon(Icons.keyboard_arrow_down), DropdownButton<int>(
iconEnabledColor: Colors.white, value: selectedAccountIndex,
style: const TextStyle( dropdownColor: theme.colorScheme.primary,
color: Colors.white, fontSize: 14), underline: const SizedBox(),
items: List.generate(users.length, (index) { icon: const Icon(Icons.keyboard_arrow_down),
return DropdownMenuItem<int>( iconEnabledColor: theme.colorScheme.onPrimary,
value: index, style: TextStyle(
child: Text( color: theme.colorScheme.onPrimary,
users[index].accountNo ?? 'N/A', fontSize: 18,
style: const TextStyle( ),
color: Colors.white, fontSize: 14), items: List.generate(users.length, (index) {
), return DropdownMenuItem<int>(
); value: index,
}), child: Text(
onChanged: (int? newIndex) async { users[index].accountNo ?? 'N/A',
if (newIndex == null || style: TextStyle(
newIndex == selectedAccountIndex) { color: theme.colorScheme.onPrimary,
return; fontSize: 18,
} fontWeight: FontWeight.w700,
if (isBalanceLoading) return;
if (isVisible) {
setState(() {
isBalanceLoading = true;
selectedAccountIndex = newIndex;
});
await Future.delayed(
const Duration(milliseconds: 200));
setState(() {
isBalanceLoading = false;
});
} else {
setState(() {
selectedAccountIndex = newIndex;
});
}
await _loadTransactions(
users[newIndex].accountNo!);
},
),
const Spacer(),
IconButton(
icon: isRefreshing
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
), ),
) ),
: const Icon(Icons.refresh, );
color: Colors.white), }),
onPressed: isRefreshing onChanged: (int? newIndex) async {
? null if (newIndex == null ||
: () => _refreshAccountData(context), newIndex == selectedAccountIndex) {
tooltip: 'Refresh', return;
), }
], if (isBalanceLoading) return;
), if (isVisible) {
Text( setState(() {
getFullAccountType(currAccount.accountType), isBalanceLoading = true;
style: const TextStyle( selectedAccountIndex = newIndex;
color: Colors.white, fontSize: 16), });
), await Future.delayed(
const SizedBox(height: 4), const Duration(milliseconds: 200),
Row( );
mainAxisAlignment: MainAxisAlignment.start, setState(() {
children: [ isBalanceLoading = false;
const Text("", });
} else {
setState(() {
selectedAccountIndex = newIndex;
});
}
await _loadTransactions(
users[newIndex].accountNo!,
);
},
),
const Spacer(),
IconButton(
icon: isRefreshing
? SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: theme.colorScheme.onPrimary,
strokeWidth: 2,
),
)
: Icon(
Symbols.refresh,
color: theme.colorScheme.onPrimary,
),
onPressed: isRefreshing
? null
: () => _refreshAccountData(context),
tooltip: 'Refresh',
),
],
),
const SizedBox(height: 15),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"",
style: TextStyle( style: TextStyle(
color: Colors.white, color: theme.colorScheme.onPrimary,
fontSize: 40, fontSize: 40,
fontWeight: FontWeight.w700)), fontWeight: FontWeight.w700,
isRefreshing || isBalanceLoading ),
? _buildBalanceShimmer() ),
: Text( isRefreshing || isBalanceLoading
isVisible ? _buildBalanceShimmer()
? currAccount.currentBalance ?? '0.00' : Text(
: '********', isVisible
style: const TextStyle( ? currAccount.currentBalance ??
color: Colors.white, '0.00'
: '*****',
style: TextStyle(
color: theme.colorScheme.onPrimary,
fontSize: 40, fontSize: 40,
fontWeight: FontWeight.w700)), fontWeight: FontWeight.w700,
const Spacer(), ),
InkWell( ),
onTap: () async { const Spacer(),
if (isBalanceLoading) return; InkWell(
if (!isVisible) { onTap: () async {
setState(() { if (isBalanceLoading) return;
isBalanceLoading = true; if (!isVisible) {
}); setState(() {
await Future.delayed( isBalanceLoading = true;
const Duration(seconds: 1)); });
setState(() { await Future.delayed(
isVisible = true; const Duration(seconds: 1),
isBalanceLoading = false; );
}); setState(() {
} else { isVisible = true;
setState(() { isBalanceLoading = false;
isVisible = false; });
}); } else {
} setState(() {
}, isVisible = false;
child: Icon( });
isVisible }
? Symbols.visibility_lock },
: Symbols.visibility, child: Padding(
color: Colors.white), padding: const EdgeInsets.all(8.0),
), child: Icon(
], isVisible
? Symbols.visibility_lock
: Symbols.visibility,
color: theme.scaffoldBackgroundColor,
weight: 800,
),
),
),
],
),
const SizedBox(height: 15),
],
),
),
const SizedBox(height: 18),
Text(
AppLocalizations.of(context).quickLinks,
style: const TextStyle(fontSize: 17),
),
const SizedBox(height: 16),
// Quick Links
GridView.count(
crossAxisCount: 4,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: [
_buildQuickLink(
Symbols.id_card,
AppLocalizations.of(context).customerInfo,
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CustomerInfoScreen(
user: users[selectedAccountIndex],
),
),
);
},
), ),
const SizedBox(height: 15), _buildQuickLink(
Symbols.currency_rupee,
AppLocalizations.of(context).quickPay,
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => QuickPayScreen(
debitAccount: currAccount.accountNo!,
),
),
);
},
),
_buildQuickLink(Symbols.send_money,
AppLocalizations.of(context).fundTransfer, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FundTransferScreen(
creditAccountNo:
users[selectedAccountIndex]
.accountNo!,
remitterName:
users[selectedAccountIndex]
.name!)));
}, disable: false),
_buildQuickLink(
Symbols.server_person,
AppLocalizations.of(context).accountInfo,
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AccountInfoScreen(
users: users,
selectedIndex: selectedAccountIndex,
),
),
);
},
),
_buildQuickLink(Symbols.receipt_long,
AppLocalizations.of(context).accountStatement,
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AccountStatementScreen(
accountNo: users[selectedAccountIndex]
.accountNo!,
balance: users[selectedAccountIndex]
.availableBalance!,
accountType: users[selectedAccountIndex]
.accountType!,
)));
}),
_buildQuickLink(Symbols.checkbook,
AppLocalizations.of(context).handleCheque, () {},
disable: true),
_buildQuickLink(Icons.group,
AppLocalizations.of(context).manageBeneficiary,
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ManageBeneficiariesScreen(
customerName: currAccount.name!)));
}, disable: false),
_buildQuickLink(Symbols.support_agent,
AppLocalizations.of(context).contactUs, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const EnquiryScreen()));
}),
], ],
), ),
), const SizedBox(height: 5),
const SizedBox(height: 18),
Text(
AppLocalizations.of(context).quickLinks,
style: TextStyle(fontSize: 17),
),
const SizedBox(height: 16),
// Quick Links // Recent Transactions
GridView.count( Text(
crossAxisCount: 4, AppLocalizations.of(context).recentTransactions,
shrinkWrap: true, style: const TextStyle(fontSize: 17),
physics: const NeverScrollableScrollPhysics(), ),
children: [ const SizedBox(height: 16),
_buildQuickLink(Symbols.id_card, if (_txLoading)
AppLocalizations.of(context).customerInfo, () { ..._buildTransactionShimmer()
Navigator.push( else if (_transactions.isNotEmpty)
context, ..._transactions.map(
MaterialPageRoute( (tx) => ListTile(
builder: (context) => CustomerInfoScreen(
user: users[selectedAccountIndex],
)));
}),
_buildQuickLink(Symbols.currency_rupee,
AppLocalizations.of(context).quickPay, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => QuickPayScreen(
debitAccount: currAccount.accountNo!)));
}),
_buildQuickLink(Symbols.send_money,
AppLocalizations.of(context).fundTransfer, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const FundTransferBeneficiaryScreen()));
}, disable: false),
_buildQuickLink(Symbols.server_person,
AppLocalizations.of(context).accountInfo, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AccountInfoScreen(
user: users[selectedAccountIndex])));
}),
_buildQuickLink(Symbols.receipt_long,
AppLocalizations.of(context).accountStatement, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AccountStatementScreen(
accountNo: users[selectedAccountIndex]
.accountNo!,
)));
}),
_buildQuickLink(Symbols.checkbook,
AppLocalizations.of(context).handleCheque, () {},
disable: false),
_buildQuickLink(Icons.group,
AppLocalizations.of(context).manageBeneficiary, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const ManageBeneficiariesScreen()));
}, disable: false),
_buildQuickLink(Symbols.support_agent,
AppLocalizations.of(context).contactUs, () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const EnquiryScreen()));
}),
],
),
const SizedBox(height: 5),
// Recent Transactions
Text(
AppLocalizations.of(context).recentTransactions,
style: TextStyle(fontSize: 17),
),
const SizedBox(height: 16),
if (_txLoading)
..._buildTransactionShimmer()
else if (_transactions.isNotEmpty)
..._transactions.map((tx) => ListTile(
leading: Icon( leading: Icon(
tx.type == 'CR' tx.type == 'CR'
? Symbols.call_received ? Symbols.call_received
: Symbols.call_made, : Symbols.call_made,
color: color: tx.type == 'CR'
tx.type == 'CR' ? Colors.green : Colors.red, ? const Color(0xFF10BB10)
: theme.colorScheme.error,
), ),
title: Text( title: Text(
tx.date ?? '',
style: const TextStyle(fontSize: 15),
),
subtitle: Text(
tx.name != null tx.name != null
? (tx.name!.length > 18 ? (tx.name!.length > 18
? tx.name!.substring(0, 20) ? tx.name!.substring(0, 22)
: tx.name!) : tx.name!)
: '', : '',
style: const TextStyle(fontSize: 14), style: const TextStyle(fontSize: 12),
), ),
subtitle: Text(tx.date ?? '', trailing: Text(
style: const TextStyle(fontSize: 12)), "${tx.amount}",
trailing: Text("${tx.amount}", style: const TextStyle(fontSize: 17),
style: const TextStyle(fontSize: 16)), ),
)) onTap: () {
else Navigator.push(
Padding( context,
padding: const EdgeInsets.symmetric(vertical: 24.0), MaterialPageRoute(
child: Center( builder: (_) =>
child: Text( TransactionDetailsScreen(transaction: tx),
AppLocalizations.of(context).noTransactions, ),
style: TextStyle( );
fontSize: 16, },
color: Colors.grey[600], ),
)
else
Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Center(
child: Text(
AppLocalizations.of(context).noTransactions,
style: TextStyle(
fontSize: 16,
color: Theme.of(context).colorScheme.outline,
),
), ),
), ),
), ),
), ],
], ),
), ),
), );
}
return Center(
child: Text(AppLocalizations.of(context).somethingWentWrong),
); );
} },
return Center( ),
child: Text(AppLocalizations.of(context).somethingWentWrong));
}),
), ),
); );
} }
List<Widget> _buildTransactionShimmer() { List<Widget> _buildTransactionShimmer() {
final theme = Theme.of(context);
return List.generate(3, (i) { return List.generate(3, (i) {
return ListTile( return ListTile(
leading: Shimmer.fromColors( leading: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: const CircleAvatar(radius: 12, backgroundColor: Colors.white), child: CircleAvatar(
radius: 12, backgroundColor: theme.scaffoldBackgroundColor),
), ),
title: Shimmer.fromColors( title: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: Container(height: 10, width: 100, color: Colors.white), child: Container(
height: 10, width: 100, color: theme.scaffoldBackgroundColor),
), ),
subtitle: Shimmer.fromColors( subtitle: Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!, highlightColor: Colors.grey[100]!,
child: Container(height: 8, width: 60, color: Colors.white), child: Container(
height: 8, width: 60, color: theme.scaffoldBackgroundColor),
), ),
); );
}); });
} }
Widget _buildQuickLink(IconData icon, String label, VoidCallback onTap, Widget _buildQuickLink(
{bool disable = false}) { IconData icon,
String label,
VoidCallback onTap, {
bool disable = false,
}) {
final theme = Theme.of(context);
return InkWell( return InkWell(
onTap: disable ? null : onTap, onTap: disable ? null : onTap,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(icon, Icon(
size: 30, icon,
color: disable ? Colors.grey : Theme.of(context).primaryColor), size: 30,
color: disable
? theme.colorScheme.onSurface.withOpacity(0.3)
: theme.colorScheme.primary,
grade: 200,
weight: 700,
),
const SizedBox(height: 4), const SizedBox(height: 4),
Text(label, Text(
textAlign: TextAlign.center, label,
style: const TextStyle(fontSize: 13)), textAlign: TextAlign.center,
style: const TextStyle(fontSize: 13),
),
], ],
), ),
); );

View File

@@ -1,14 +1,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../accounts/models/account.dart'; import '../../accounts/models/account.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../../../l10n/app_localizations.dart';
class AccountCard extends StatelessWidget { class AccountCard extends StatelessWidget {
final Account account; final Account account;
const AccountCard({ const AccountCard({super.key, required this.account});
super.key,
required this.account,
});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -16,14 +13,7 @@ class AccountCard extends StatelessWidget {
width: 300, width: 300,
padding: const EdgeInsets.all(20), padding: const EdgeInsets.all(20),
decoration: BoxDecoration( decoration: BoxDecoration(
gradient: LinearGradient( color: Colors.white,
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).primaryColor.withBlue(200),
],
),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(
@@ -42,8 +32,8 @@ class AccountCard extends StatelessWidget {
children: [ children: [
Text( Text(
account.accountType, account.accountType,
style: const TextStyle( style: TextStyle(
color: Colors.white, color: Theme.of(context).colorScheme.onPrimary,
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
@@ -52,23 +42,21 @@ class AccountCard extends StatelessWidget {
account.accountType == 'Savings' account.accountType == 'Savings'
? Icons.savings ? Icons.savings
: Icons.account_balance, : Icons.account_balance,
color: Colors.white, color: Theme.of(context).colorScheme.onPrimary,
), ),
], ],
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
Text( Text(
account.accountNumber, account.accountNumber,
style: const TextStyle( style: TextStyle(
color: Colors.white70, color: Theme.of(context).colorScheme.onPrimary, fontSize: 16),
fontSize: 16,
),
), ),
const SizedBox(height: 30), const SizedBox(height: 30),
Text( Text(
'${account.currency} ${account.balance.toStringAsFixed(2)}', '${account.currency} ${account.balance.toStringAsFixed(2)}',
style: const TextStyle( style: TextStyle(
color: Colors.white, color: Theme.of(context).colorScheme.onPrimary,
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
@@ -77,12 +65,11 @@ class AccountCard extends StatelessWidget {
Text( Text(
AppLocalizations.of(context).availableBalance, AppLocalizations.of(context).availableBalance,
style: TextStyle( style: TextStyle(
color: Colors.white70, color: Theme.of(context).colorScheme.onPrimary, fontSize: 16),
fontSize: 12,
),
), ),
], ],
), ),
); );
} }
} }

View File

@@ -4,7 +4,7 @@ import '../../transactions/models/transaction.dart';
class TransactionListItem extends StatelessWidget { class TransactionListItem extends StatelessWidget {
final Transaction transaction; final Transaction transaction;
const TransactionListItem({ const TransactionListItem({
super.key, super.key,
required this.transaction, required this.transaction,
@@ -13,7 +13,7 @@ class TransactionListItem extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final bool isIncome = transaction.amount > 0; final bool isIncome = transaction.amount > 0;
return Card( return Card(
elevation: 0, elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 8), margin: const EdgeInsets.symmetric(vertical: 8),
@@ -25,7 +25,8 @@ class TransactionListItem extends StatelessWidget {
Container( Container(
padding: const EdgeInsets.all(10), padding: const EdgeInsets.all(10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: _getCategoryColor(transaction.category).withAlpha((0.1 * 255).toInt()), color: _getCategoryColor(transaction.category)
.withAlpha((0.1 * 255).toInt()),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
child: Icon( child: Icon(
@@ -34,7 +35,7 @@ class TransactionListItem extends StatelessWidget {
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
// Transaction details // Transaction details
Expanded( Expanded(
child: Column( child: Column(
@@ -48,7 +49,8 @@ class TransactionListItem extends StatelessWidget {
), ),
), ),
Text( Text(
DateFormat('MMM dd, yyyy • h:mm a').format(transaction.date), DateFormat('MMM dd, yyyy • h:mm a')
.format(transaction.date),
style: TextStyle( style: TextStyle(
color: Colors.grey[600], color: Colors.grey[600],
fontSize: 12, fontSize: 12,
@@ -57,7 +59,7 @@ class TransactionListItem extends StatelessWidget {
], ],
), ),
), ),
// Amount // Amount
Text( Text(
'${isIncome ? '+' : ''}${transaction.amount.toStringAsFixed(2)} USD', '${isIncome ? '+' : ''}${transaction.amount.toStringAsFixed(2)} USD',
@@ -106,4 +108,4 @@ class TransactionListItem extends StatelessWidget {
return Icons.category; return Icons.category;
} }
} }
} }

View File

@@ -1,8 +1,8 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class EnquiryScreen extends StatefulWidget { class EnquiryScreen extends StatefulWidget {
const EnquiryScreen({super.key}); const EnquiryScreen({super.key});
@@ -34,16 +34,20 @@ class _EnquiryScreen extends State<EnquiryScreen> {
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(role, style: const TextStyle(color: Colors.grey)), Text(role,
style: TextStyle(color: Theme.of(context).colorScheme.onSurface)),
const SizedBox(height: 4), const SizedBox(height: 4),
GestureDetector( GestureDetector(
onTap: () => _launchEmailAddress(email), onTap: () => _launchEmailAddress(email),
child: Text(email, style: const TextStyle(color: Colors.blue)), child: Text(email,
style: TextStyle(color: Theme.of(context).colorScheme.primary)),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
GestureDetector( GestureDetector(
onTap: () => _launchPhoneNumber(phone), onTap: () => _launchPhoneNumber(phone),
child: Text(phone, style: const TextStyle(color: Colors.blue)), child: Text(phone,
style:
TextStyle(color: Theme.of(context).scaffoldBackgroundColor)),
), ),
], ],
); );
@@ -53,32 +57,8 @@ class _EnquiryScreen extends State<EnquiryScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(AppLocalizations.of(context).enquiry),
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(
AppLocalizations.of(context).enquiry,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
@@ -86,26 +66,26 @@ class _EnquiryScreen extends State<EnquiryScreen> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// … existing Mail us / Call us / Write to us … // … existing Mail us / Call us / Write to us …
const SizedBox(height: 20), const SizedBox(height: 20),
Text(AppLocalizations.of(context).writeToUs, Text(
style: TextStyle(color: Colors.grey)), AppLocalizations.of(context).writeToUs,
),
const SizedBox(height: 4), const SizedBox(height: 4),
const Text( Text(
"complaint@kccb.in", "complaint@kccb.in",
style: TextStyle(color: Colors.blue), style: TextStyle(color: Theme.of(context).colorScheme.primary),
), ),
SizedBox(height: 20), const SizedBox(height: 20),
Text( Text(
AppLocalizations.of(context).keyContacts, AppLocalizations.of(context).keyContacts,
style: TextStyle( style: TextStyle(
fontSize: 17, fontSize: 17,
color: Theme.of(context).primaryColor, color: Theme.of(context).colorScheme.primary,
), ),
// horizontal line // horizontal line
), ),
Divider(color: Colors.grey[300]), Divider(color: Theme.of(context).colorScheme.outline),
const SizedBox(height: 16), const SizedBox(height: 16),
_buildContactItem( _buildContactItem(
AppLocalizations.of(context).chairman, AppLocalizations.of(context).chairman,

View File

@@ -0,0 +1,440 @@
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/api/services/neft_service.dart';
import 'package:kmobile/api/services/rtgs_service.dart';
import 'package:kmobile/api/services/imps_service.dart';
import 'package:kmobile/data/models/imps_transaction.dart';
import 'package:kmobile/widgets/bank_logos.dart';
import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/data/models/neft_transaction.dart';
import 'package:kmobile/data/models/payment_response.dart';
import 'package:kmobile/data/models/rtgs_transaction.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart';
import '../../../l10n/app_localizations.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/data/models/transfer.dart';
enum TransactionMode { neft, rtgs, imps }
class FundTransferAmountScreen extends StatefulWidget {
final String debitAccountNo;
final Beneficiary creditBeneficiary;
final String remitterName;
final bool isOwnBank;
const FundTransferAmountScreen({
super.key,
required this.debitAccountNo,
required this.creditBeneficiary,
required this.remitterName,
this.isOwnBank = false,
});
@override
State<FundTransferAmountScreen> createState() =>
_FundTransferAmountScreenState();
}
class _FundTransferAmountScreenState extends State<FundTransferAmountScreen> {
final _amountController = TextEditingController();
final _formKey = GlobalKey<FormState>();
TransactionMode _selectedMode = TransactionMode.neft;
@override
void dispose() {
_amountController.dispose();
super.dispose();
}
void _onProceed() {
if (_formKey.currentState!.validate()) {
final amount = double.tryParse(_amountController.text) ?? 0;
if (widget.isOwnBank) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TransactionPinScreen(
onPinCompleted: (pinScreenContext, tpin) async {
final transfer = Transfer(
fromAccount: widget.debitAccountNo,
toAccount: widget.creditBeneficiary.accountNo,
toAccountType: 'Savings', // Assuming 'SB' for savings
amount: _amountController.text,
tpin: tpin,
);
final paymentService = getIt<PaymentService>();
final paymentResponseFuture =
paymentService.processQuickPayWithinBank(transfer);
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: paymentResponseFuture),
),
);
},
),
),
);
} else {
if (_selectedMode == TransactionMode.rtgs && amount < 200000) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(AppLocalizations.of(context).invalidRtgs),
content: Text(AppLocalizations.of(context).invalidRtgsPopUp),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text(AppLocalizations.of(context).ok),
),
],
),
);
return; // Stop further execution
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TransactionPinScreen(
onPinCompleted: (pinScreenContext, tpin) async {
if (_selectedMode == TransactionMode.neft) {
final neftTx = NeftTransaction(
fromAccount: widget.debitAccountNo,
toAccount: widget.creditBeneficiary.accountNo,
amount: _amountController.text,
ifscCode: widget.creditBeneficiary.ifscCode,
remitterName: widget.remitterName,
beneficiaryName: widget.creditBeneficiary.name,
tpin: tpin,
);
final neftService = getIt<NeftService>();
final completer = Completer<PaymentResponse>();
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final neftResponse =
await neftService.processNeftTransaction(neftTx);
final paymentResponse = PaymentResponse(
isSuccess:
neftResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: neftTx.toAccount,
amount: neftTx.amount,
currency: 'INR',
utr: neftResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
String errorMessage;
if (e.response != null && e.response!.data != null) {
try {
// final error = jsonDecode(e.response!.toString())['error'];
final error = e.response?.data['error'];
errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
}[error] ??
"Something Went Wrong";
} catch (_) {
errorMessage = "Something Went Wrong";
}
} else {
errorMessage = "Something Went Wrong";
}
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
if (!pinScreenContext.mounted) return;
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: AppLocalizations.of(pinScreenContext)
.somethingWentWrong,
);
completer.complete(paymentResponse);
}
}
//IMPS transaction
else if (_selectedMode == TransactionMode.imps) {
final impsTx = ImpsTransaction(
fromAccount: widget.debitAccountNo,
toAccount: widget.creditBeneficiary.accountNo,
amount: _amountController.text,
ifscCode: widget.creditBeneficiary.ifscCode,
remitterName: widget.remitterName,
beneficiaryName: widget.creditBeneficiary.name,
tpin: tpin,
);
final impsService = getIt<ImpsService>();
final completer = Completer<PaymentResponse>();
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final impsResponse =
await impsService.processImpsTransaction(impsTx);
final paymentResponse = PaymentResponse(
isSuccess:
impsResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: impsTx.toAccount,
amount: impsTx.amount,
currency: 'INR',
utr: impsResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
final error = jsonDecode(e.response.toString())['error'];
var errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
}[error] ??
"Something Went Wrong";
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: "Something went Wrong",
);
completer.complete(paymentResponse);
}
}
//RTGS
else {
final rtgsTx = RtgsTransaction(
fromAccount: widget.debitAccountNo,
toAccount: widget.creditBeneficiary.accountNo,
amount: _amountController.text,
ifscCode: widget.creditBeneficiary.ifscCode,
remitterName: widget.remitterName,
beneficiaryName: widget.creditBeneficiary.name,
tpin: tpin,
);
final rtgsService = getIt<RtgsService>();
final completer = Completer<PaymentResponse>();
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final rtgsResponse =
await rtgsService.processRtgsTransaction(rtgsTx);
final paymentResponse = PaymentResponse(
isSuccess:
rtgsResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: rtgsTx.toAccount,
amount: rtgsTx.amount,
currency: 'INR',
utr: rtgsResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
final error = jsonDecode(e.response.toString())['error'];
var errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
// ignore: use_build_context_synchronously
}[error] ??
"Something Went Wrong";
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: "Something Went Wrong",
);
completer.complete(paymentResponse);
}
}
},
),
),
);
}
}
}
@override
Widget build(BuildContext context) {
final loc = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(
title: Text(loc.fundTransfer.replaceFirst(RegExp('\n'), '')),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Debit Account (User)
Text(
loc.debitFrom,
style: Theme.of(context).textTheme.titleSmall,
),
Card(
elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: ListTile(
leading: Image.asset(
'assets/images/logo.png',
width: 40,
height: 40,
),
title: Text(widget.remitterName),
subtitle: Text(widget.debitAccountNo),
),
),
const SizedBox(height: 24),
// Credit Account (Beneficiary)
Text(
AppLocalizations.of(context).creditedTo,
style: Theme.of(context).textTheme.titleSmall,
),
Card(
elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: ListTile(
leading:
getBankLogo(widget.creditBeneficiary.bankName, context),
title: Text(widget.creditBeneficiary.name),
subtitle: Text(widget.creditBeneficiary.accountNo),
),
),
const SizedBox(height: 24),
if (!widget.isOwnBank) ...[
// Transaction Mode Selection
Text(
AppLocalizations.of(context).selectTransactionType,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 12),
Container(
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey.shade300),
),
child: ToggleButtons(
isSelected: [
_selectedMode == TransactionMode.neft,
_selectedMode == TransactionMode.rtgs,
_selectedMode == TransactionMode.imps,
],
onPressed: (index) {
setState(() {
_selectedMode = TransactionMode.values[index];
});
},
borderRadius: BorderRadius.circular(10),
selectedColor: Theme.of(context).colorScheme.onPrimary,
fillColor: Theme.of(context).colorScheme.primary,
color: Theme.of(context).colorScheme.onSurface,
borderColor: Colors.transparent,
selectedBorderColor: Colors.transparent,
splashColor: Theme.of(context).colorScheme.primary,
highlightColor: Theme.of(context).colorScheme.primary,
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 12.0),
child: Text(AppLocalizations.of(context).neft),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 12.0),
child: Text(AppLocalizations.of(context).rtgs),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24.0, vertical: 12.0),
child: Text(AppLocalizations.of(context).imps),
),
],
),
),
const SizedBox(height: 24),
],
// Amount
TextFormField(
controller: _amountController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: loc.amount,
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.currency_rupee),
),
validator: (value) {
if (value == null || value.isEmpty) {
return loc.amountRequired;
}
if (double.tryParse(value) == null ||
double.parse(value) <= 0) {
return loc.validAmount;
}
return null;
},
),
const Spacer(),
// Proceed Button
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _onProceed,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: Text(AppLocalizations.of(context).proceed),
),
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}

View File

@@ -1,115 +1,131 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart'; import 'package:kmobile/widgets/bank_logos.dart';
import 'package:kmobile/features/beneficiaries/screens/add_beneficiary_screen.dart'; import 'package:kmobile/data/models/beneficiary.dart';
import 'package:kmobile/features/fund_transfer/screens/fund_transfer_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/fund_transfer_amount_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../di/injection.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:shimmer/shimmer.dart';
class FundTransferBeneficiaryScreen extends StatefulWidget { class FundTransferBeneficiaryScreen extends StatefulWidget {
const FundTransferBeneficiaryScreen({super.key}); final String creditAccountNo;
final String remitterName;
final bool isOwnBank;
const FundTransferBeneficiaryScreen(
{super.key,
required this.creditAccountNo,
required this.remitterName,
required this.isOwnBank});
@override @override
State<FundTransferBeneficiaryScreen> createState() => State<FundTransferBeneficiaryScreen> createState() =>
_FundTransferBeneficiaryScreen(); _FundTransferBeneficiaryScreenState();
} }
class _FundTransferBeneficiaryScreen class _FundTransferBeneficiaryScreenState
extends State<FundTransferBeneficiaryScreen> { extends State<FundTransferBeneficiaryScreen> {
final List<Map<String, String>> beneficiaries = [ var service = getIt<BeneficiaryService>();
{ bool _isLoading = true;
'bank': 'State Bank Of India', List<Beneficiary> _beneficiaries = [];
'name': 'Trina Bakshi',
}, @override
{ void initState() {
'bank': 'State Bank Of India', super.initState();
'name': 'Sheetal Rao', _loadBeneficiaries();
}, }
{
'bank': 'Punjab National Bank', Future<void> _loadBeneficiaries() async {
'name': 'Manoj Kumar', final data = await service.fetchBeneficiaryList();
}, setState(() {
{ _beneficiaries = data
'bank': 'State Bank Of India', .where((b) => widget.isOwnBank
'name': 'Rohit Mehra', ? b.bankName ==
}, 'THE KANGRA CENTRAL COOPERATIVE BANK LIMITED'
]; : b.bankName != 'THE KANGRA CENTRAL COOPERATIVE BANK LIMITED')
.toList();
_isLoading = false;
});
}
Widget _buildShimmerList() {
return ListView.builder(
itemCount: 6,
itemBuilder: (context, index) => Shimmer.fromColors(
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
child: ListTile(
leading: const CircleAvatar(
radius: 24,
backgroundColor: Colors.white,
),
title: Container(
height: 16,
color: Colors.white,
margin: const EdgeInsets.symmetric(vertical: 4),
),
subtitle: Container(
height: 14,
color: Colors.white,
margin: const EdgeInsets.symmetric(vertical: 4),
),
),
),
);
}
Widget _buildBeneficiaryList() {
if (_beneficiaries.isEmpty) {
return Center(
child: Text(AppLocalizations.of(context).noBeneficiaryFound));
}
return ListView.builder(
itemCount: _beneficiaries.length,
itemBuilder: (context, index) {
final beneficiary = _beneficiaries[index];
return ListTile(
leading: CircleAvatar(
radius: 24,
backgroundColor: Colors.transparent,
child: getBankLogo(beneficiary.bankName, context),
),
title: Text(beneficiary.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(beneficiary.accountNo),
if (beneficiary.bankName != null &&
beneficiary.bankName!.isNotEmpty)
Text(
beneficiary.bankName!,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FundTransferAmountScreen(
debitAccountNo: widget.creditAccountNo,
creditBeneficiary: beneficiary,
remitterName: widget.remitterName,
isOwnBank: widget.isOwnBank,
),
),
);
},
);
},
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(AppLocalizations.of(context).beneficiaries),
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(
AppLocalizations.of(context).fundTransferBeneficiary,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
),
centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: beneficiaries.length,
itemBuilder: (context, index) {
final beneficiary = beneficiaries[index];
return ListTile(
leading: const CircleAvatar(
backgroundColor: Colors.blue, child: Text('A')),
title: Text(beneficiary['name']!),
subtitle: Text(beneficiary['bank']!),
trailing: IconButton(
icon: const Icon(
Symbols.arrow_right,
size: 20,
),
onPressed: () {
// Delete action
},
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const FundTransferScreen()));
},
);
},
),
),
floatingActionButton: Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AddBeneficiaryScreen()));
},
backgroundColor: Colors.grey[300],
foregroundColor: Colors.blue[900],
elevation: 5,
child: const Icon(Icons.add),
),
), ),
body: _isLoading ? _buildShimmerList() : _buildBeneficiaryList(),
); );
} }
} }

View File

@@ -1,148 +1,90 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/fund_transfer_beneficiary_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class FundTransferScreen extends StatefulWidget { class FundTransferScreen extends StatelessWidget {
const FundTransferScreen({super.key}); final String creditAccountNo;
final String remitterName;
@override const FundTransferScreen({
State<FundTransferScreen> createState() => _FundTransferScreen(); super.key,
} required this.creditAccountNo,
required this.remitterName,
class _FundTransferScreen extends State<FundTransferScreen> { });
String amount = "";
void onKeyTap(String key) {
setState(() {
if (key == 'back') {
if (amount.isNotEmpty) {
amount = amount.substring(0, amount.length - 1);
}
} else if (key == 'done') {
if (kDebugMode) {
print('${AppLocalizations.of(context).amountEntered} $amount');
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => const TransactionPinScreen(
// transactionData: {},
// transactionCode: 'TRANSFER'
// )));
}
} else {
amount += key;
}
});
}
Widget buildKey(String value) {
if (value == 'done') {
return GestureDetector(
onTap: () => onKeyTap(value),
child: const Icon(Symbols.check, size: 30),
);
} else if (value == 'back') {
return GestureDetector(
onTap: () => onKeyTap(value),
child: const Icon(Symbols.backspace, size: 30));
} else {
return GestureDetector(
onTap: () => onKeyTap(value),
child: Center(
child: Text(value,
style: const TextStyle(fontSize: 24, color: Colors.black)),
),
);
}
}
final keys = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'done',
'0',
'back',
];
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(AppLocalizations.of(context)
icon: const Icon(Symbols.arrow_back_ios_new), .fundTransfer
onPressed: () { .replaceFirst(RegExp('\n'), '')),
Navigator.pop(context);
},
),
title: Text(
AppLocalizations.of(context).fundTransfer,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
),
centerTitle: false,
actions: const [
Padding(
padding: EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundImage: AssetImage('assets/images/avatar.jpg'),
// Replace with your image
radius: 20,
),
),
],
), ),
body: Column( body: ListView(
children: [ children: [
const Spacer(), FundTransferManagementTile(
Row( icon: Symbols.input_circle,
mainAxisAlignment: MainAxisAlignment.center, label: AppLocalizations.of(context).ownBank,
children: [ onTap: () {
Text(AppLocalizations.of(context).debitFrom), Navigator.push(
Text( context,
'0300015678903456', MaterialPageRoute(
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500), builder: (context) => FundTransferBeneficiaryScreen(
) creditAccountNo: creditAccountNo,
], remitterName: remitterName,
isOwnBank: true,
),
),
);
},
), ),
const SizedBox(height: 20), const Divider(height: 1),
Text(AppLocalizations.of(context).enterAmount, FundTransferManagementTile(
style: TextStyle(fontSize: 20)), icon: Symbols.output_circle,
const SizedBox(height: 20), label: AppLocalizations.of(context).outsideBank,
Container( onTap: () {
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), Navigator.push(
decoration: BoxDecoration( context,
color: Colors.grey.shade200, MaterialPageRoute(
borderRadius: BorderRadius.circular(12), builder: (context) => FundTransferBeneficiaryScreen(
), creditAccountNo: creditAccountNo,
child: Text( remitterName: remitterName,
amount.isEmpty ? "0" : amount, isOwnBank: false,
style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold), ),
), ),
), );
const Spacer(), },
Container(
padding: const EdgeInsets.all(16.0),
color: Colors.white,
child: GridView.count(
crossAxisCount: 3,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 12,
crossAxisSpacing: 12,
childAspectRatio: 1.2,
children: keys.map((key) => buildKey(key)).toList(),
),
), ),
const Divider(height: 1),
], ],
), ),
); );
} }
} }
class FundTransferManagementTile extends StatelessWidget {
final IconData icon;
final String label;
final VoidCallback onTap;
final bool disable;
const FundTransferManagementTile({
super.key,
required this.icon,
required this.label,
required this.onTap,
this.disable = false,
});
@override
Widget build(BuildContext context) {
return ListTile(
leading: Icon(icon),
title: Text(label),
trailing: const Icon(Symbols.arrow_right, size: 20),
onTap: onTap,
enabled: !disable,
);
}
}

View File

@@ -1,3 +1,4 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'dart:ui' as ui; import 'dart:ui' as ui;
@@ -7,15 +8,13 @@ import 'package:kmobile/data/models/payment_response.dart';
import 'package:lottie/lottie.dart'; import 'package:lottie/lottie.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:confetti/confetti.dart';
class PaymentAnimationScreen extends StatefulWidget { class PaymentAnimationScreen extends StatefulWidget {
final Future<PaymentResponse> paymentResponse; final Future<PaymentResponse> paymentResponse;
const PaymentAnimationScreen({ const PaymentAnimationScreen({super.key, required this.paymentResponse});
super.key,
required this.paymentResponse,
});
@override @override
State<PaymentAnimationScreen> createState() => _PaymentAnimationScreenState(); State<PaymentAnimationScreen> createState() => _PaymentAnimationScreenState();
@@ -23,6 +22,20 @@ class PaymentAnimationScreen extends StatefulWidget {
class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> { class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
final GlobalKey _shareKey = GlobalKey(); final GlobalKey _shareKey = GlobalKey();
late ConfettiController _confettiController;
@override
void initState() {
super.initState();
_confettiController =
ConfettiController(duration: const Duration(seconds: 2));
}
@override
void dispose() {
_confettiController.dispose();
super.dispose();
}
Future<void> _shareScreenshot() async { Future<void> _shareScreenshot() async {
try { try {
@@ -37,14 +50,18 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
final file = await File('${tempDir.path}/payment_result.png').create(); final file = await File('${tempDir.path}/payment_result.png').create();
await file.writeAsBytes(pngBytes); await file.writeAsBytes(pngBytes);
await Share.shareXFiles([XFile(file.path)], await Share.shareXFiles(
text: '${AppLocalizations.of(context).paymentResult}'); [XFile(file.path)],
text: AppLocalizations.of(context).paymentResult,
);
} catch (e) { } catch (e) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
'${AppLocalizations.of(context).failedToShareScreenshot}: $e')), '${AppLocalizations.of(context).failedToShareScreenshot}: $e',
),
),
); );
} }
} }
@@ -69,8 +86,29 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
final response = snapshot.data!; final response = snapshot.data!;
final isSuccess = response.isSuccess; final isSuccess = response.isSuccess;
if (isSuccess) _confettiController.play();
return Stack( return Stack(
children: [ children: [
Align(
alignment: Alignment.topCenter,
child: ConfettiWidget(
confettiController: _confettiController,
blastDirectionality: BlastDirectionality.explosive,
emissionFrequency: 0.2,
numberOfParticles: 40,
gravity: 0.3,
maxBlastForce: 25,
minBlastForce: 10,
shouldLoop: false,
colors: const [
Colors.green,
Colors.blue,
Colors.pink,
Colors.orange,
],
),
),
Center( Center(
child: RepaintBoundary( child: RepaintBoundary(
key: _shareKey, key: _shareKey,
@@ -95,48 +133,61 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
Text( Text(
AppLocalizations.of(context) AppLocalizations.of(context)
.paymentSuccessful, .paymentSuccessful,
style: TextStyle( style: const TextStyle(
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.green), color: Colors.green,
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
if (response.amount != null) if (response.amount != null)
Text( Text(
'${AppLocalizations.of(context).amount}: ${response.amount} ${response.currency ?? ''}', '${AppLocalizations.of(context).amount}: ${response.amount} ${response.currency ?? ""}',
style: const TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
fontFamily: 'Rubik'), fontFamily: 'Rubik',
),
), ),
if (response.creditedAccount != null) if (response.creditedAccount != null)
Text( Text(
'${AppLocalizations.of(context).creditedAccount}: ${response.creditedAccount}', '${AppLocalizations.of(context).creditedAccount}: ${response.creditedAccount}',
style: const TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
fontFamily: 'Rubik'), fontFamily: 'Rubik',
),
), ),
if (response.date != null) if (response.date != null)
Text( Text(
'Date: ${response.date!.toLocal().toIso8601String()}', "Date: ${response.date!.toLocal().toIso8601String()}",
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
if (response.utr != null &&
response.utr!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'UTR: ${response.utr}',
style: const TextStyle(fontSize: 16),
),
),
], ],
) )
: Column( : Column(
children: [ children: [
Text( Text(
AppLocalizations.of(context).paymentFailed, AppLocalizations.of(context).paymentFailed,
style: TextStyle( style: const TextStyle(
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.red), color: Colors.red,
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
if (response.errorMessage != null) if (response.errorMessage != null)
Text( Text(
response.errorMessage!, response.errorMessage ?? '',
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
], ],
@@ -147,7 +198,6 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
), ),
), ),
), ),
// Buttons at the bottom
Positioned( Positioned(
left: 0, left: 0,
right: 0, right: 0,
@@ -159,27 +209,22 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
onPressed: _shareScreenshot, onPressed: _shareScreenshot,
icon: Icon( icon: Icon(
Icons.share_rounded, Icons.share_rounded,
color: Theme.of(context).primaryColor, color: Theme.of(context).colorScheme.primary,
),
label: Text(
AppLocalizations.of(context).share,
style: TextStyle(color: Theme.of(context).colorScheme.primary),
), ),
label: Text(AppLocalizations.of(context).share,
style:
TextStyle(color: Theme.of(context).primaryColor)),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor:
Theme.of(context).scaffoldBackgroundColor,
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 32, vertical: 12), horizontal: 45, vertical: 12),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).primaryColor,
width: 1,
),
borderRadius: BorderRadius.circular(30), borderRadius: BorderRadius.circular(30),
), ),
textStyle: const TextStyle( textStyle: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: Colors.black), ),
), ),
), ),
ElevatedButton.icon( ElevatedButton.icon(
@@ -187,6 +232,7 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
Navigator.of(context) Navigator.of(context)
.popUntil((route) => route.isFirst); .popUntil((route) => route.isFirst);
}, },
icon: const Icon(Icons.check),
label: Text(AppLocalizations.of(context).done), label: Text(AppLocalizations.of(context).done),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
@@ -195,7 +241,9 @@ class _PaymentAnimationScreenState extends State<PaymentAnimationScreen> {
borderRadius: BorderRadius.circular(30), borderRadius: BorderRadius.circular(30),
), ),
textStyle: const TextStyle( textStyle: const TextStyle(
fontSize: 18, fontWeight: FontWeight.w600), fontSize: 18,
fontWeight: FontWeight.w600,
),
), ),
), ),
], ],

View File

@@ -1,5 +1,4 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/features/fund_transfer/screens/tpin_set_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/tpin_set_screen.dart';
@@ -12,8 +11,10 @@ class TpinOtpScreen extends StatefulWidget {
class _TpinOtpScreenState extends State<TpinOtpScreen> { class _TpinOtpScreenState extends State<TpinOtpScreen> {
final List<FocusNode> _focusNodes = List.generate(4, (_) => FocusNode()); final List<FocusNode> _focusNodes = List.generate(4, (_) => FocusNode());
final List<TextEditingController> _controllers = final List<TextEditingController> _controllers = List.generate(
List.generate(4, (_) => TextEditingController()); 4,
(_) => TextEditingController(),
);
@override @override
void dispose() { void dispose() {
@@ -42,9 +43,7 @@ class _TpinOtpScreenState extends State<TpinOtpScreen> {
if (_enteredOtp == '0000') { if (_enteredOtp == '0000') {
Navigator.pushReplacement( Navigator.pushReplacement(
context, context,
MaterialPageRoute( MaterialPageRoute(builder: (_) => TpinSetScreen()),
builder: (_) => TpinSetScreen(),
),
); );
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -67,8 +66,11 @@ class _TpinOtpScreenState extends State<TpinOtpScreen> {
child: Column( child: Column(
// mainAxisSize: MainAxisSize.min, // mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.lock_outline, Icon(
size: 48, color: theme.colorScheme.primary), Icons.lock_outline,
size: 48,
color: theme.colorScheme.primary,
),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
AppLocalizations.of(context).otpVerification, AppLocalizations.of(context).otpVerification,
@@ -103,7 +105,7 @@ class _TpinOtpScreenState extends State<TpinOtpScreen> {
decoration: InputDecoration( decoration: InputDecoration(
counterText: '', counterText: '',
filled: true, filled: true,
fillColor: Colors.blue[50], fillColor: Theme.of(context).primaryColorLight,
border: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: BorderSide( borderSide: BorderSide(
@@ -129,12 +131,15 @@ class _TpinOtpScreenState extends State<TpinOtpScreen> {
icon: const Icon(Icons.verified_user_rounded), icon: const Icon(Icons.verified_user_rounded),
label: Text( label: Text(
AppLocalizations.of(context).verifyOtp, AppLocalizations.of(context).verifyOtp,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.w600),
), ),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: theme.colorScheme.primary, backgroundColor: theme.colorScheme.primary,
padding: padding: const EdgeInsets.symmetric(
const EdgeInsets.symmetric(vertical: 14, horizontal: 28), vertical: 14,
horizontal: 28,
),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30), borderRadius: BorderRadius.circular(30),
), ),
@@ -147,7 +152,8 @@ class _TpinOtpScreenState extends State<TpinOtpScreen> {
// Resend OTP logic here // Resend OTP logic here
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text(AppLocalizations.of(context).otpResent)), content: Text(AppLocalizations.of(context).otpResent),
),
); );
}, },
child: Text(AppLocalizations.of(context).resendOtp), child: Text(AppLocalizations.of(context).resendOtp),

View File

@@ -1,5 +1,4 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/features/fund_transfer/screens/tpin_otp_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/tpin_otp_screen.dart';
@@ -10,16 +9,17 @@ class TpinSetupPromptScreen extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(title: Text(AppLocalizations.of(context).setTpin)),
title: Text(AppLocalizations.of(context).setTpin),
),
body: Padding( body: Padding(
padding: const EdgeInsets.symmetric(vertical: 100.0), padding: const EdgeInsets.symmetric(vertical: 100.0),
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.lock_person_rounded, Icon(
size: 60, color: theme.colorScheme.primary), Icons.lock_person_rounded,
size: 60,
color: theme.colorScheme.primary,
),
const SizedBox(height: 18), const SizedBox(height: 18),
Text( Text(
AppLocalizations.of(context).tpinRequired, AppLocalizations.of(context).tpinRequired,
@@ -41,12 +41,15 @@ class TpinSetupPromptScreen extends StatelessWidget {
icon: const Icon(Icons.arrow_forward_rounded), icon: const Icon(Icons.arrow_forward_rounded),
label: Text( label: Text(
AppLocalizations.of(context).setTpin, AppLocalizations.of(context).setTpin,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
), ),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: theme.colorScheme.primary, backgroundColor: theme.colorScheme.primary,
padding: padding: const EdgeInsets.symmetric(
const EdgeInsets.symmetric(vertical: 14, horizontal: 32), vertical: 14,
horizontal: 32,
),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),
@@ -54,9 +57,7 @@ class TpinSetupPromptScreen extends StatelessWidget {
onPressed: () { onPressed: () {
Navigator.pushReplacement( Navigator.pushReplacement(
context, context,
MaterialPageRoute( MaterialPageRoute(builder: (_) => const TpinOtpScreen()),
builder: (_) => const TpinOtpScreen(),
),
); );
}, },
), ),

View File

@@ -1,4 +1,4 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/api/services/auth_service.dart'; import 'package:kmobile/api/services/auth_service.dart';
@@ -55,6 +55,7 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
await authService.setTpin(pin); await authService.setTpin(pin);
} catch (e) { } catch (e) {
setState(() { setState(() {
// ignore: unnecessary_string_interpolations
_errorText = "${AppLocalizations.of(context).tpinFailed}"; _errorText = "${AppLocalizations.of(context).tpinFailed}";
_tpin.clear(); _tpin.clear();
}); });
@@ -66,14 +67,17 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
builder: (ctx) => AlertDialog( builder: (ctx) => AlertDialog(
shape: shape: RoundedRectangleBorder(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)), borderRadius: BorderRadius.circular(18),
),
title: Column( title: Column(
children: [ children: [
Icon(Icons.check_circle, color: Colors.green, size: 60), const Icon(Icons.check_circle, color: Colors.green, size: 60),
SizedBox(height: 12), const SizedBox(height: 12),
Text(AppLocalizations.of(context).success, Text(
style: TextStyle(fontWeight: FontWeight.bold)), AppLocalizations.of(context).success,
style: const TextStyle(fontWeight: FontWeight.bold),
),
], ],
), ),
content: Text( content: Text(
@@ -85,8 +89,10 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
onPressed: () { onPressed: () {
Navigator.of(ctx).pop(); Navigator.of(ctx).pop();
}, },
child: Text(AppLocalizations.of(context).ok, child: Text(
style: TextStyle(fontSize: 16)), AppLocalizations.of(context).ok,
style: const TextStyle(fontSize: 16),
),
), ),
], ],
), ),
@@ -125,7 +131,7 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
['1', '2', '3'], ['1', '2', '3'],
['4', '5', '6'], ['4', '5', '6'],
['7', '8', '9'], ['7', '8', '9'],
['Enter', '0', '<'] ['Enter', '0', '<'],
]; ];
return Column( return Column(
@@ -144,8 +150,9 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
_handleComplete(); _handleComplete();
} else { } else {
setState(() { setState(() {
_errorText = _errorText = AppLocalizations.of(
AppLocalizations.of(context).pleaseEnter6Digits; context,
).pleaseEnter6Digits;
}); });
} }
} else if (key.isNotEmpty) { } else if (key.isNotEmpty) {
@@ -166,7 +173,9 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
key == '<' ? '' : key, key == '<' ? '' : key,
style: TextStyle( style: TextStyle(
fontSize: 20, fontSize: 20,
color: key == 'Enter' ? Colors.blue : Colors.black, color: key == 'Enter'
? Theme.of(context).primaryColor
: Colors.black,
), ),
), ),
), ),
@@ -195,7 +204,8 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
child: Column( child: Column(
children: [ children: [
const Spacer(), const Spacer(),
const Icon(Icons.lock_outline, size: 60, color: Colors.blue), Icon(Icons.lock_outline,
size: 60, color: Theme.of(context).primaryColor),
const SizedBox(height: 20), const SizedBox(height: 20),
Text( Text(
getTitle(), getTitle(),
@@ -206,8 +216,10 @@ class _TpinSetScreenState extends State<TpinSetScreen> {
if (_errorText != null) if (_errorText != null)
Padding( Padding(
padding: const EdgeInsets.only(top: 8.0), padding: const EdgeInsets.only(top: 8.0),
child: Text(_errorText!, child: Text(
style: const TextStyle(color: Colors.red)), _errorText!,
style: const TextStyle(color: Colors.red),
),
), ),
const Spacer(), const Spacer(),
buildNumberPad(), buildNumberPad(),

View File

@@ -1,31 +1,54 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kmobile/api/services/auth_service.dart'; import 'package:kmobile/api/services/auth_service.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/data/models/transfer.dart';
import 'package:kmobile/di/injection.dart'; import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/tpin_prompt_screen.dart'; import 'package:kmobile/features/fund_transfer/screens/tpin_prompt_screen.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_success_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../l10n/app_localizations.dart';
class TransactionPinScreen extends StatefulWidget { class TransactionPinScreen extends StatefulWidget {
final Transfer transactionData; final Future<void> Function(BuildContext, String) onPinCompleted;
const TransactionPinScreen({super.key, required this.transactionData});
const TransactionPinScreen({super.key, required this.onPinCompleted});
@override @override
State<TransactionPinScreen> createState() => _TransactionPinScreen(); State<TransactionPinScreen> createState() => _TransactionPinScreenState();
} }
class _TransactionPinScreen extends State<TransactionPinScreen> { class _TransactionPinScreenState extends State<TransactionPinScreen>
with SingleTickerProviderStateMixin {
final List<String> _pin = []; final List<String> _pin = [];
bool _loading = true; bool _loading = true;
bool _isSubmitting = false;
late final AnimationController _bounceController;
late final Animation<double> _bounceAnimation;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_checkIfTpinIsSet(); _checkIfTpinIsSet();
_bounceController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 150),
);
_bounceAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
CurvedAnimation(
parent: _bounceController,
curve: Curves.elasticIn,
reverseCurve: Curves.elasticOut),
)..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_bounceController.reverse();
}
});
}
@override
void dispose() {
_bounceController.dispose();
super.dispose();
} }
Future<void> _checkIfTpinIsSet() async { Future<void> _checkIfTpinIsSet() async {
@@ -36,9 +59,7 @@ class _TransactionPinScreen extends State<TransactionPinScreen> {
if (!isSet && mounted) { if (!isSet && mounted) {
Navigator.pushReplacement( Navigator.pushReplacement(
context, context,
MaterialPageRoute( MaterialPageRoute(builder: (_) => const TpinSetupPromptScreen()),
builder: (_) => const TpinSetupPromptScreen(),
),
); );
} else if (mounted) { } else if (mounted) {
setState(() => _loading = false); setState(() => _loading = false);
@@ -48,67 +69,95 @@ class _TransactionPinScreen extends State<TransactionPinScreen> {
setState(() => _loading = false); setState(() => _loading = false);
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text(AppLocalizations.of(context).tpinStatusFailed)), content: Text(AppLocalizations.of(context).tpinStatusFailed),
),
); );
} }
} }
} }
void _onKeyPressed(String value) { void _onKeyPressed(String value) {
if (_isSubmitting) return;
setState(() { setState(() {
if (value == 'back') { if (value == 'back') {
if (_pin.isNotEmpty) _pin.removeLast(); if (_pin.isNotEmpty) _pin.removeLast();
} else if (_pin.length < 6) { } else if (_pin.length < 6) {
_pin.add(value); _pin.add(value);
_bounceController.forward(from: 0);
} }
}); });
} }
Future<void> _submitPin() async {
if (_isSubmitting) return;
if (_pin.length == 6) {
setState(() => _isSubmitting = true);
try {
await widget.onPinCompleted(context, _pin.join());
} finally {
if (mounted) {
setState(() => _isSubmitting = false);
}
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context).enter6DigitTpin),
),
);
}
}
Widget _buildPinIndicators() { Widget _buildPinIndicators() {
return Row( return AnimatedBuilder(
mainAxisAlignment: MainAxisAlignment.center, animation: _bounceAnimation,
children: List.generate(6, (index) { builder: (context, child) {
return Container( return Row(
margin: const EdgeInsets.symmetric(horizontal: 8), mainAxisAlignment: MainAxisAlignment.center,
width: 20, children: List.generate(6, (index) {
height: 20, final isAnimating =
decoration: BoxDecoration( index == _pin.length - 1 && _bounceController.isAnimating;
shape: BoxShape.circle, return Transform.scale(
border: Border.all(color: Colors.blue, width: 2), scale: isAnimating ? _bounceAnimation.value : 1.0,
color: index < _pin.length ? Colors.blue : Colors.transparent, child: Container(
), margin: const EdgeInsets.symmetric(horizontal: 8),
); width: 30,
}), height: 30,
); decoration: BoxDecoration(
shape: BoxShape.circle,
color: index < _pin.length
? Theme.of(context).colorScheme.onSurfaceVariant
: Theme.of(context)
.colorScheme
.surfaceContainerHighest),
),
);
}),
);
});
} }
Widget _buildKey(String label, {IconData? icon}) { Widget _buildKey(String label, {IconData? icon}) {
return Expanded( return Expanded(
child: InkWell( child: InkWell(
onTap: () async { onTap: () {
if (label == 'back') { HapticFeedback.lightImpact();
_onKeyPressed('back'); if (label == 'done') {
} else if (label == 'done') { _submitPin();
// Handle submit if needed
if (_pin.length == 6) {
await sendTransaction();
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text(AppLocalizations.of(context).enter6DigitTpin)),
);
}
} else { } else {
_onKeyPressed(label); _onKeyPressed(label);
} }
}, },
borderRadius: BorderRadius.circular(48),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20), padding: const EdgeInsets.symmetric(vertical: 20),
child: Center( child: Center(
child: icon != null child: _isSubmitting && label == 'done'
? Icon(icon, size: 28) ? const CircularProgressIndicator()
: Text(label, style: const TextStyle(fontSize: 24)), : icon != null
? Icon(icon, size: 28)
: Text(label, style: const TextStyle(fontSize: 24)),
), ),
), ),
), ),
@@ -122,69 +171,45 @@ class _TransactionPinScreen extends State<TransactionPinScreen> {
Row(children: [_buildKey('1'), _buildKey('2'), _buildKey('3')]), Row(children: [_buildKey('1'), _buildKey('2'), _buildKey('3')]),
Row(children: [_buildKey('4'), _buildKey('5'), _buildKey('6')]), Row(children: [_buildKey('4'), _buildKey('5'), _buildKey('6')]),
Row(children: [_buildKey('7'), _buildKey('8'), _buildKey('9')]), Row(children: [_buildKey('7'), _buildKey('8'), _buildKey('9')]),
Row(children: [ Row(
_buildKey('done', icon: Icons.check), children: [
_buildKey('0'), _buildKey('done', icon: Icons.check),
_buildKey('back', icon: Icons.backspace_outlined), _buildKey('0'),
]), _buildKey('back', icon: Icons.backspace_outlined),
],
),
], ],
); );
} }
Future<void> sendTransaction() async {
final paymentService = getIt<PaymentService>();
final transfer = widget.transactionData;
transfer.tpin = _pin.join();
try {
final paymentResponse =
paymentService.processQuickPayWithinBank(transfer);
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) =>
PaymentAnimationScreen(paymentResponse: paymentResponse)),
);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toString())),
);
}
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton( title: Text(AppLocalizations.of(context).tpin),
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text(
AppLocalizations.of(context).tpin,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
),
centerTitle: false, centerTitle: false,
), ),
body: Padding( body: _loading
padding: const EdgeInsets.only(bottom: 20.0), ? const Center(child: CircularProgressIndicator())
child: Column( : SafeArea(
children: [ child: Padding(
const Spacer(), padding: const EdgeInsets.only(bottom: 20.0),
Text( child: Column(
AppLocalizations.of(context).enterTpin, children: [
style: TextStyle(fontSize: 18), const Spacer(),
Text(
AppLocalizations.of(context).enterTpin,
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 50),
_buildPinIndicators(),
const Spacer(),
_buildKeypad(),
],
),
),
), ),
const SizedBox(height: 20),
_buildPinIndicators(),
const Spacer(),
_buildKeypad(),
],
),
),
); );
} }
} }

View File

@@ -1,4 +1,4 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
@@ -35,8 +35,9 @@ class _TransactionSuccessScreen extends State<TransactionSuccessScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final String transactionDate = final String transactionDate = DateTime.now().toLocal().toString().split(
DateTime.now().toLocal().toString().split(' ')[0]; ' ',
)[0];
final String creditAccount = widget.creditAccount; final String creditAccount = widget.creditAccount;
return Scaffold( return Scaffold(
@@ -49,40 +50,30 @@ class _TransactionSuccessScreen extends State<TransactionSuccessScreen> {
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const CircleAvatar( CircleAvatar(
radius: 50, radius: 50,
backgroundColor: Colors.blue, backgroundColor: Theme.of(context).primaryColor,
child: Icon( child: Icon(Icons.check,
Icons.check, color: Theme.of(context).scaffoldBackgroundColor,
color: Colors.white, size: 60),
size: 60,
),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
Text( Text(
AppLocalizations.of(context).transactionSuccess, AppLocalizations.of(context).transactionSuccess,
style: TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18, fontWeight: FontWeight.w600),
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
"On $transactionDate", "On $transactionDate",
style: const TextStyle( style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6)),
fontSize: 14,
color: Colors.black54,
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
"${AppLocalizations.of(context).toAccountNumber}: $creditAccount", "${AppLocalizations.of(context).toAccountNumber}: $creditAccount",
style: const TextStyle( style: TextStyle(fontSize: 12, color: Theme.of(context).colorScheme.onSurface.withOpacity(0.8)),
fontSize: 12,
color: Colors.black87,
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
], ],
@@ -100,15 +91,16 @@ class _TransactionSuccessScreen extends State<TransactionSuccessScreen> {
child: OutlinedButton.icon( child: OutlinedButton.icon(
onPressed: _shareScreenshot, onPressed: _shareScreenshot,
icon: const Icon(Icons.share, size: 18), icon: const Icon(Icons.share, size: 18),
label: Text(AppLocalizations.of(context).share), label: Text(AppLocalizations.of(context).share,
style: TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer),
),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.white, backgroundColor: Theme.of(context).primaryColorDark,
foregroundColor: Colors.blueAccent, foregroundColor:
side: Theme.of(context).scaffoldBackgroundColor,
const BorderSide(color: Colors.black, width: 1), ),
elevation: 0),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
@@ -117,16 +109,18 @@ class _TransactionSuccessScreen extends State<TransactionSuccessScreen> {
onPressed: () { onPressed: () {
// Done action // Done action
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => builder: (context) => const NavigationScaffold(),
const NavigationScaffold())); ),
);
}, },
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
shape: const StadiumBorder(), shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(vertical: 16), padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: Colors.blue[900], backgroundColor: Theme.of(context).primaryColorDark,
foregroundColor: Colors.white, foregroundColor:
Theme.of(context).scaffoldBackgroundColor,
), ),
child: Text(AppLocalizations.of(context).done), child: Text(AppLocalizations.of(context).done),
), ),

View File

@@ -0,0 +1,109 @@
import 'package:flutter/material.dart';
import '../../../api/services/change_password_service.dart';
import '../../../di/injection.dart';
import '../../../l10n/app_localizations.dart';
class ChangePasswordOTPScreen extends StatefulWidget {
final String currentPassword;
final String newPassword;
final String confirmPassword;
final String mobileNumber;
// ignore: use_key_in_widget_constructors
const ChangePasswordOTPScreen({
required this.currentPassword,
required this.newPassword,
required this.confirmPassword,
required this.mobileNumber,
});
@override
State<ChangePasswordOTPScreen> createState() => _ChangePasswordOTPScreenState();
}
class _ChangePasswordOTPScreenState extends State<ChangePasswordOTPScreen> {
bool _isLoading = true;
final TextEditingController otpController = TextEditingController();
@override
void initState() {
super.initState();
// Simulate OTP sending delay
Future.delayed(const Duration(seconds: 2), () {
setState(() {
_isLoading = false;
});
});
}
final changePasswordService = getIt<ChangePasswordService>();
Future<void> _validateOTP() async {
try {
await changePasswordService.validateOtp(
otp: otpController.text,
mobileNumber: widget.mobileNumber,
);
// If OTP is valid, then change the password
await changePasswordService.validateChangePwd(
OldLPsw: widget.currentPassword,
newLPsw: widget.newPassword,
confirmLPsw: widget.confirmPassword,
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context).pwdchangeSuccess)),
);
// Navigate back to profile or login
Navigator.of(context).popUntil((route) => route.isFirst);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${AppLocalizations.of(context).failedToValidate}: $e')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(AppLocalizations.of(context).otpVerification)),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: _isLoading
? const Center(child: CircularProgressIndicator())
: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
AppLocalizations.of(context).otpSent,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 24),
TextFormField(
controller: otpController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).enterOTP,
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _validateOTP,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: Text(AppLocalizations.of(context).validateOTP),
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,155 @@
// ignore_for_file: use_key_in_widget_constructors
import 'package:flutter/material.dart';
import '../../../api/services/change_password_service.dart';
import '../../../di/injection.dart';
import '../../../l10n/app_localizations.dart';
import 'change_password_otp_screen.dart';
class ChangePasswordScreen extends StatefulWidget {
const ChangePasswordScreen();
@override
State<ChangePasswordScreen> createState() => _ChangePasswordScreenState();
}
class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
final _formKey = GlobalKey<FormState>();
final currentPasswordController = TextEditingController();
final newPasswordController = TextEditingController();
final confirmPasswordController = TextEditingController();
bool _showCurrentPassword = false;
bool _showNewPassword = false;
bool _showConfirmPassword = false;
final passwordRegex =
RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$');
String? validateCurrentPassword(String? value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).currentpwdrqd;
}
return null;
}
String? validateNewPassword(String? value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).newpwdrqd;
}
if (!passwordRegex.hasMatch(value)) {
return AppLocalizations.of(context).pwdFormat;
}
if (value == currentPasswordController.text) {
return AppLocalizations.of(context).newoldpwddiff;
}
return null;
}
String? validateConfirmPassword(String? value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).confirmpwdrqd;
}
if (value != newPasswordController.text) {
return AppLocalizations.of(context).pwdmismatch;
}
return null;
}
final ChangePasswordService _changePasswordService = getIt<ChangePasswordService>();
void _proceed() async {
if (_formKey.currentState!.validate()) {
try {
const mobileNumber = "8981274001"; // Replace with actual mobile number
await _changePasswordService.getOtp(mobileNumber: mobileNumber);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangePasswordOTPScreen(
currentPassword: currentPasswordController.text,
newPassword: newPasswordController.text,
confirmPassword: confirmPasswordController.text,
mobileNumber: mobileNumber,
),
),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${AppLocalizations.of(context).failedtosentOTP}: $e')),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(AppLocalizations.of(context).changeLoginPassword)),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: currentPasswordController,
obscureText: !_showCurrentPassword,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).currentpwd,
suffixIcon: IconButton(
icon: Icon(_showCurrentPassword
? Icons.visibility
: Icons.visibility_off),
onPressed: () =>
setState(() => _showCurrentPassword = !_showCurrentPassword),
),
),
validator: validateCurrentPassword,
),
const SizedBox(height: 16),
TextFormField(
controller: newPasswordController,
obscureText: !_showNewPassword,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).newpwd,
suffixIcon: IconButton(
icon: Icon(_showNewPassword
? Icons.visibility
: Icons.visibility_off),
onPressed: () =>
setState(() => _showNewPassword = !_showNewPassword),
),
),
validator: validateNewPassword,
),
const SizedBox(height: 16),
TextFormField(
controller: confirmPasswordController,
obscureText: !_showConfirmPassword,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).confirmpwd,
suffixIcon: IconButton(
icon: Icon(_showConfirmPassword
? Icons.visibility
: Icons.visibility_off),
onPressed: () =>
setState(() => _showConfirmPassword = !_showConfirmPassword),
),
),
validator: validateConfirmPassword,
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _proceed,
child: Text(AppLocalizations.of(context).proceed),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
class LogoutDialog extends StatelessWidget {
const LogoutDialog({super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(AppLocalizations.of(context).logout),
content: Text(AppLocalizations.of(context).logoutCheck),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false), // dismiss
child: Text(AppLocalizations.of(context).no),
),
TextButton(
onPressed: () => Navigator.pop(context, true), // confirm
child: Text(AppLocalizations.of(context).yes),
),
],
);
}
}

View File

@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/config/theme_type.dart';
import 'package:kmobile/features/auth/controllers/theme_cubit.dart';
import '../../../l10n/app_localizations.dart';
class ColorThemeDialog extends StatelessWidget {
const ColorThemeDialog({super.key});
@override
Widget build(BuildContext context) {
return SimpleDialog(
title: Text(AppLocalizations.of(context).selectThemeColor),
children: [
ListTile(
leading: const CircleAvatar(backgroundColor: Colors.deepPurple),
title: Text(AppLocalizations.of(context).violet),
onTap: () {
context.read<ThemeCubit>().changeTheme(ThemeType.violet);
Navigator.pop(context);
},
),
ListTile(
leading: const CircleAvatar(backgroundColor: Colors.green),
title: Text(AppLocalizations.of(context).green),
onTap: () {
context.read<ThemeCubit>().changeTheme(ThemeType.green);
Navigator.pop(context);
},
),
ListTile(
leading: const CircleAvatar(backgroundColor: Colors.orange),
title: Text(AppLocalizations.of(context).orange),
onTap: () {
context.read<ThemeCubit>().changeTheme(ThemeType.orange);
Navigator.pop(context);
},
),
ListTile(
leading: const CircleAvatar(backgroundColor: Colors.blue),
title: Text(AppLocalizations.of(context).blue),
onTap: () {
context.read<ThemeCubit>().changeTheme(ThemeType.blue);
Navigator.pop(context);
},
),
],
);
}
}

View File

@@ -1,52 +1,40 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
import 'package:kmobile/app.dart'; import 'package:kmobile/app.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LanguageDialog extends StatelessWidget { class LanguageDialog extends StatelessWidget {
const LanguageDialog({super.key}); // ignore: use_super_parameters
const LanguageDialog({Key? key}) : super(key: key);
String getLocaleName(AppLocalizations localizations, String code) { Future<void> _setLocale(BuildContext context, String langCode) async {
final localeCodeMap = { final prefs = await SharedPreferences.getInstance();
'en': localizations.english, await prefs.setString('locale', langCode); // Save selected language
'hi': localizations.hindi, KMobile.setLocale(context, Locale(langCode)); // Update locale in app
}; Navigator.of(context).pop(); // Close the dialog
return localeCodeMap[code] ?? 'Unknown';
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Builder( return AlertDialog(
builder: (context) { title: Text(AppLocalizations.of(context).selectLanguage),
final localizations = AppLocalizations.of(context); content: Column(
mainAxisSize: MainAxisSize.min,
final supportedLocales = [ children: [
const Locale('en'), ListTile(
const Locale('hi'), leading: const Icon(Icons.language),
]; title: const Text('English'),
onTap: () => _setLocale(context, 'en'),
return AlertDialog(
title: Text(localizations.language),
content: Column(
mainAxisSize: MainAxisSize.min,
children: supportedLocales.map((locale) {
return ListTile(
leading: const Icon(Icons.language),
title: Text(getLocaleName(localizations, locale.languageCode)),
onTap: () {
Navigator.pop(context);
KMobile.setLocale(context, locale);
},
);
}).toList(),
), ),
actions: [ ListTile(
TextButton( leading: const Icon(Icons.language),
onPressed: () => Navigator.pop(context), title: const Text('हिन्दी'),
child: Text(localizations.cancel), onTap: () => _setLocale(context, 'hi'),
), ),
], ],
); ),
},
); );
} }
} }

View File

@@ -1,6 +1,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:kmobile/features/profile/preferences/theme_mode_dialog.dart';
import 'language_dialog.dart'; import 'language_dialog.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'color_theme_dialog.dart';
import '../../../l10n/app_localizations.dart';
import 'package:kmobile/features/auth/controllers/theme_cubit.dart';
import 'package:kmobile/features/auth/controllers/theme_state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class PreferenceScreen extends StatelessWidget { class PreferenceScreen extends StatelessWidget {
const PreferenceScreen({super.key}); const PreferenceScreen({super.key});
@@ -11,21 +16,44 @@ class PreferenceScreen extends StatelessWidget {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(loc.preferences), // Localized "Preferences" title: Text(loc.preferences),
), ),
body: ListView( body: BlocBuilder<ThemeCubit, ThemeState>(
children: [ builder: (context, state) {
ListTile( return ListView(
leading: const Icon(Icons.language), children: [
title: Text(loc.language), // Localized "Language" // Language Selection
onTap: () { ListTile(
showDialog( leading: const Icon(Icons.language),
context: context, title: Text(loc.language),
builder: (context) => LanguageDialog(), onTap: () {
); showDialog(
}, context: context,
), builder: (_) => const LanguageDialog(),
], );
},
),
//Theme Mode Switch (Light/Dark)
ListTile(
leading: const Icon(Icons.brightness_6),
title: Text(AppLocalizations.of(context).themeMode),
onTap: () {
showThemeModeDialog(context);
},
),
//Color_Theme_Selection
ListTile(
leading: const Icon(Icons.color_lens),
title: Text(AppLocalizations.of(context).themeColor),
onTap: () {
showDialog(
context: context,
builder: (_) => const ColorThemeDialog(),
);
}),
],
);
},
), ),
); );
} }

View File

@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/features/auth/controllers/theme_mode_cubit.dart';
import '../../../l10n/app_localizations.dart';
String _getThemeModeText(ThemeMode mode, AppLocalizations l10n) {
switch (mode) {
case ThemeMode.system:
return l10n.themeModeSystem;
case ThemeMode.light:
return l10n.themeModeLight;
case ThemeMode.dark:
return l10n.themeModeDark;
}
}
Future<void> showThemeModeDialog(BuildContext context) async {
final cubit = context.read<ThemeModeCubit>();
final currentMode = context.read<ThemeModeCubit>().state.mode;
final l10n = AppLocalizations.of(context);
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(l10n.selectThemeMode),
content: Column(
mainAxisSize: MainAxisSize.min,
children: ThemeMode.values.map((mode) {
return RadioListTile<ThemeMode>(
title: Text(_getThemeModeText(mode, l10n)),
value: mode,
groupValue: currentMode,
onChanged: (value) {
if (value != null) {
cubit.changeThemeMode(value);
Navigator.pop(context);
}
},
);
}).toList(),
),
);
},
);
}

View File

@@ -1,9 +1,24 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:kmobile/data/repositories/auth_repository.dart';
import 'package:kmobile/features/profile/change_password/change_password_screen.dart';
import 'package:kmobile/features/profile/logout_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../di/injection.dart';
import '../../l10n/app_localizations.dart';
import 'package:kmobile/features/profile/preferences/preference_screen.dart'; import 'package:kmobile/features/profile/preferences/preference_screen.dart';
class ProfileScreen extends StatelessWidget { class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key}); const ProfileScreen({super.key});
Future<void> _handleLogout(BuildContext context) async {
final auth = getIt<AuthRepository>();
final prefs = await SharedPreferences.getInstance();
await prefs.clear(); // clear saved session/token
await auth.clearAuthTokens();
// Navigate to login and remove all previous routes
Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -17,16 +32,39 @@ class ProfileScreen extends StatelessWidget {
children: [ children: [
ListTile( ListTile(
leading: const Icon(Icons.settings), leading: const Icon(Icons.settings),
title: Text(loc.preferences), // Localized "Preferences" title: Text(loc.preferences),
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (_) => const PreferenceScreen(), builder: (context) => const PreferenceScreen()),
),
); );
}, },
), ),
ListTile(
leading: const Icon(Icons.password),
title: Text(loc.changeLoginPassword),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ChangePasswordScreen()),
);
},
),
ListTile(
leading: const Icon(Icons.logout),
title: Text(AppLocalizations.of(context).logout),
onTap: () async {
final shouldLogout = await showDialog<bool>(
context: context,
builder: (_) => const LogoutDialog(),
);
if (shouldLogout == true) {
await _handleLogout(context);
}
},
),
// You can add more profile options here later // You can add more profile options here later
], ],
), ),

View File

@@ -1,9 +1,21 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'dart:async';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:kmobile/api/services/imps_service.dart';
import 'package:kmobile/api/services/neft_service.dart';
import 'package:kmobile/api/services/rtgs_service.dart';
import 'package:kmobile/data/models/imps_transaction.dart';
import 'package:kmobile/data/models/neft_transaction.dart';
import 'package:kmobile/data/models/payment_response.dart';
import 'package:kmobile/data/models/rtgs_transaction.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_pin_screen.dart';
import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_swipe_button/flutter_swipe_button.dart'; import 'package:flutter_swipe_button/flutter_swipe_button.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import '../../../../di/injection.dart';
import '../../../../api/services/beneficiary_service.dart';
class QuickPayOutsideBankScreen extends StatefulWidget { class QuickPayOutsideBankScreen extends StatefulWidget {
final String debitAccount; final String debitAccount;
@@ -26,21 +38,83 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
final ifscController = TextEditingController(); final ifscController = TextEditingController();
final phoneController = TextEditingController(); final phoneController = TextEditingController();
final amountController = TextEditingController(); final amountController = TextEditingController();
final service = getIt<BeneficiaryService>();
//String accountType = 'Savings';
late String accountType; late String accountType;
bool _isValidating = false;
bool _isBeneficiaryValidated = false;
String? _validationError;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() { setState(() {
accountType = AppLocalizations.of(context).savings; accountType = 'Savings';
}); });
}); });
} }
//final List<String> transactionModes = ['NEFT', 'RTGS', 'IMPS']; void _validateIFSC() async {
final ifsc = ifscController.text.trim().toUpperCase();
if (ifsc.isEmpty) return;
final result = await service.validateIFSC(ifsc);
if (mounted) {
if (result.bankName == '') {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context).invalidIfsc)),
);
bankNameController.clear();
branchNameController.clear();
} else {
bankNameController.text = result.bankName;
branchNameController.text = result.branchName;
}
}
}
void _validateBeneficiary() async {
FocusScope.of(context).unfocus();
setState(() {
_isValidating = true;
_validationError = null;
_isBeneficiaryValidated = false;
nameController.text = ''; // clear previous name
});
final String accountNo = accountNumberController.text.trim();
final String ifsc = ifscController.text.trim();
final String remitter = "Unknown";
final service = getIt<BeneficiaryService>();
try {
final String beneficiaryName = await service.validateBeneficiary(
accountNo: accountNo,
ifscCode: ifsc,
remitterName: remitter,
);
setState(() {
nameController.text = beneficiaryName;
_isBeneficiaryValidated = true;
_validationError = null;
});
} catch (e) {
setState(() {
_validationError = e.toString();
_isBeneficiaryValidated = false;
});
} finally {
if (mounted) {
setState(() {
_isValidating = false;
});
}
}
}
List<String> transactionModes(BuildContext context) { List<String> transactionModes(BuildContext context) {
return [ return [
AppLocalizations.of(context).neft, AppLocalizations.of(context).neft,
@@ -65,36 +139,243 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
super.dispose(); super.dispose();
} }
void _onProceedToPay() {
if (_formKey.currentState!.validate()) {
if (!_isBeneficiaryValidated) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text(AppLocalizations.of(context).plsValidateBeneficiary)),
);
return;
}
final amount = double.tryParse(amountController.text) ?? 0;
final selectedMode = transactionModes(context)[selectedTransactionIndex];
final isRtgs = selectedMode == AppLocalizations.of(context).rtgs;
final isNeft = selectedMode == AppLocalizations.of(context).neft;
final isImps = selectedMode == AppLocalizations.of(context).imps;
if (isRtgs && amount < 200000) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(AppLocalizations.of(context).invalidRtgs),
content: Text(AppLocalizations.of(context).invalidRtgsPopUp),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text(AppLocalizations.of(context).ok),
),
],
),
);
return;
}
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TransactionPinScreen(
onPinCompleted: (pinScreenContext, tpin) async {
if (isNeft) {
// NEFT
final neftTx = NeftTransaction(
fromAccount: widget.debitAccount,
toAccount: accountNumberController.text,
amount: amountController.text,
ifscCode: ifscController.text,
remitterName: "Unknown",
beneficiaryName: nameController.text,
tpin: tpin,
);
final neftService = getIt<NeftService>();
final completer = Completer<PaymentResponse>();
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final neftResponse =
await neftService.processNeftTransaction(neftTx);
final paymentResponse = PaymentResponse(
isSuccess: neftResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: neftTx.toAccount,
amount: neftTx.amount,
currency: 'INR',
utr: neftResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
String errorMessage;
if (e.response != null && e.response!.data != null) {
try {
// final error = jsonDecode(e.response!.toString())['error'];
final error = e.response?.data['error'];
errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
}[error] ??
"Something Went Wrong";
} catch (_) {
errorMessage = "Something Went Wrong";
}
} else {
errorMessage = "Something Went Wrong";
}
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: e.toString(),
);
completer.complete(paymentResponse);
}
}
if (isImps) {
// IMPS
final impsTx = ImpsTransaction(
fromAccount: widget.debitAccount,
toAccount: accountNumberController.text,
amount: amountController.text,
ifscCode: ifscController.text,
remitterName: "Unknown",
beneficiaryName: nameController.text,
tpin: tpin,
);
final impsService = getIt<ImpsService>();
final completer = Completer<PaymentResponse>();
if (!pinScreenContext.mounted) {
return;
}
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final impsResponse =
await impsService.processImpsTransaction(impsTx);
final paymentResponse = PaymentResponse(
isSuccess: impsResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: impsTx.toAccount,
amount: impsTx.amount,
currency: 'INR',
utr: impsResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
final error = e.response?.data['error'];
var errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
}[error] ??
"Something Went Wrong";
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: e.toString(),
);
completer.complete(paymentResponse);
}
}
if (isRtgs) {
// RTGS
final rtgsTx = RtgsTransaction(
fromAccount: widget.debitAccount,
toAccount: accountNumberController.text,
amount: amountController.text,
ifscCode: ifscController.text,
remitterName: "Unknown",
beneficiaryName: nameController.text,
tpin: tpin,
);
final rtgsService = getIt<RtgsService>();
final completer = Completer<PaymentResponse>();
if (!pinScreenContext.mounted) {
return;
}
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: completer.future),
),
);
try {
final rtgsResponse =
await rtgsService.processRtgsTransaction(rtgsTx);
final paymentResponse = PaymentResponse(
isSuccess: rtgsResponse.message.toUpperCase() == 'SUCCESS',
date: DateTime.now(),
creditedAccount: rtgsTx.toAccount,
amount: rtgsTx.amount,
currency: 'INR',
utr: rtgsResponse.utr,
);
completer.complete(paymentResponse);
} on DioException catch (e) {
log('dio exception');
final error = e.response?.data['error'];
var errorMessage = {
"INCORRECT_TPIN": "Please Enter the correct TPIN",
"INSUFFICIENT_FUNDS":
"Your account does not have sufficient balance"
}[error] ??
"Something Went Wrong";
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: errorMessage,
);
completer.complete(paymentResponse);
} catch (e) {
final paymentResponse = PaymentResponse(
isSuccess: false,
errorMessage: e.toString(),
);
completer.complete(paymentResponse);
}
}
},
),
),
);
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).quickPayOutsideBank, AppLocalizations.of(context).quickPayOutsideBank,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
@@ -103,40 +384,55 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
child: ListView( child: ListView(
children: [ children: [
const SizedBox(height: 10), const SizedBox(height: 10),
Row( Text(
children: [ AppLocalizations.of(context).debitFrom,
Text(AppLocalizations.of(context).debitFrom), style: Theme.of(context).textTheme.titleSmall,
Text(
widget.debitAccount,
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.w500),
)
],
), ),
const SizedBox(height: 20), Card(
elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: ListTile(
leading: Image.asset(
'assets/images/logo.png',
width: 40,
height: 40,
),
title: Text(widget.debitAccount),
subtitle: Text(AppLocalizations.of(context).ownBank),
),
),
const SizedBox(height: 24),
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).accountNumber, labelText: AppLocalizations.of(context).accountNumber,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
controller: accountNumberController, controller: accountNumberController,
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
obscureText: true, obscureText: true,
textInputAction: TextInputAction.next, textInputAction: TextInputAction.next,
onChanged: (value) {
nameController.clear();
setState(() {
_isBeneficiaryValidated = false;
});
},
validator: (value) { validator: (value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return AppLocalizations.of(context).accountNumberRequired; return AppLocalizations.of(context).accountNumberRequired;
} else if (value.length != 11) { } else if (value.length < 7 || value.length > 20) {
return AppLocalizations.of(context).validAccountNumber; return AppLocalizations.of(context).accno7to20;
} }
return null; return null;
}, },
@@ -147,15 +443,17 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).confirmAccountNumber, labelText: AppLocalizations.of(context).confirmAccountNumber,
// prefixIcon: Icon(Icons.person), // prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
@@ -171,130 +469,88 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
}, },
), ),
const SizedBox(height: 25), const SizedBox(height: 25),
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).name,
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
controller: nameController,
keyboardType: TextInputType.name,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).nameRequired;
}
return null;
},
),
const SizedBox(height: 25),
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).bankName,
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
controller: bankNameController,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).bankNameRequired;
}
return null;
},
),
const SizedBox(height: 25),
TextFormField(
decoration: InputDecoration(
labelText: AppLocalizations.of(context).branchName,
border: OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
controller: branchNameController,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).branchNameRequired;
}
return null;
},
),
const SizedBox(height: 25),
Row( Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded( Expanded(
child: TextFormField( child: TextFormField(
decoration: InputDecoration( maxLength: 11,
labelText: AppLocalizations.of(context).ifscCode, inputFormatters: [
border: OutlineInputBorder(), LengthLimitingTextInputFormatter(11),
isDense: true, ],
filled: true, decoration: InputDecoration(
fillColor: Colors.white, labelText: AppLocalizations.of(context).ifscCode,
enabledBorder: OutlineInputBorder( border: const OutlineInputBorder(),
borderSide: BorderSide(color: Colors.black), isDense: true,
), filled: true,
focusedBorder: OutlineInputBorder( fillColor: Theme.of(context).scaffoldBackgroundColor,
borderSide: BorderSide(color: Colors.black, width: 2), enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2),
),
), ),
controller: ifscController,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
_validateIFSC();
},
onChanged: (value) {
final trimmed = value.trim().toUpperCase();
if (trimmed.length < 11) {
// clear bank/branch if backspace or changed
bankNameController.clear();
branchNameController.clear();
}
},
validator: (value) {
final pattern = RegExp(r'^[A-Z]{4}0[A-Z0-9]{6}$');
if (value == null || value.trim().isEmpty) {
return AppLocalizations.of(context).enterIfsc;
} else if (!pattern.hasMatch(
value.trim().toUpperCase(),
)) {
return AppLocalizations.of(
context,
).invalidIfscFormat;
}
return null;
},
), ),
controller: ifscController, ),
textInputAction: TextInputAction.next, const SizedBox(
validator: (value) { width: 10,
if (value == null || value.isEmpty) { ),
return AppLocalizations.of(context).ifscRequired;
}
return null;
},
)),
const SizedBox(width: 10),
Expanded( Expanded(
child: DropdownButtonFormField<String>( child: DropdownButtonFormField<String>(
value: accountType, value: accountType,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).accountType, labelText: AppLocalizations.of(context).accountType,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2),
), ),
), ),
items: [ items: [
AppLocalizations.of(context).savings, 'Savings',
AppLocalizations.of(context).current 'Current',
] ]
.map((e) => DropdownMenuItem( .map(
value: e, (e) => DropdownMenuItem(value: e, child: Text(e)),
child: Text(e), )
))
.toList(), .toList(),
onChanged: (value) => setState(() { onChanged: (value) => setState(() {
accountType = value!; accountType = value!;
@@ -304,6 +560,114 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
], ],
), ),
const SizedBox(height: 25), const SizedBox(height: 25),
TextFormField(
controller: bankNameController,
enabled: false,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).bankName,
border: const OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Theme.of(context).dialogBackgroundColor,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
),
),
),
const SizedBox(height: 25),
TextFormField(
controller: branchNameController,
enabled: false,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).branchName,
border: const OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Theme.of(context).dialogBackgroundColor,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
),
),
),
const SizedBox(height: 24),
if (!_isBeneficiaryValidated)
Padding(
padding: const EdgeInsets.only(bottom: 24),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isValidating
? null
: () {
if (confirmAccountNumberController.text ==
accountNumberController.text) {
_validateBeneficiary();
} else {
setState(() {
_validationError =
AppLocalizations.of(context)
.accountMismatch;
});
}
},
child: _isValidating
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
AppLocalizations.of(context).validateBeneficiary),
),
),
),
if (_validationError != null)
Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Text(
_validationError!,
style:
TextStyle(color: Theme.of(context).colorScheme.error),
),
),
TextFormField(
controller: nameController,
enabled: false,
decoration: InputDecoration(
labelText: AppLocalizations.of(context).name,
border: const OutlineInputBorder(),
isDense: true,
filled: true,
fillColor: Theme.of(context).dialogBackgroundColor,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return AppLocalizations.of(context).nameRequired;
}
return null;
},
),
const SizedBox(height: 25),
Row( Row(
children: [ children: [
Expanded( Expanded(
@@ -312,16 +676,19 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
keyboardType: TextInputType.phone, keyboardType: TextInputType.phone,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).phone, labelText: AppLocalizations.of(context).phone,
prefixIcon: Icon(Icons.phone), prefixIcon: const Icon(Icons.phone),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2),
), ),
), ),
textInputAction: TextInputAction.next, textInputAction: TextInputAction.next,
@@ -335,15 +702,18 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
child: TextFormField( child: TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).amount, labelText: AppLocalizations.of(context).amount,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2),
), ),
), ),
controller: amountController, controller: amountController,
@@ -366,50 +736,33 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
const SizedBox(height: 30), const SizedBox(height: 30),
Row( Row(
children: [ children: [
Text(AppLocalizations.of(context).transactionMode, Text(
style: TextStyle(fontWeight: FontWeight.w500)), AppLocalizations.of(context).transactionMode,
style: const TextStyle(fontWeight: FontWeight.w500),
),
const SizedBox(width: 12), const SizedBox(width: 12),
Expanded(child: buildTransactionModeSelector()), Expanded(child: buildTransactionModeSelector()),
], ],
), ),
const SizedBox(height: 45), const SizedBox(height: 45),
Align( Align(
alignment: Alignment.center, alignment: Alignment.center,
child: SwipeButton.expand( child: SwipeButton.expand(
thumb: const Icon( thumb: Icon(Icons.arrow_forward,
Icons.arrow_forward, color: Theme.of(context).dialogBackgroundColor),
color: Colors.white, activeThumbColor: Theme.of(context).colorScheme.primary,
), activeTrackColor:
activeThumbColor: Colors.blue[900], Theme.of(context).colorScheme.secondary.withAlpha(100),
activeTrackColor: Colors.blue.shade100, borderRadius: BorderRadius.circular(30),
borderRadius: BorderRadius.circular(30), height: 56,
height: 56, onSwipe: _onProceedToPay,
child: Text( child: Text(
AppLocalizations.of(context).swipeToPay, AppLocalizations.of(context).swipeToPay,
style: style: const TextStyle(
TextStyle(fontSize: 16, fontWeight: FontWeight.bold), fontSize: 16, fontWeight: FontWeight.bold),
), ),
onSwipe: () { ),
if (_formKey.currentState!.validate()) { ),
// Perform payment logic
final selectedMode =
transactionModes(context)[selectedTransactionIndex];
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${AppLocalizations.of(context).payingVia} $selectedMode...')),
);
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
// const TransactionPinScreen(
// transactionData: {},
// transactionCode: 'PAYMENT',
// )));
}
},
)),
], ],
), ),
), ),
@@ -432,19 +785,22 @@ class _QuickPayOutsideBankScreen extends State<QuickPayOutsideBankScreen> {
margin: const EdgeInsets.symmetric(horizontal: 4), margin: const EdgeInsets.symmetric(horizontal: 4),
padding: const EdgeInsets.symmetric(vertical: 5), padding: const EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration( decoration: BoxDecoration(
color: isSelected ? Colors.blue[200] : Colors.white, color: isSelected
? Theme.of(context).colorScheme.primary
: Theme.of(context).scaffoldBackgroundColor,
borderRadius: BorderRadius.circular(5), borderRadius: BorderRadius.circular(5),
border: Border.all( border: Border.all(
color: isSelected ? Colors.blue : Colors.grey, color: isSelected
? Theme.of(context).colorScheme.primary
: Theme.of(context).scaffoldBackgroundColor,
width: isSelected ? 0 : 1.2, width: isSelected ? 0 : 1.2,
), ),
), ),
alignment: Alignment.center, alignment: Alignment.center,
child: Text( child: Text(
transactionModes(context)[index], transactionModes(context)[index],
style: const TextStyle( style:
color: Colors.black, TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
), ),
), ),
), ),

View File

@@ -1,9 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:kmobile/features/quick_pay/screens/quick_pay_outside_bank_screen.dart'; import 'package:kmobile/features/quick_pay/screens/quick_pay_outside_bank_screen.dart';
import 'package:kmobile/features/quick_pay/screens/quick_pay_within_bank_screen.dart'; import 'package:kmobile/features/quick_pay/screens/quick_pay_within_bank_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import '../../../l10n/app_localizations.dart';
class QuickPayScreen extends StatefulWidget { class QuickPayScreen extends StatefulWidget {
final String debitAccount; final String debitAccount;
@@ -18,32 +17,9 @@ class _QuickPayScreen extends State<QuickPayScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).quickPay, AppLocalizations.of(context).quickPay.replaceAll('\n', ''),
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
), ),
centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: ListView( body: ListView(
children: [ children: [
@@ -52,30 +28,31 @@ class _QuickPayScreen extends State<QuickPayScreen> {
label: AppLocalizations.of(context).ownBank, label: AppLocalizations.of(context).ownBank,
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => QuickPayWithinBankScreen( builder: (context) => QuickPayWithinBankScreen(
debitAccount: widget.debitAccount))); debitAccount: widget.debitAccount,
),
),
);
}, },
), ),
const Divider( const Divider(height: 1),
height: 1,
),
QuickPayManagementTile( QuickPayManagementTile(
//disable: true,
icon: Symbols.output_circle, icon: Symbols.output_circle,
label: AppLocalizations.of(context).outsideBank, label: AppLocalizations.of(context).outsideBank,
onTap: () { onTap: () {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => QuickPayOutsideBankScreen( builder: (context) => QuickPayOutsideBankScreen(
debitAccount: widget.debitAccount))); debitAccount: widget.debitAccount,
),
),
);
}, },
), ),
const Divider( const Divider(height: 1),
height: 1,
),
], ],
), ),
); );

View File

@@ -1,9 +1,12 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_swipe_button/flutter_swipe_button.dart'; import 'package:flutter_swipe_button/flutter_swipe_button.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/data/models/transfer.dart'; import 'package:kmobile/data/models/transfer.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:kmobile/di/injection.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import '../../../l10n/app_localizations.dart';
import '../../fund_transfer/screens/transaction_pin_screen.dart'; import '../../fund_transfer/screens/transaction_pin_screen.dart';
class QuickPayWithinBankScreen extends StatefulWidget { class QuickPayWithinBankScreen extends StatefulWidget {
@@ -23,36 +26,75 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
final TextEditingController amountController = TextEditingController(); final TextEditingController amountController = TextEditingController();
String? _selectedAccountType; String? _selectedAccountType;
String? _beneficiaryName;
bool _isValidating = false;
bool _isBeneficiaryValidated = false;
String? _validationError;
@override
void initState() {
super.initState();
accountNumberController.addListener(_resetBeneficiaryValidation);
confirmAccountNumberController.addListener(_resetBeneficiaryValidation);
}
void _resetBeneficiaryValidation() {
if (_isBeneficiaryValidated ||
_beneficiaryName != null ||
_validationError != null) {
setState(() {
_isBeneficiaryValidated = false;
_beneficiaryName = null;
_validationError = null;
});
}
}
@override
void dispose() {
accountNumberController.removeListener(_resetBeneficiaryValidation);
confirmAccountNumberController.removeListener(_resetBeneficiaryValidation);
accountNumberController.dispose();
confirmAccountNumberController.dispose();
amountController.dispose();
super.dispose();
}
Future<void> _validateBeneficiary() async {
var beneficiaryService = getIt<BeneficiaryService>();
setState(() {
_isValidating = true;
_validationError = null;
});
try {
final name = await beneficiaryService
.validateBeneficiaryWithinBank(accountNumberController.text);
setState(() {
_beneficiaryName = name;
_isBeneficiaryValidated = true;
_isValidating = false;
});
} catch (e) {
setState(() {
_validationError = "Account Number not from KCCB";
_isValidating = false;
_isBeneficiaryValidated = false;
_beneficiaryName = null;
});
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Symbols.arrow_back_ios_new),
onPressed: () {
Navigator.pop(context);
},
),
title: Text( title: Text(
AppLocalizations.of(context).quickPayOwnBank, AppLocalizations.of(context).quickPayOwnBank,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w500),
), ),
centerTitle: false, centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(right: 10.0),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
radius: 20,
child: SvgPicture.asset(
'assets/images/avatar_male.svg',
width: 40,
height: 40,
fit: BoxFit.cover,
),
),
),
],
), ),
body: Padding( body: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
@@ -64,10 +106,10 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).debitAccountNumber, labelText: AppLocalizations.of(context).debitAccountNumber,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
), ),
readOnly: true, readOnly: true,
controller: TextEditingController(text: widget.debitAccount), controller: TextEditingController(text: widget.debitAccount),
@@ -79,15 +121,17 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).accountNumber, labelText: AppLocalizations.of(context).accountNumber,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
controller: accountNumberController, controller: accountNumberController,
@@ -103,30 +147,23 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
return null; return null;
}, },
), ),
// const Align(
// alignment: Alignment.topLeft,
// child: Padding(
// padding: EdgeInsets.only(left: 15.0, top: 5),
// child: Text(
// 'Beneficiary Account Number',
// style: TextStyle(color: Colors.black54),
// ),
// )),
const SizedBox(height: 25), const SizedBox(height: 25),
TextFormField( TextFormField(
controller: confirmAccountNumberController, controller: confirmAccountNumberController,
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).confirmAccountNumber, labelText: AppLocalizations.of(context).confirmAccountNumber,
// prefixIcon: Icon(Icons.person), // prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
@@ -141,20 +178,78 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
return null; return null;
}, },
), ),
if (!_isBeneficiaryValidated)
Padding(
padding: const EdgeInsets.only(top: 12.0),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isValidating
? null
: () {
if (accountNumberController.text.length == 11 &&
confirmAccountNumberController.text ==
accountNumberController.text) {
_validateBeneficiary();
} else {
setState(() {
_validationError =
AppLocalizations.of(context)
.accountMismatch;
});
}
},
child: _isValidating
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
AppLocalizations.of(context).validateBeneficiary),
),
),
),
if (_beneficiaryName != null && _isBeneficiaryValidated)
Padding(
padding: const EdgeInsets.only(top: 12.0),
child: Row(
children: [
const Icon(Icons.check_circle, color: Colors.green),
const SizedBox(width: 8),
Text(
'${AppLocalizations.of(context).beneficiaryName}: $_beneficiaryName',
style: const TextStyle(
color: Colors.green, fontWeight: FontWeight.bold),
),
],
),
),
if (_validationError != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_validationError!,
style: const TextStyle(color: Colors.red),
),
),
const SizedBox(height: 24), const SizedBox(height: 24),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
decoration: InputDecoration( decoration: InputDecoration(
labelText: labelText: AppLocalizations.of(
AppLocalizations.of(context).beneficiaryAccountType, context,
border: OutlineInputBorder(), ).beneficiaryAccountType,
border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
value: _selectedAccountType, value: _selectedAccountType,
@@ -180,28 +275,21 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
return null; return null;
}, },
), ),
// const Align(
// alignment: Alignment.topLeft,
// child: Padding(
// padding: EdgeInsets.only(left: 15.0, top: 5),
// child: Text(
// 'Beneficiary Account Type',
// style: TextStyle(color: Colors.black54),
// ),
// )),
const SizedBox(height: 25), const SizedBox(height: 25),
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: AppLocalizations.of(context).amount, labelText: AppLocalizations.of(context).amount,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).scaffoldBackgroundColor,
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
controller: amountController, controller: amountController,
@@ -222,52 +310,59 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
Align( Align(
alignment: Alignment.center, alignment: Alignment.center,
child: SwipeButton.expand( child: SwipeButton.expand(
thumb: const Icon( thumb: Icon(Icons.arrow_forward,
Icons.arrow_forward, color: Theme.of(context).dialogBackgroundColor),
color: Colors.white, activeThumbColor: Theme.of(context).colorScheme.primary,
), activeTrackColor: Theme.of(
activeThumbColor: Theme.of(context).primaryColor, context,
activeTrackColor: ).colorScheme.secondary.withAlpha(100),
Theme.of(context).colorScheme.secondary.withAlpha(100),
borderRadius: BorderRadius.circular(30), borderRadius: BorderRadius.circular(30),
height: 56, height: 56,
child: Text( child: Text(
AppLocalizations.of(context).swipeToPay, AppLocalizations.of(context).swipeToPay,
style: TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
onSwipe: () { onSwipe: () {
if (_formKey.currentState!.validate()) { if (_formKey.currentState!.validate()) {
if (!_isBeneficiaryValidated) {
setState(() {
_validationError = AppLocalizations.of(context)
.validateBeneficiaryproceeding;
});
return;
}
// Perform payment logic // Perform payment logic
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => TransactionPinScreen( builder: (context) => TransactionPinScreen(
transactionData: Transfer( onPinCompleted: (pinScreenContext, tpin) async {
fromAccount: widget.debitAccount, final transfer = Transfer(
toAccount: accountNumberController.text, fromAccount: widget.debitAccount,
toAccountType: _selectedAccountType!, toAccount: accountNumberController.text,
amount: amountController.text, toAccountType: _selectedAccountType!,
), amount: amountController.text,
))); tpin: tpin,
);
final paymentService = getIt<PaymentService>();
final paymentResponseFuture = paymentService
.processQuickPayWithinBank(transfer);
Navigator.of(pinScreenContext).pushReplacement(
MaterialPageRoute(
builder: (_) => PaymentAnimationScreen(
paymentResponse: paymentResponseFuture),
),
);
},
),
),
);
} }
}, },
), ),
), ),
// SliderButton(
// action: () async {
// ///Do something here OnSlide
// return true;
// },
// label: const Text(
// "Slide to pay",
// style: TextStyle(
// color: Color(0xff4a4a4a),
// fontWeight: FontWeight.w500,
// fontSize: 17),
// ),
// icon: Icon(Symbols.arrow_forward,
// color: Theme.of(context).primaryColor, weight: 200),
// )
], ],
), ),
), ),
@@ -290,12 +385,13 @@ class _QuickPayWithinBankScreen extends State<QuickPayWithinBankScreen> {
border: const OutlineInputBorder(), border: const OutlineInputBorder(),
isDense: true, isDense: true,
filled: true, filled: true,
fillColor: Colors.white, fillColor: Theme.of(context).dialogBackgroundColor,
enabledBorder: const OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black), borderSide: BorderSide(color: Theme.of(context).colorScheme.outline),
), ),
focusedBorder: const OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2), borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary, width: 2),
), ),
), ),
); );

View File

@@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lottie/lottie.dart';
class SecurityErrorScreen extends StatelessWidget {
final String message;
const SecurityErrorScreen({Key? key, required this.message}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Lottie.asset('assets/animations/error.json', height: 200),
const SizedBox(height: 20),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: () => SystemChannels.platform.invokeMethod('SystemNavigator.pop'),
child: const Text('Okay'),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,124 @@
import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart';
class Branch {
final String name;
final String code;
final String ifsc;
final String address;
Branch({
required this.name,
required this.code,
required this.ifsc,
required this.address,
});
}
class BranchLocatorScreen extends StatefulWidget {
const BranchLocatorScreen({super.key});
@override
State<BranchLocatorScreen> createState() => _BranchLocatorScreenState();
}
class _BranchLocatorScreenState extends State<BranchLocatorScreen> {
final TextEditingController _searchController = TextEditingController();
// Static list of 2 branches
final List<Branch> _branches = [
Branch(
name: "Dharamsala - Head Office",
code: "002",
ifsc: "KACE0000002",
address: "Civil Lines Dharmashala, Kangra, HP - 176215"),
Branch(
name: "Kangra",
code: "033",
ifsc: "KACE0000033",
address: "Rajput Bhawankangrapo, Kangra, HP "),
];
List<Branch> _filteredBranches = [];
@override
void initState() {
super.initState();
_filteredBranches = _branches; // Initially show all branches
}
void _filterBranches(String query) {
setState(() {
if (query.isEmpty) {
_filteredBranches = _branches;
} else {
_filteredBranches = _branches.where((branch) {
final lowerQuery = query.toLowerCase();
return branch.name.toLowerCase().contains(lowerQuery) ||
branch.code.toLowerCase().contains(lowerQuery) ||
branch.ifsc.toLowerCase().contains(lowerQuery) ||
branch.address.toLowerCase().contains(lowerQuery);
}).toList();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).branchLocator),
),
body: Column(
children: [
// Search bar
Padding(
padding: const EdgeInsets.all(12.0),
child: TextField(
controller: _searchController,
onChanged: _filterBranches,
decoration: InputDecoration(
hintText: AppLocalizations.of(context).searchbranchby,
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
// List of branches
Expanded(
child: _filteredBranches.isEmpty
? const Center(child: Text("No matching branches found"))
: ListView.builder(
itemCount: _filteredBranches.length,
itemBuilder: (context, index) {
final branch = _filteredBranches[index];
return Card(
margin: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
child: ListTile(
leading: Icon(Icons.location_city,
color: Theme.of(context).colorScheme.primary),
title: Text(branch.name,
style:
const TextStyle(fontWeight: FontWeight.bold)),
subtitle: Text(
"Code: ${branch.code} | IFSC: ${branch.ifsc} \nBranch Address: ${branch.address}"),
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Selected ${branch.name}")),
);
},
),
);
},
),
),
],
),
);
}
}

View File

@@ -1,4 +1,6 @@
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:kmobile/features/service/screens/branch_locator_screen.dart';
import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
@@ -11,99 +13,91 @@ class ServiceScreen extends StatefulWidget {
} }
class _ServiceScreen extends State<ServiceScreen> { class _ServiceScreen extends State<ServiceScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
title: Text( title: Text(
AppLocalizations.of(context).services, AppLocalizations.of(context).services,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500), ),
centerTitle: false,
),
body: ListView(
children: [
ServiceManagementTile(
icon: Symbols.add,
label: AppLocalizations.of(context).accountOpeningDeposit,
onTap: () {},
disabled: true, // Add this
), ),
centerTitle: false, const Divider(height: 1),
actions: [ ServiceManagementTile(
// IconButton( icon: Symbols.add,
// icon: const Icon(Icons.notifications_outlined), label: AppLocalizations.of(context).accountOpeningLoan,
// onPressed: () { onTap: () {},
// // Navigate to notifications disabled: true, // Add this
// }, ),
// ), const Divider(height: 1),
Padding( ServiceManagementTile(
padding: const EdgeInsets.only(right: 10.0), icon: Symbols.captive_portal,
child: InkWell( label: AppLocalizations.of(context).quickLinks,
borderRadius: BorderRadius.circular(20), onTap: () {},
onTap: () { disabled: true, // Add this
// Navigator.push(context, MaterialPageRoute( ),
// builder: (context) => const CustomerInfoScreen())); const Divider(height: 1),
}, ServiceManagementTile(
child: const CircleAvatar( icon: Symbols.missing_controller,
backgroundImage: AssetImage( label: AppLocalizations.of(context).branchLocator,
'assets/images/avatar.jpg'), // Replace with your image onTap: () {
radius: 20, Navigator.push(
), context,
), MaterialPageRoute(
), builder: (context) => const BranchLocatorScreen()));
], },
), disabled: true, // Add this
body: ListView( ),
children: [ const Divider(height: 1),
ServiceManagementTile( ],
icon: Symbols.add, ),
label: AppLocalizations.of(context).accountOpeningDeposit, );
onTap: () {}, }
),
const Divider(
height: 1,
),
ServiceManagementTile(
icon: Symbols.add,
label: AppLocalizations.of(context).accountOpeningLoan,
onTap: () {},
),
const Divider(
height: 1,
),
ServiceManagementTile(
icon: Symbols.captive_portal,
label: AppLocalizations.of(context).quickLinks,
onTap: () {},
),
const Divider(
height: 1,
),
ServiceManagementTile(
icon: Symbols.missing_controller,
label: AppLocalizations.of(context).branchLocator,
onTap: () {},
),
const Divider(
height: 1,
)
],
),
);
}
} }
class ServiceManagementTile extends StatelessWidget { class ServiceManagementTile extends StatelessWidget {
final IconData icon; final IconData icon;
final String label; final String label;
final VoidCallback onTap; final VoidCallback onTap;
final bool disabled; // Add this line
const ServiceManagementTile({ const ServiceManagementTile({
super.key, super.key,
required this.icon, required this.icon,
required this.label, required this.label,
required this.onTap, required this.onTap,
this.disabled = false, // Add this line
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListTile( return ListTile(
leading: Icon(icon), leading: Icon(
title: Text(label), icon,
trailing: const Icon(Symbols.arrow_right, size: 20), color: disabled ? theme.disabledColor : null, // Change color when disabled
onTap: onTap, ),
title: Text(
label,
style: TextStyle(
color: disabled ? theme.disabledColor : null, // Change color when disabled
),
),
trailing: Icon(
Symbols.arrow_right,
size: 20,
color: disabled ? theme.disabledColor : null, // Change color when disabled
),
onTap: disabled ? null : onTap, // Disable onTap when disabled
); );
} }
} }

View File

@@ -4,7 +4,7 @@ class Transaction {
final double amount; final double amount;
final DateTime date; final DateTime date;
final String category; final String category;
Transaction({ Transaction({
required this.id, required this.id,
required this.description, required this.description,
@@ -12,4 +12,4 @@ class Transaction {
required this.date, required this.date,
required this.category, required this.category,
}); });
} }

Some files were not shown because too many files have changed in this diff Show More