Add initial project structure and configuration files for iOS and Android

This commit is contained in:
2025-04-10 23:24:52 +05:30
commit e5ab751a74
86 changed files with 3762 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
import 'package:dio/dio.dart';
import '../../data/repositories/auth_repository.dart';
class AuthInterceptor extends Interceptor {
final AuthRepository _authRepository;
final Dio _dio;
AuthInterceptor(this._authRepository, this._dio);
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
// Skip auth header for login and refresh endpoints
if (options.path.contains('/auth/login') ||
options.path.contains('/auth/refresh')) {
return handler.next(options);
}
// Get token and add to request
final token = await _authRepository.getAccessToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
return handler.next(options);
}
@override
Future<void> onError(
DioException err,
ErrorInterceptorHandler handler,
) async {
// Handle 401 errors by refreshing token and retrying
if (err.response?.statusCode == 401) {
// On 401, try to get a new token
final token = await _authRepository.getAccessToken();
if (token != null) {
// If we have a new token, retry the request
final opts = err.requestOptions;
opts.headers['Authorization'] = 'Bearer $token';
try {
final response = await _dio.fetch(opts);
return handler.resolve(response);
} on DioException catch (e) {
return handler.next(e);
}
}
}
return handler.next(err);
}
}

View File

@@ -0,0 +1,79 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import '../../features/auth/models/auth_token.dart';
import '../../features/auth/models/auth_credentials.dart';
import '../../data/models/user.dart';
import '../../core/errors/exceptions.dart';
class AuthService {
final Dio _dio;
AuthService(this._dio);
Future<AuthToken> login(AuthCredentials credentials) async {
try {
final response = await _dio.post(
'/auth/login',
data: credentials.toJson(),
);
if (response.statusCode == 200) {
return AuthToken.fromJson(response.data);
} else {
throw AuthException('Login failed');
}
} on DioException catch (e) {
if (e.response?.statusCode == 401) {
throw AuthException('Invalid credentials');
}
throw NetworkException('Network error during login');
} catch (e) {
throw UnexpectedException('Unexpected error during login: ${e.toString()}');
}
}
Future<AuthToken> refreshToken(String refreshToken) async {
try {
final response = await _dio.post(
'/auth/refresh',
data: {'refresh_token': refreshToken},
);
if (response.statusCode == 200) {
return AuthToken.fromJson(response.data);
} else {
throw AuthException('Token refresh failed');
}
} catch (e) {
throw AuthException('Failed to refresh token: ${e.toString()}');
}
}
Future<void> logout(String refreshToken) async {
try {
await _dio.post(
'/auth/logout',
data: {'refresh_token': refreshToken},
);
} catch (e) {
// We might want to just log this error rather than throwing,
// as logout should succeed even if the server call fails
log('Logout error: ${e.toString()}');
}
}
Future<User> getUserProfile() async {
try {
final response = await _dio.get('/auth/profile');
if (response.statusCode == 200) {
return User.fromJson(response.data);
} else {
throw AuthException('Failed to get user profile');
}
} catch (e) {
throw AuthException('Error fetching user profile: ${e.toString()}');
}
}
}

106
lib/app.dart Normal file
View File

@@ -0,0 +1,106 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'config/themes.dart';
import 'config/routes.dart';
import 'di/injection.dart';
import 'features/auth/controllers/auth_cubit.dart';
import 'features/auth/controllers/auth_state.dart';
import 'features/auth/screens/login_screen.dart';
import 'features/dashboard/screens/dashboard_screen.dart';
class KMobile extends StatelessWidget {
const KMobile({super.key});
@override
Widget build(BuildContext context) {
// Set status bar color
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark,
),
);
return MultiBlocProvider(
providers: [
BlocProvider<AuthCubit>(
create: (_) => getIt<AuthCubit>(),
),
// Add other Bloc/Cubit providers here
],
child: MaterialApp(
title: 'Banking App',
debugShowCheckedModeBanner: false,
theme: AppThemes.lightTheme,
darkTheme: AppThemes.darkTheme,
themeMode: ThemeMode.system, // Use system theme by default
onGenerateRoute: AppRoutes.generateRoute,
initialRoute: AppRoutes.splash,
builder: (context, child) {
return MediaQuery(
// Prevent font scaling to maintain design consistency
data: MediaQuery.of(context)
.copyWith(textScaler: const TextScaler.linear(1.0)),
child: child!,
);
},
home: BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
// Handle different authentication states
if (state is AuthInitial || state is AuthLoading) {
return const _SplashScreen();
}
if (state is Authenticated) {
return const DashboardScreen();
}
return const LoginScreen();
},
),
),
);
}
}
// Simple splash screen component
class _SplashScreen extends StatelessWidget {
const _SplashScreen();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Replace with your bank logo
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: 24),
const Text(
'SecureBank',
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
const CircularProgressIndicator(),
],
),
),
);
}
}

78
lib/config/routes.dart Normal file
View File

@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
import '../features/auth/screens/login_screen.dart';
// import '../features/auth/screens/forgot_password_screen.dart';
// import '../features/auth/screens/register_screen.dart';
import '../features/dashboard/screens/dashboard_screen.dart';
// import '../features/accounts/screens/accounts_screen.dart';
// import '../features/transactions/screens/transactions_screen.dart';
// import '../features/payments/screens/payments_screen.dart';
// import '../features/settings/screens/settings_screen.dart';
class AppRoutes {
// Private constructor to prevent instantiation
AppRoutes._();
// Route names
static const String splash = '/';
static const String login = '/login';
static const String register = '/register';
static const String forgotPassword = '/forgot-password';
static const String dashboard = '/dashboard';
static const String accounts = '/accounts';
static const String transactions = '/transactions';
static const String payments = '/payments';
// Route generator
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case login:
return MaterialPageRoute(builder: (_) => const LoginScreen());
case register:
// Placeholder - create the RegisterScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const RegisterScreen());
return _errorRoute();
case forgotPassword:
// Placeholder - create the ForgotPasswordScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const ForgotPasswordScreen());
return _errorRoute();
case dashboard:
return MaterialPageRoute(builder: (_) => const DashboardScreen());
case accounts:
// Placeholder - create the AccountsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const AccountsScreen());
return _errorRoute();
case transactions:
// Placeholder - create the TransactionsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const TransactionsScreen());
return _errorRoute();
case payments:
// Placeholder - create the PaymentsScreen class and uncomment
// return MaterialPageRoute(builder: (_) => const PaymentsScreen());
return _errorRoute();
default:
return _errorRoute();
}
}
// Error route
static Route<dynamic> _errorRoute() {
return MaterialPageRoute(builder: (_) {
return Scaffold(
appBar: AppBar(
title: const Text('Error'),
),
body: const Center(
child: Text('Route not found!'),
),
);
});
}
}

251
lib/config/themes.dart Normal file
View File

@@ -0,0 +1,251 @@
import 'package:flutter/material.dart';
class AppThemes {
// Private constructor to prevent instantiation
AppThemes._();
// Light theme colors
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),
),
displayMedium: TextStyle(
fontSize: 60,
fontWeight: FontWeight.w300,
color: Color(0xFF212121),
),
displaySmall: TextStyle(
fontSize: 48,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
),
headlineMedium: TextStyle(
fontSize: 34,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
),
headlineSmall: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
),
titleLarge: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Color(0xFF212121),
),
bodyLarge: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
),
bodyMedium: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Color(0xFF212121),
),
bodySmall: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: Color(0xFF757575),
),
labelLarge: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Color(0xFF212121),
),
);
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,
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,
),
textTheme: _textThemeLight,
appBarTheme: const AppBarTheme(
elevation: 0,
backgroundColor: _surfaceColorLight,
foregroundColor: Color(0xFF212121),
centerTitle: true,
),
cardTheme: CardTheme(
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 final ThemeData darkTheme = ThemeData(
useMaterial3: true,
colorScheme: const ColorScheme.dark(
primary: _primaryColorDark,
secondary: _secondaryColorDark,
error: _errorColorDark,
surface: _surfaceColorDark,
onPrimary: Colors.black,
onSecondary: Colors.black,
onSurface: Colors.white,
onError: Colors.black,
brightness: Brightness.dark,
),
textTheme: _textThemeDark,
appBarTheme: const AppBarTheme(
elevation: 0,
backgroundColor: _surfaceColorDark,
foregroundColor: Colors.white,
centerTitle: true,
),
cardTheme: CardTheme(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
color: const Color(0xFF2C2C2C),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.black,
backgroundColor: _primaryColorDark,
elevation: 2,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
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

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

27
lib/data/models/user.dart Normal file
View File

@@ -0,0 +1,27 @@
import 'package:equatable/equatable.dart';
class User extends Equatable {
final String id;
final String username;
final String email;
final String? phoneNumber;
const User({
required this.id,
required this.username,
required this.email,
this.phoneNumber,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
username: json['username'],
email: json['email'],
phoneNumber: json['phone_number'],
);
}
@override
List<Object?> get props => [id, username, email, phoneNumber];
}

View File

@@ -0,0 +1,118 @@
import '../../api/services/auth_service.dart';
import '../../features/auth/models/auth_token.dart';
import '../../features/auth/models/auth_credentials.dart';
import '../../data/models/user.dart';
import '../../security/secure_storage.dart';
class AuthRepository {
final AuthService _authService;
final SecureStorage _secureStorage;
static const _accessTokenKey = 'access_token';
static const _refreshTokenKey = 'refresh_token';
static const _tokenExpiryKey = 'token_expiry';
static const _userKey = 'user_data';
AuthRepository(this._authService, this._secureStorage);
Future<User> login(String username, String password) async {
// Create credentials and call service
final credentials = AuthCredentials(username: username, password: password);
final authToken = await _authService.login(credentials);
// Save token securely
await _saveAuthToken(authToken);
// Get and save user profile
final user = await _authService.getUserProfile();
await _saveUserData(user);
return user;
}
Future<bool> isLoggedIn() async {
final token = await _getAuthToken();
return token != null && !token.isExpired;
}
Future<void> logout() async {
final token = await _getAuthToken();
if (token != null) {
try {
await _authService.logout(token.refreshToken);
} finally {
// Clear stored data regardless of logout API success
await _clearAuthData();
}
}
}
Future<User?> getCurrentUser() async {
final userJson = await _secureStorage.read(_userKey);
if (userJson != null) {
return User.fromJson(userJson);
}
return null;
}
Future<String?> getAccessToken() async {
final token = await _getAuthToken();
if (token == null) return null;
// If token expired, try to refresh it
if (token.isExpired) {
final newToken = await _refreshToken(token.refreshToken);
if (newToken != null) {
return newToken.accessToken;
}
return null;
}
return token.accessToken;
}
// Private helper methods
Future<void> _saveAuthToken(AuthToken token) async {
await _secureStorage.write(_accessTokenKey, token.accessToken);
await _secureStorage.write(_refreshTokenKey, token.refreshToken);
await _secureStorage.write(_tokenExpiryKey, token.expiresAt.toIso8601String());
}
Future<AuthToken?> _getAuthToken() async {
final accessToken = await _secureStorage.read(_accessTokenKey);
final refreshToken = await _secureStorage.read(_refreshTokenKey);
final expiryString = await _secureStorage.read(_tokenExpiryKey);
if (accessToken != null && refreshToken != null && expiryString != null) {
return AuthToken(
accessToken: accessToken,
refreshToken: refreshToken,
expiresAt: DateTime.parse(expiryString),
);
}
return null;
}
Future<void> _saveUserData(User user) async {
await _secureStorage.write(_userKey, user);
}
Future<void> _clearAuthData() async {
await _secureStorage.delete(_accessTokenKey);
await _secureStorage.delete(_refreshTokenKey);
await _secureStorage.delete(_tokenExpiryKey);
await _secureStorage.delete(_userKey);
}
Future<AuthToken?> _refreshToken(String refreshToken) async {
try {
final newToken = await _authService.refreshToken(refreshToken);
await _saveAuthToken(newToken);
return newToken;
} catch (e) {
// If refresh fails, clear auth data
await _clearAuthData();
return null;
}
}
}

59
lib/di/injection.dart Normal file
View File

@@ -0,0 +1,59 @@
import 'package:get_it/get_it.dart';
import 'package:dio/dio.dart';
import '../api/services/auth_service.dart';
import '../api/interceptors/auth_interceptor.dart';
import '../data/repositories/auth_repository.dart';
import '../features/auth/controllers/auth_cubit.dart';
import '../security/secure_storage.dart';
final getIt = GetIt.instance;
Future<void> setupDependencies() async {
// Register Dio client
getIt.registerSingleton<Dio>(_createDioClient());
// Register secure storage
getIt.registerSingleton<SecureStorage>(SecureStorage());
// Register services
getIt.registerSingleton<AuthService>(AuthService(getIt<Dio>()));
// Register repositories
getIt.registerSingleton<AuthRepository>(
AuthRepository(getIt<AuthService>(), getIt<SecureStorage>()),
);
// Add auth interceptor after repository is available
getIt<Dio>().interceptors.add(
AuthInterceptor(getIt<AuthRepository>(), getIt<Dio>()),
);
// Register controllers/cubits
getIt.registerFactory<AuthCubit>(() => AuthCubit(getIt<AuthRepository>()));
}
Dio _createDioClient() {
final dio = Dio(
BaseOptions(
baseUrl: 'https://api.yourbank.com/v1',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 3),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
),
);
// Add logging interceptor for development
dio.interceptors.add(LogInterceptor(
request: true,
requestHeader: true,
requestBody: true,
responseHeader: true,
responseBody: true,
error: true,
));
return dio;
}

View File

@@ -0,0 +1,15 @@
class Account {
final String id;
final String accountNumber;
final String accountType;
final double balance;
final String currency;
Account({
required this.id,
required this.accountNumber,
required this.accountType,
required this.balance,
required this.currency,
});
}

View File

@@ -0,0 +1,50 @@
import 'package:bloc/bloc.dart';
import '../../../data/repositories/auth_repository.dart';
import 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
final AuthRepository _authRepository;
AuthCubit(this._authRepository) : super(AuthInitial()) {
checkAuthStatus();
}
Future<void> checkAuthStatus() async {
emit(AuthLoading());
try {
final isLoggedIn = await _authRepository.isLoggedIn();
if (isLoggedIn) {
final user = await _authRepository.getCurrentUser();
if (user != null) {
emit(Authenticated(user));
} else {
emit(Unauthenticated());
}
} else {
emit(Unauthenticated());
}
} catch (e) {
emit(AuthError(e.toString()));
}
}
Future<void> login(String username, String password) async {
emit(AuthLoading());
try {
final user = await _authRepository.login(username, password);
emit(Authenticated(user));
} catch (e) {
emit(AuthError(e.toString()));
}
}
Future<void> logout() async {
emit(AuthLoading());
try {
await _authRepository.logout();
emit(Unauthenticated());
} catch (e) {
emit(AuthError(e.toString()));
}
}
}

View File

@@ -0,0 +1,31 @@
import 'package:equatable/equatable.dart';
import '../../../data/models/user.dart';
abstract class AuthState extends Equatable {
@override
List<Object?> get props => [];
}
class AuthInitial extends AuthState {}
class AuthLoading extends AuthState {}
class Authenticated extends AuthState {
final User user;
Authenticated(this.user);
@override
List<Object?> get props => [user];
}
class Unauthenticated extends AuthState {}
class AuthError extends AuthState {
final String message;
AuthError(this.message);
@override
List<Object?> get props => [message];
}

View File

@@ -0,0 +1,11 @@
class AuthCredentials {
final String username;
final String password;
AuthCredentials({required this.username, required this.password});
Map<String, dynamic> toJson() => {
'username': username,
'password': password,
};
}

View File

@@ -0,0 +1,26 @@
import 'package:equatable/equatable.dart';
class AuthToken extends Equatable {
final String accessToken;
final String refreshToken;
final DateTime expiresAt;
const AuthToken({
required this.accessToken,
required this.refreshToken,
required this.expiresAt,
});
factory AuthToken.fromJson(Map<String, dynamic> json) {
return AuthToken(
accessToken: json['access_token'],
refreshToken: json['refresh_token'],
expiresAt: DateTime.parse(json['expires_at']),
);
}
bool get isExpired => DateTime.now().isAfter(expiresAt);
@override
List<Object> get props => [accessToken, refreshToken, expiresAt];
}

View File

@@ -0,0 +1,155 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../controllers/auth_cubit.dart';
import '../controllers/auth_state.dart';
import '../../dashboard/screens/dashboard_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
LoginScreenState createState() => LoginScreenState();
}
class LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
@override
void dispose() {
_usernameController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
context.read<AuthCubit>().login(
_usernameController.text.trim(),
_passwordController.text,
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Login')),
body: BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state is Authenticated) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const DashboardScreen()),
);
} 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,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Bank logo or app branding
const FlutterLogo(size: 80),
const SizedBox(height: 48),
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your username';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: const Icon(Icons.lock),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
),
obscureText: _obscurePassword,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
// Navigate to forgot password screen
},
child: const Text('Forgot Password?'),
),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: state is AuthLoading ? null : _submitForm,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: state is AuthLoading
? const CircularProgressIndicator()
: const Text('LOGIN', style: TextStyle(fontSize: 16)),
),
const SizedBox(height: 16),
// Registration option
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Don't have an account?"),
TextButton(
onPressed: () {
// Navigate to registration screen
},
child: const Text('Register'),
),
],
),
],
),
),
);
},
),
);
}
}

View File

@@ -0,0 +1,347 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../auth/controllers/auth_cubit.dart';
import '../../auth/controllers/auth_state.dart';
import '../widgets/account_card.dart';
import '../widgets/transaction_list_item.dart';
import '../../accounts/models/account.dart';
import '../../transactions/models/transaction.dart';
class DashboardScreen extends StatefulWidget {
const DashboardScreen({super.key});
@override
State<DashboardScreen> createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
// Mock data for demonstration
final List<Account> _accounts = [
Account(
id: '1',
accountNumber: '**** 4589',
accountType: 'Savings',
balance: 12450.75,
currency: 'USD',
),
Account(
id: '2',
accountNumber: '**** 7823',
accountType: 'Checking',
balance: 3840.50,
currency: 'USD',
),
];
final List<Transaction> _recentTransactions = [
Transaction(
id: 't1',
description: 'Coffee Shop',
amount: -4.50,
date: DateTime.now().subtract(const Duration(hours: 3)),
category: 'Food & Drink',
),
Transaction(
id: 't2',
description: 'Salary Deposit',
amount: 2500.00,
date: DateTime.now().subtract(const Duration(days: 2)),
category: 'Income',
),
Transaction(
id: 't3',
description: 'Electric Bill',
amount: -85.75,
date: DateTime.now().subtract(const Duration(days: 3)),
category: 'Utilities',
),
Transaction(
id: 't4',
description: 'Amazon Purchase',
amount: -32.50,
date: DateTime.now().subtract(const Duration(days: 5)),
category: 'Shopping',
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Dashboard'),
actions: [
IconButton(
icon: const Icon(Icons.notifications_outlined),
onPressed: () {
// Navigate to notifications
},
),
IconButton(
icon: const Icon(Icons.logout),
onPressed: () {
_showLogoutConfirmation(context);
},
),
],
),
body: RefreshIndicator(
onRefresh: () async {
// Implement refresh logic to fetch updated data
await Future.delayed(const Duration(seconds: 1));
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Greeting section
BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if (state is Authenticated) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hello, ${state.user.username}',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 4),
Text(
'Welcome back to your banking app',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey[600],
),
),
],
);
}
return Container();
},
),
const SizedBox(height: 24),
// Account cards section
const Text(
'Your Accounts',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 12),
SizedBox(
height: 180,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _accounts.length + 1, // +1 for the "Add Account" card
itemBuilder: (context, index) {
if (index < _accounts.length) {
return Padding(
padding: const EdgeInsets.only(right: 16.0),
child: AccountCard(account: _accounts[index]),
);
} else {
// "Add Account" card
return Container(
width: 300,
margin: const EdgeInsets.only(right: 16.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey[300]!),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.add_circle_outline,
size: 40,
color: Theme.of(context).primaryColor,
),
const SizedBox(height: 8),
Text(
'Add New Account',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
},
),
),
const SizedBox(height: 32),
// Quick Actions section
const Text(
'Quick Actions',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildQuickActionButton(
icon: Icons.swap_horiz,
label: 'Transfer',
onTap: () {
// Navigate to transfer screen
},
),
_buildQuickActionButton(
icon: Icons.payment,
label: 'Pay Bills',
onTap: () {
// Navigate to bill payment screen
},
),
_buildQuickActionButton(
icon: Icons.qr_code_scanner,
label: 'Scan & Pay',
onTap: () {
// Navigate to QR code scanner
},
),
_buildQuickActionButton(
icon: Icons.more_horiz,
label: 'More',
onTap: () {
// Show more options
},
),
],
),
const SizedBox(height: 32),
// Recent Transactions section
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Recent Transactions',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
TextButton(
onPressed: () {
// Navigate to all transactions
},
child: const Text('See All'),
),
],
),
const SizedBox(height: 8),
ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: _recentTransactions.length,
itemBuilder: (context, index) {
return TransactionListItem(
transaction: _recentTransactions[index],
);
},
),
],
),
),
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.dashboard),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_balance_wallet),
label: 'Accounts',
),
BottomNavigationBarItem(
icon: Icon(Icons.show_chart),
label: 'Insights',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
onTap: (index) {
// Handle navigation
},
),
);
}
Widget _buildQuickActionButton({
required IconData icon,
required String label,
required VoidCallback onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Column(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withAlpha((0.1 * 255).toInt()),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
icon,
color: Theme.of(context).primaryColor,
size: 28,
),
),
const SizedBox(height: 8),
Text(
label,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
],
),
);
}
void _showLogoutConfirmation(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Logout'),
content: const Text('Are you sure you want to logout?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('CANCEL'),
),
TextButton(
onPressed: () {
Navigator.pop(context);
context.read<AuthCubit>().logout();
},
child: const Text('LOGOUT'),
),
],
),
);
}
}

View File

@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import '../../accounts/models/account.dart';
class AccountCard extends StatelessWidget {
final Account account;
const AccountCard({
super.key,
required this.account,
});
@override
Widget build(BuildContext context) {
return Container(
width: 300,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).primaryColor.withBlue(200),
],
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withAlpha((0.1 * 255).toInt()),
spreadRadius: 1,
blurRadius: 5,
offset: const Offset(0, 3),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
account.accountType,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Icon(
account.accountType == 'Savings'
? Icons.savings
: Icons.account_balance,
color: Colors.white,
),
],
),
const SizedBox(height: 20),
Text(
account.accountNumber,
style: const TextStyle(
color: Colors.white70,
fontSize: 16,
),
),
const SizedBox(height: 30),
Text(
'${account.currency} ${account.balance.toStringAsFixed(2)}',
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 5),
const Text(
'Available Balance',
style: TextStyle(
color: Colors.white70,
fontSize: 12,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,109 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../transactions/models/transaction.dart';
class TransactionListItem extends StatelessWidget {
final Transaction transaction;
const TransactionListItem({
super.key,
required this.transaction,
});
@override
Widget build(BuildContext context) {
final bool isIncome = transaction.amount > 0;
return Card(
elevation: 0,
margin: const EdgeInsets.symmetric(vertical: 8),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: [
// Category icon
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: _getCategoryColor(transaction.category).withAlpha((0.1 * 255).toInt()),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
_getCategoryIcon(transaction.category),
color: _getCategoryColor(transaction.category),
),
),
const SizedBox(width: 12),
// Transaction details
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
transaction.description,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
Text(
DateFormat('MMM dd, yyyy • h:mm a').format(transaction.date),
style: TextStyle(
color: Colors.grey[600],
fontSize: 12,
),
),
],
),
),
// Amount
Text(
'${isIncome ? '+' : ''}${transaction.amount.toStringAsFixed(2)} USD',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: isIncome ? Colors.green : Colors.red,
),
),
],
),
),
);
}
Color _getCategoryColor(String category) {
switch (category.toLowerCase()) {
case 'food & drink':
return Colors.orange;
case 'shopping':
return Colors.purple;
case 'transportation':
return Colors.blue;
case 'utilities':
return Colors.red;
case 'income':
return Colors.green;
default:
return Colors.grey;
}
}
IconData _getCategoryIcon(String category) {
switch (category.toLowerCase()) {
case 'food & drink':
return Icons.restaurant;
case 'shopping':
return Icons.shopping_bag;
case 'transportation':
return Icons.directions_car;
case 'utilities':
return Icons.power;
case 'income':
return Icons.attach_money;
default:
return Icons.category;
}
}
}

View File

@@ -0,0 +1,15 @@
class Transaction {
final String id;
final String description;
final double amount;
final DateTime date;
final String category;
Transaction({
required this.id,
required this.description,
required this.amount,
required this.date,
required this.category,
});
}

19
lib/main.dart Normal file
View File

@@ -0,0 +1,19 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'di/injection.dart';
import 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Set preferred orientations
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// Initialize dependencies
await setupDependencies();
runApp(const KMobile());
}

View File

@@ -0,0 +1,34 @@
import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorage {
final FlutterSecureStorage _storage;
SecureStorage(): _storage = const FlutterSecureStorage();
Future<void> write(String key, dynamic value) async {
final stringValue = value is String
? value
: json.encode(value);
await _storage.write(key: key, value: stringValue);
}
Future<dynamic> read(String key) async {
final value = await _storage.read(key: key);
if (value == null) return null;
try {
return json.decode(value);
} catch (_) {
return value;
}
}
Future<void> delete(String key) async {
await _storage.delete(key: key);
}
Future<void> deleteAll() async {
await _storage.deleteAll();
}
}