Commit 13590d3f authored by Ester Alfonzo's avatar Ester Alfonzo

agrado de matriculas

parent 863e6aca
...@@ -4,9 +4,10 @@ import 'package:flutter/material.dart'; ...@@ -4,9 +4,10 @@ import 'package:flutter/material.dart';
class AppTheme { class AppTheme {
AppTheme._(); AppTheme._();
/**#660000
static const Color _lightPrimaryColor = Color(0xFFF1882D); #AA0A0A */
static const Color _lightSecondaryColor = Color(0xFF1D2B4E); static const Color _lightPrimaryColor = Color(0xFF660000);
static const Color _lightSecondaryColor = Color(0xFFAA0A0A);
static const Color _lightOnPrimaryColor = Colors.white; static const Color _lightOnPrimaryColor = Colors.white;
static const Color _lightOnSecondaryColor = Colors.white; static const Color _lightOnSecondaryColor = Colors.white;
static const Color _lightTextInputColor = Colors.white; static const Color _lightTextInputColor = Colors.white;
...@@ -14,7 +15,7 @@ class AppTheme { ...@@ -14,7 +15,7 @@ class AppTheme {
static const Color _lightHintTextColor = Color(0xFFCFCFCF); static const Color _lightHintTextColor = Color(0xFFCFCFCF);
static const Color _darkPrimaryColor = Colors.white24; static const Color _darkPrimaryColor = Colors.white24;
static const Color _darkSecondaryColor = Color(0xFFF1882D); static const Color _darkSecondaryColor = Color(0xFFAA0A0A);
static const Color _darkOnPrimaryColor = Colors.white; static const Color _darkOnPrimaryColor = Colors.white;
static const Color _darkPrimaryVariantColor = Colors.black; static const Color _darkPrimaryVariantColor = Colors.black;
static const Color _darkOnSecondaryColor = Colors.white; static const Color _darkOnSecondaryColor = Colors.white;
...@@ -68,6 +69,9 @@ class AppTheme { ...@@ -68,6 +69,9 @@ class AppTheme {
800: Color(0xFF060A29), 800: Color(0xFF060A29),
900: Color(0xFF040722), 900: Color(0xFF040722),
}; };
static Color getSecondaryColor() {
return _lightSecondaryColor;
}
static final ThemeData customLightTheme = ThemeData( static final ThemeData customLightTheme = ThemeData(
//brightness: Brightness.light, //brightness: Brightness.light,
...@@ -157,7 +161,7 @@ class AppTheme { ...@@ -157,7 +161,7 @@ class AppTheme {
fontWeight: FontWeight.bold, color: _lightHintTextColor, fontSize: 14), fontWeight: FontWeight.bold, color: _lightHintTextColor, fontSize: 14),
fillColor: _lightTextInputColor, fillColor: _lightTextInputColor,
floatingLabelStyle: const TextStyle( floatingLabelStyle: const TextStyle(
color: Color(0xFFF1882D), color: Color(0xFFAA0A0A),
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
errorStyle: TextStyle( errorStyle: TextStyle(
...@@ -167,7 +171,7 @@ class AppTheme { ...@@ -167,7 +171,7 @@ class AppTheme {
fontFamily: 'Roboto', fontFamily: 'Roboto',
), ),
labelStyle: const TextStyle( labelStyle: const TextStyle(
color: Color(0xFFF98C27), color: Color(0xFFAA0A0A),
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
......
/*import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class Authentication {
static Future<FirebaseApp> initializeFirebase(BuildContext context) async {
FirebaseApp firebaseApp = await Firebase.initializeApp();
// TODO: Add auto login logic
return firebaseApp;
}
static Future<void> signOut({required BuildContext context}) async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
Authentication.customSnackBar(
content: 'Error signing out. Try again.',
),
);
}
}
static Future<dynamic> signInWithGoogle(BuildContext context) async {
print('signInWithGoogle');
FirebaseAuth auth = FirebaseAuth.instance;
dynamic userProfile;
dynamic token;
try {
final GoogleSignIn googleSignIn = GoogleSignIn(
clientId:
'753850511112-fmc4ros60g9dljoi0ed9sh9dj4hslif6.apps.googleusercontent.com');
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
/*print('credential');
print(credential);
print('idToken');
print(googleSignInAuthentication.idToken);
print('accessToken');
print(googleSignInAuthentication.accessToken);*/
token = googleSignInAuthentication.idToken;
try {
final UserCredential userCredential =
await auth.signInWithCredential(credential);
AdditionalUserInfo? user;
user = userCredential.additionalUserInfo;
userProfile = user?.profile;
//print('user');
//print(user?.profile);
} on FirebaseAuthException catch (e) {
if (e.code == 'account-exists-with-different-credential') {
ScaffoldMessenger.of(context).showSnackBar(
Authentication.customSnackBar(
content: 'La cuenta ya existe con una credencial diferente.',
),
);
} else if (e.code == 'invalid-credential') {
ScaffoldMessenger.of(context).showSnackBar(
Authentication.customSnackBar(
content:
'Ocurrió un error al acceder a las credenciales. Intente nuevamente.',
),
);
}
return null;
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
Authentication.customSnackBar(
content:
'Se produjo un error al utilizar el inicio de sesión de Google. Intente nuevamente.',
),
);
return null;
}
return {'userProfile': userProfile, 'token': token};
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
Authentication.customSnackBar(
content:
'Se produjo un error al utilizar el inicio de sesión de Google. Intente nuevamente.',
),
);
return null;
}
return null;
}
static SnackBar customSnackBar({required String content}) {
return SnackBar(
backgroundColor: Colors.black,
content: Text(
content,
style: const TextStyle(color: Colors.redAccent, letterSpacing: 0.5),
),
);
}
}
*/
\ No newline at end of file
...@@ -4,7 +4,7 @@ import 'package:cookie_jar/cookie_jar.dart'; ...@@ -4,7 +4,7 @@ import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart'; import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'ConectionApi.dart'; import 'ConectionApi.dart';
class Api { class RemoteClient {
String apiUrl = "https://tramites.una.py/etramite-backend/"; String apiUrl = "https://tramites.una.py/etramite-backend/";
ConectionApi conection = ConectionApi(); ConectionApi conection = ConectionApi();
......
import 'package:dropdown_search/dropdown_search.dart'; /*import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart';
...@@ -98,7 +98,7 @@ BoxConstraints dropdownButtonTamanho(context) { ...@@ -98,7 +98,7 @@ BoxConstraints dropdownButtonTamanho(context) {
minHeight: MediaQuery.of(context).size.height * 0.5, minHeight: MediaQuery.of(context).size.height * 0.5,
minWidth: MediaQuery.of(context).size.width * 0.98, minWidth: MediaQuery.of(context).size.width * 0.98,
); );
} }*/
/** /**
* keytool -keystore /home/ealfonzo/.android/debug.keystore -list -v -alias androiddebugkey -storepass android -keypass android * keytool -keystore /home/ealfonzo/.android/debug.keystore -list -v -alias androiddebugkey -storepass android -keypass android
*/ */
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../presentation/screens/home/sc_homeScreen.dart';
import '../presentation/screens/login/sc_loginScreen.dart';
import '../presentation/screens/splash/sc_splash.dart';
class AppRouter { class AppRouter {
static const String HOME = '/'; static const String HOME = '/';
......
import 'package:ealu_flutter/core/api.dart'; import '../../core/RemoteClient.dart';
import 'package:ealu_flutter/data/models/LoginModel.dart'; import '../../core/responsesError.dart';
import '../models/LoginModel.dart';
import '../../core/apiResponses.dart'; class DataSourceLogin {
class RemoteLogin {
Api api;
RemoteLogin(this.api);
Future<LoginModel?> remoteloginUser(dynamic params, dynamic body) async { Future<LoginModel?> remoteloginUser(dynamic params, dynamic body) async {
var response = await api.post('', params, body); RemoteClient api = RemoteClient();
var response = await api.post('login', params, body);
if (response != null) {
if (response.statusCode == 200) {
return LoginModel.fromJson(response.data);
} else {
if (response.statusCode == 401) {
throw UnauthorizedException();
} else if (response.statusCode == 404) {
throw NotFoundException(message: "xxxx");
} else {
throw ServerException();
}
}
}
return null;
}
Future<LoginModel?> remoteSessionInfo(dynamic params) async {
RemoteClient api = RemoteClient();
var response = await api.get('sesion-ealu/info', params);
if (response != null) { if (response != null) {
if (response.statusCode == 200) { if (response.statusCode == 200) {
return LoginModel.fromJson(response.data); return LoginModel.fromJson(response.data);
......
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
import 'package:ealu_flutter/domain/entities/alumno.dart';
class AlumnoModel extends Alumno {
String cedula;
String nombre;
String apellido;
String sexo;
String estcivil;
String telefono;
String direccion;
String mail;
dynamic lateralidad;
dynamic pueblosOriginarios;
dynamic pueblosoriginariostext;
dynamic discapacidad;
dynamic discVisual;
dynamic discMotora;
dynamic discAuditiva;
dynamic discOtros;
dynamic discOtrosText;
String str;
AlumnoModel({
required this.cedula,
required this.nombre,
required this.apellido,
required this.sexo,
required this.estcivil,
required this.telefono,
required this.direccion,
required this.mail,
this.lateralidad,
this.pueblosOriginarios,
this.pueblosoriginariostext,
this.discapacidad,
this.discVisual,
this.discMotora,
this.discAuditiva,
this.discOtros,
this.discOtrosText,
required this.str,
});
factory AlumnoModel.fromJson(Map<String, dynamic> json) => AlumnoModel(
cedula: json["cedula"],
nombre: json["nombre"],
apellido: json["apellido"],
sexo: json["sexo"],
estcivil: json["estcivil"],
telefono: json["telefono"],
direccion: json["direccion"],
mail: json["mail"],
lateralidad: json["lateralidad"],
pueblosOriginarios: json["pueblosOriginarios"],
pueblosoriginariostext: json["pueblosoriginariostext"],
discapacidad: json["discapacidad"],
discVisual: json["disc_visual"],
discMotora: json["disc_motora"],
discAuditiva: json["disc_auditiva"],
discOtros: json["disc_otros"],
discOtrosText: json["disc_otros_text"],
str: json["str"],
);
Map<String, dynamic> toJson() => {
"cedula": cedula,
"nombre": nombre,
"apellido": apellido,
"sexo": sexo,
"estcivil": estcivil,
"telefono": telefono,
"direccion": direccion,
"mail": mail,
"lateralidad": lateralidad,
"pueblosOriginarios": pueblosOriginarios,
"pueblosoriginariostext": pueblosoriginariostext,
"discapacidad": discapacidad,
"disc_visual": discVisual,
"disc_motora": discMotora,
"disc_auditiva": discAuditiva,
"disc_otros": discOtros,
"disc_otros_text": discOtrosText,
"str": str,
};
}
import 'package:ealu_flutter/domain/entities/matricula.dart';
class MatriculaModel extends Matricula {
dynamic codfacul;
String codcarsec;
String carrera;
String codcarre;
dynamic cedula;
int anhoingreso;
dynamic anhoegreso;
bool verenealu;
String tipomatric;
String tiTipomatric;
dynamic cantInscripciones;
String arancelcero;
int arancelceroAnhohasta;
int arancelceroSemhasta;
MatriculaModel({
this.codfacul,
required this.codcarsec,
required this.carrera,
required this.codcarre,
this.cedula,
required this.anhoingreso,
this.anhoegreso,
required this.verenealu,
required this.tipomatric,
required this.tiTipomatric,
this.cantInscripciones,
required this.arancelcero,
required this.arancelceroAnhohasta,
required this.arancelceroSemhasta,
}):super;
factory MatriculaModel.fromJson(Map<String, dynamic> json) => MatriculaModel(
codfacul: json["codfacul"],
codcarsec: json["codcarsec"],
carrera: json["carrera"],
codcarre: json["codcarre"],
cedula: json["cedula"],
anhoingreso: json["anhoingreso"],
anhoegreso: json["anhoegreso"],
verenealu: json["verenealu"],
tipomatric: json["tipomatric"],
tiTipomatric: json["ti_tipomatric"],
cantInscripciones: json["cantInscripciones"],
arancelcero: json["arancelcero"],
arancelceroAnhohasta: json["arancelcero_anhohasta"],
arancelceroSemhasta: json["arancelcero_semhasta"],
);
Map<String, dynamic> toJson() => {
"codfacul": codfacul,
"codcarsec": codcarsec,
"carrera": carrera,
"codcarre": codcarre,
"cedula": cedula,
"anhoingreso": anhoingreso,
"anhoegreso": anhoegreso,
"verenealu": verenealu,
"tipomatric": tipomatric,
"ti_tipomatric": tiTipomatric,
"cantInscripciones": cantInscripciones,
"arancelcero": arancelcero,
"arancelcero_anhohasta": arancelceroAnhohasta,
"arancelcero_semhasta": arancelceroSemhasta,
};
}
import '../../domain/entities/matricula.dart';
import '../../domain/entities/sesionInfo.dart';
import 'AlumnoModel.dart';
import 'MatriculaModel.dart';
SessionInfoModel sessionInfoModelFromJson(String str) =>
SessionInfoModel.fromJson(json.decode(str));
String sessionInfModelToJson(SessionInfoModel data) =>
json.encode(data.toJson());
class SessionInfoModel extends SessionInfo {
List<Matricula> matriculaListModel;
AlumnoModel alumnoModel;
SessionInfoModel({
required this.matriculaListModel,
required this.alumnoModel,
}) : super(alumno: alumnoModel, matriculaList: matriculaListModel);
factory SessionInfoModel.fromJson(Map<String, dynamic> json) =>
SessionInfoModel(
matriculaListModel: List<Matricula>.from(
json["matriculaList"].map((x) => MatriculaModel.fromJson(x))),
alumnoModel: AlumnoModel.fromJson(json["alumno"]),
);
Map<String, dynamic> toJson() => {
"matriculaListModel":
List<dynamic>.from(matriculaList.map((x) => x.toJson())),
"alumno": alumno.toJson(),
};
}
import '../../core/apiResponses.dart'; import 'package:ealu_flutter/presentation/blocs/login/login_bloc.dart';
import '../../core/responsesError.dart';
import '../../domain/entities/user.dart'; import '../../domain/entities/user.dart';
import '../../services/toastService.dart'; import '../../domain/repositories/auth_repository.dart';
import '../datasources/login_remote.dart'; import '../../presentation/widgets/toast.dart';
import '../datasources/login_data_source.dart';
class AuthRepository { class AuthRepositoryImpl implements AuthRepository {
final RemoteLogin remoteLogin; final DataSourceLogin remote;
//final LocalDataSource localDataSource;
AuthRepository({ AuthRepositoryImpl(this.remote);
required this.remoteLogin,
//required this.localDataSource,
});
@override @override
Future<User?> login(String email, String password) async { Future<User?> login(String email, String password) async {
try { try {
final loginModel = await remoteLogin.remoteloginUser(email, password); final loginModel = await remote.remoteloginUser(email, password);
final user = User.fromModel(loginModel!.userModel);
//await localDataSource.cacheAuth(Auth);
return user;
} on UnauthorizedException {
showToastError("No autorizado");
return null;
} on ServerException {
showToastError("Error de servidor");
return null;
} on Exception {
showToastError("Error desconocido'");
return null;
}
}
@override
Future<User?> sessionInfo() async {
try {
final loginModel = await remote.remoteSessionInfo(email, password);
final user = User.fromModel(loginModel!.userModel); final user = User.fromModel(loginModel!.userModel);
//await localDataSource.cacheAuth(Auth); //await localDataSource.cacheAuth(Auth);
return user; return user;
...@@ -29,6 +47,5 @@ class AuthRepository { ...@@ -29,6 +47,5 @@ class AuthRepository {
showToastError("Error desconocido'"); showToastError("Error desconocido'");
return null; return null;
} }
return null;
} }
} }
class Alumno {
String cedula;
String nombre;
String apellido;
String sexo;
String estcivil;
String telefono;
String direccion;
String mail;
dynamic lateralidad;
dynamic pueblosOriginarios;
dynamic pueblosoriginariostext;
dynamic discapacidad;
dynamic discVisual;
dynamic discMotora;
dynamic discAuditiva;
dynamic discOtros;
dynamic discOtrosText;
String str;
Alumno({
required this.cedula,
required this.nombre,
required this.apellido,
required this.sexo,
required this.estcivil,
required this.telefono,
required this.direccion,
required this.mail,
this.lateralidad,
this.pueblosOriginarios,
this.pueblosoriginariostext,
this.discapacidad,
this.discVisual,
this.discMotora,
this.discAuditiva,
this.discOtros,
this.discOtrosText,
required this.str,
});
}
import 'package:equatable/equatable.dart';
class Matricula extends Equatable {
dynamic codfacul;
String codcarsec;
String carrera;
String codcarre;
dynamic cedula;
int anhoingreso;
dynamic anhoegreso;
bool verenealu;
String tipomatric;
String tiTipomatric;
dynamic cantInscripciones;
String arancelcero;
int arancelceroAnhohasta;
int arancelceroSemhasta;
Matricula({
this.codfacul,
required this.codcarsec,
required this.carrera,
required this.codcarre,
this.cedula,
required this.anhoingreso,
this.anhoegreso,
required this.verenealu,
required this.tipomatric,
required this.tiTipomatric,
this.cantInscripciones,
required this.arancelcero,
required this.arancelceroAnhohasta,
required this.arancelceroSemhasta,
});
@override
// TODO: implement props
List<Object?> get props => throw UnimplementedError();
}
import 'package:equatable/equatable.dart';
import 'alumno.dart';
import 'matricula.dart';
class SessionInfo extends Equatable {
List<Matricula> matriculaList;
Alumno alumno;
SessionInfo({
required this.matriculaList,
required this.alumno,
});
@override
List<Object?> get props => throw UnimplementedError();
}
import '../entities/user.dart';
abstract class AuthRepository {
Future<User?> login(String email, String password);
}
import '../../data/repositories/auth_repository.dart'; import '../../data/repositories/auth_repository.dart';
import '../entities/user.dart'; import '../entities/user.dart';
import '../repositories/auth_repository.dart';
class LoginUseCase { class LoginUseCase {
final AuthRepository authRepository; final AuthRepository authRepository;
LoginUseCase(this.authRepository); LoginUseCase({required this.authRepository});
Future<User?> login(String username, String password) { Future<User?> login(String username, String password) {
return authRepository.login(username, password); return authRepository.login(username, password);
...@@ -12,7 +13,7 @@ class LoginUseCase { ...@@ -12,7 +13,7 @@ class LoginUseCase {
} }
class LogoutUseCase { class LogoutUseCase {
final AuthRepository repository; final AuthRepositoryImpl repository;
LogoutUseCase(this.repository); LogoutUseCase(this.repository);
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sizer/sizer.dart'; import 'package:sizer/sizer.dart';
import 'core/AppTheme.dart';
import 'core/router.dart'; import 'core/router.dart';
import 'data/datasources/login_data_source.dart';
import 'data/repositories/auth_repository.dart';
import 'domain/repositories/auth_repository.dart';
import 'domain/usecases/authentication_case_use.dart';
import 'presentation/blocs/authentication/authentication_bloc.dart';
import 'presentation/blocs/authentication/authentication_event.dart';
import 'presentation/blocs/authentication/authentication_state.dart';
import 'presentation/blocs/login/login_bloc.dart';
import 'presentation/screens/home/sc_homeScreen.dart';
import 'presentation/screens/login/sc_loginScreen.dart';
import 'presentation/screens/splash/sc_splash.dart';
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
@override @override
...@@ -18,15 +29,7 @@ class MyApp extends StatelessWidget { ...@@ -18,15 +29,7 @@ class MyApp extends StatelessWidget {
supportedLocales: [ supportedLocales: [
Locale('es'), // Spanish Locale('es'), // Spanish
], ],
theme: ThemeData( theme: AppTheme.customLightTheme,
brightness: Brightness.light,
scaffoldBackgroundColor: Colors.grey.shade900,
primaryColor: COLOR_CONST.PRIMARY,
hoverColor: COLOR_CONST.GRAY2,
fontFamily: 'Oswald',
colorScheme: ColorScheme.fromSwatch()
.copyWith(secondary: COLOR_CONST.PRIMARY),
),
onGenerateRoute: AppRouter.generateRoute, onGenerateRoute: AppRouter.generateRoute,
home: BlocBuilder<AuthenticationBloc, AuthenticationState>( home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
builder: (context, state) { builder: (context, state) {
...@@ -53,21 +56,16 @@ class MyApp extends StatelessWidget { ...@@ -53,21 +56,16 @@ class MyApp extends StatelessWidget {
future: Future.sync(() => true), future: Future.sync(() => true),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.hasData) { if (snapshot.hasData) {
final UserRepository userRepository = UserRepository();
/*final TimerRepository timerRepository = TimerRepository();
final HomeRepository homeRepository = HomeRepository();
final ShowRepository showRepository = ShowRepository();
final ProductsRepository productsRepository = ProductsRepository();
final BookTimeSlotRepository bookTimeSlotRepository =
BookTimeSlotRepository();
final SessionRepository sessionRepository =
SessionRepository(pref: LocalPref());
final SeatSlotRepository seatSlotRepository = SeatSlotRepository();*/
return MultiRepositoryProvider( return MultiRepositoryProvider(
providers: [ providers: [
RepositoryProvider<UserRepository>( RepositoryProvider<DataSourceLogin>(
create: (context) => userRepository), create: (context) => DataSourceLogin(),
),
RepositoryProvider<AuthRepository>(
create: (context) => AuthRepositoryImpl(
context.read<DataSourceLogin>(),
),
),
/*RepositoryProvider<TimerRepository>( /*RepositoryProvider<TimerRepository>(
create: (context) => timerRepository), create: (context) => timerRepository),
RepositoryProvider<ProductsRepository>( RepositoryProvider<ProductsRepository>(
...@@ -86,26 +84,26 @@ class MyApp extends StatelessWidget { ...@@ -86,26 +84,26 @@ class MyApp extends StatelessWidget {
child: MultiBlocProvider( child: MultiBlocProvider(
providers: [ providers: [
BlocProvider( BlocProvider(
create: (context) => create: (context) => AuthenticationBloc()..add(AppStarted()),
AuthenticationBloc(userRepository: userRepository)
..add(AppStarted()),
), ),
BlocProvider( /*BlocProvider(
create: (context) => HomeBloc( create: (context) => HomeBloc(
homeRepository: homeRepository, homeRepository: homeRepository,
userRepository: userRepository, userRepository: userRepository,
), ),
), ),*/
BlocProvider( BlocProvider(
create: (context) => create: (context) => LoginBloc(
LoginBloc(userRepository: userRepository), authUseCase: LoginUseCase(
authRepository: context.read<AuthRepository>(),
),
),
) )
], ],
child: MyApp(), child: MyApp(),
), ),
); );
} }
return Container(); return Container();
}, },
); );
......
import 'package:bloc/bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'authentication_event.dart';
import 'authentication_state.dart';
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
AuthenticationBloc() : super(Uninitialized()) {
on<AppStarted>((event, emit) async {
//verificar si ya inicio sesion
try {
final prefs = await SharedPreferences.getInstance();
final String? institucion = prefs.getString("institucion");
final String? email = prefs.getString("email");
final String? password = prefs.getString("password");
emit(Unauthenticated());
} catch (e) {
print(e);
emit(Unauthenticated());
}
});
on<LoggedIn>((event, emit) async {
emit(Authenticated(""));
});
on<LoggedOut>((event, emit) async {
emit(Unauthenticated());
});
}
}
import 'package:equatable/equatable.dart';
abstract class AuthenticationEvent extends Equatable {
@override
List<Object> get props => [];
}
class AppStarted extends AuthenticationEvent {}
class LoggedIn extends AuthenticationEvent {}
class LoggedOut extends AuthenticationEvent {}
import 'package:equatable/equatable.dart';
abstract class AuthenticationState extends Equatable {
const AuthenticationState();
@override
List<Object> get props => [];
}
class Uninitialized extends AuthenticationState {}
class Authenticated extends AuthenticationState {
final String displayName;
const Authenticated(this.displayName);
@override
List<Object> get props => [];
@override
String toString() {
return 'Authenticated{displayName: $displayName}';
}
}
class Unauthenticated extends AuthenticationState {}
import 'dart:io'; import 'dart:io';
import 'package:bloc/bloc.dart'; import 'package:bloc/bloc.dart';
import 'package:ealu_flutter/data/datasources/login_remote.dart'; import 'package:ealu_flutter/data/datasources/login_data_source.dart';
import 'package:ealu_flutter/domain/usecases/authentication_case_use.dart'; import 'package:ealu_flutter/domain/usecases/authentication_case_use.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
...@@ -9,16 +8,16 @@ part 'login_event.dart'; ...@@ -9,16 +8,16 @@ part 'login_event.dart';
part 'login_state.dart'; part 'login_state.dart';
class LoginBloc extends Bloc<LoginEvent, LoginState> { class LoginBloc extends Bloc<LoginEvent, LoginState> {
LoginBloc() : super(LoginInitial()) { final LoginUseCase authUseCase;
LoginBloc({required this.authUseCase}) : super(LoginInitial()) {
on<LogInRemote>((event, emit) async { on<LogInRemote>((event, emit) async {
LoginUseCase authUseCase;
emit(LoginLoading()); emit(LoginLoading());
try { try {
var log = await authUseCase.login(event.email, event.password); var log = await authUseCase.login(event.email, event.password);
if (log == null) { if (log == null) {
emit(LoginError("")); emit(LoginError(""));
} else { } else {
emit(LoginLoaded()); emit(LoginSuccess());
} }
} catch (e) { } catch (e) {
emit(LoginError("")); emit(LoginError(""));
......
...@@ -11,7 +11,7 @@ class LoginInitial extends LoginState {} ...@@ -11,7 +11,7 @@ class LoginInitial extends LoginState {}
class LoginLoading extends LoginState {} class LoginLoading extends LoginState {}
class LoginLoaded extends LoginState {} class LoginSuccess extends LoginState {}
class LoginError extends LoginState { class LoginError extends LoginState {
final String error; final String error;
......
import 'package:flutter/material.dart';
class MatriculaSelect extends StatefulWidget {
final Function handleHomeRefresh;
final GlobalKey<NavigatorState> navigatorKey;
MatriculaSelect({required this.handleHomeRefresh, required this.navigatorKey});
@override
_MatriculaSelectState createState() => _MatriculaSelectState();
}
class _MatriculaSelectState extends State<MatriculaSelect> {
late Store<AppState> _store;
late String _currentMatriculaCodcarsec;
late int _currentMatriculaIndex;
late bool _visible;
late final _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
_visible = false;
}
@override
Widget build(BuildContext context) {
_store = StoreProvider.of<AppState>(context);
final sessionInfo = _store.state.auth.sessionInfo;
final currentMatricula = _store.state.auth.currentMatricula;
final isFetching = _store.state.auth.isFetching;
if (currentMatricula != null) {
_currentMatriculaCodcarsec = currentMatricula.codcarsec.trim() + ' - ' + currentMatricula.carrera.trim();
_currentMatriculaIndex = sessionInfo.matriculaList.indexWhere((matricula) => matricula.codcarsec == currentMatricula.codcarsec);
}
return !_visible && currentMatricula != null
? _buildCurrentMatricula()
: sessionInfo == null || isFetching
? SizedBox.shrink()
: _buildOverflowMenu(sessionInfo);
}
Widget _buildCurrentMatricula() {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(25.0),
),
child: InkWell(
onTap: () => setState(() => _visible = true),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.all(10.0),
child: Text(
_currentMatriculaCodcarsec,
style: TextStyle(color: Colors.white),
),
),
Padding(
padding: EdgeInsets.only(right: 10.0),
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 24,
),
),
],
),
),
);
}
Widget _buildOverflowMenu(sessionInfo) {
return PopupMenuButton<String>(
itemBuilder: (BuildContext context) {
return sessionInfo.matriculaList.map((dynamic matricula) {
return PopupMenuItem<String>(
value: matricula,
child: Text(matricula[""]),
onTap: setCurrentMatricula(sessionInfo.matriculaList[index]),
);
}).toList();
},
);}
\ No newline at end of file
import 'package:ealu_flutter/presentation/widgets/customAppBar.dart';
import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(12.h),
child: CustomAppBar(
onLogoutButtonPress: () {},
),
),
body: SafeArea(
child: Column(children: <Widget>[
Padding(
padding: const EdgeInsets.all(5),
child: MatriculaSelect(),
),
Expanded(
child: SingleChildScrollView(
child: Column(children: <Widget>[
Container(),
/*Padding(
padding: EdgeInsets.all(10),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'HOME',
style: TextStyle(
fontSize: getResponsiveIcon() + 10,
color: Color(0xFF3F3F3F),
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
Container(
width: 35,
child: FlatButton(
onPressed: () {
StoreProvider.of<AppState>(context).dispatch(
LogoutUserAction(),
);
},
padding: EdgeInsets.all(0),
child: Icon(
Ionicons.md_exit,
size: getResponsiveIcon(),
color: Color(0xFF3F3F3F),
),
),
),
],
),
),
Padding(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Novedades',
style: TextStyle(
fontSize: getResponsiveText() + 5,
fontWeight: FontWeight.bold,
color: Color(0xFF3F3F3F),
),
),
SizedBox(
height: 10,
),
StoreConnector<AppState, List<dynamic>>(
converter: (Store<AppState> store) =>
store.state.home.mensajeList,
builder: (BuildContext context,
List<dynamic> mensajeList) {
return ListView.builder(
itemCount: mensajeList.length > 3
? 3
: mensajeList.length,
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
final item = mensajeList[index];
return Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: () async {
if (await canLaunch(item.url)) {
await launch(item.url);
} else {
throw 'Could not launch ${item.url}';
}
},
child: Linkify(
onOpen: (link) async {
if (await canLaunch(link.url)) {
await launch
*/
]),
),
)
]),
),
);
}
}
import 'dart:convert';
import 'package:etramite_flutter/clases/GoogleAuth.dart';
import 'package:etramite_flutter/clases/SharedPref.dart';
import 'package:etramite_flutter/screens/HomeScreen.dart';
import 'package:etramite_flutter/screens/SingUpScreen.dart';
import 'package:etramite_flutter/services/toastService.dart';
import 'package:etramite_flutter/widgets/OptionsGradient.dart';
import 'package:etramite_flutter/widgets/RecuperarPassword.dart';
import 'package:etramite_flutter/widgets/ButtonLoginWithGoogle.dart';
import 'package:flutter/material.dart';
import 'package:etramite_flutter/services/authService.dart' as apiResponse;
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/SharedPref.dart';
import '../../blocs/login/login_bloc.dart';
import '../services/loadingService.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _isObscure = true;
dynamic user;
@override
void initState() {
super.initState();
getDataUser();
}
_handleLoginDB(BuildContext context, usuario, pass) async {
var body = {'username': usuario, 'password': pass};
await showPresent('');
var _apiResponse = await apiResponse.getLoginDB(context, usuario, pass);
/*print('apiiii');
print(_apiResponse);*/
if (_apiResponse == null) {
await dismissPresent();
} else {
await sharedPrefs.save('user', usuario);
await sharedPrefs.save('passw', pass);
await sharedPrefs.save('login', 'yes');
//await sharedPrefs.save('usuario', jsonEncode(_apiResponse['user']));
await sharedPrefs.save('usuario', _apiResponse['user']['nameAndSurname']);
await dismissPresent();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => const HomeScreen(),
),
ModalRoute.withName('/home'),
);
}
}
getDataUser() {
if (sharedPrefs.containsKey('user') == true &&
sharedPrefs.containsKey('passw') == true) {
setState(() {
_nameController.text = sharedPrefs.read('user');
_passwordController.text = sharedPrefs.read('passw');
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: BlocProvider<LoginBloc>(
create: (context) => LoginBloc(),
child: ListView(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 30, bottom: 30),
child: ClipRRect(
child: Image.asset(
'assets/e-tramite-logo.png',
width: MediaQuery.of(context).size.width / 2.5,
),
),
),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.95,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(5)),
color: Theme.of(context).cardColor,
),
child: Container(
padding: const EdgeInsets.only(
top: 20, bottom: 5, left: 10, right: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text(
'Inicia sesión o regístrate para continuar',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
TextField(
controller: _nameController,
decoration: const InputDecoration(
//labelText: 'Usuario',
hintText: 'Usuario',
isDense: true,
prefixIcon: Icon(
Icons.person,
size: 22,
),
),
),
const SizedBox(
height: 20,
),
TextField(
obscureText: _isObscure,
controller: _passwordController,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.lock_sharp,
size: 22,
),
isDense: true,
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
size: 22,
),
onPressed: () => setState(
() {
_isObscure = !_isObscure;
},
),
),
hintText: 'Contraseña',
),
),
const SizedBox(
height: 20,
),
TextButton(
child: const Text(
'¿Olvidaste tu contraseña?',
),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return buildDialogPage(context);
},
);
},
),
ElevatedButton(
child: const Text(
'INICIAR SESIÓN',
),
onPressed: () {
print(_nameController.text);
print(_passwordController.text);
if (_nameController.text != '' &&
_passwordController.text != '') {
_handleLoginDB(context, _nameController.text,
_passwordController.text);
} else {
showToastError('Complete todos los campos');
}
},
),
const SizedBox(
height: 15,
),
optionsGradient(context, 'O', 0.40),
const SizedBox(
height: 15,
),
FutureBuilder(
future: Authentication.initializeFirebase(context),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Error de Inicialización');
} else if (snapshot.connectionState ==
ConnectionState.done) {
return GoogleSignInButton(
onGoogleButtomPressed: handleLoginGoogle,
contentText: 'Continúa con Google',
);
}
return CircularProgressIndicator(
strokeWidth: 2,
backgroundColor: Colors.white,
valueColor: AlwaysStoppedAnimation<Color>(
(Theme.of(context).primaryColor),
),
);
},
),
Row(
children: <Widget>[
const Text(
'¿No tienes ninguna cuenta?',
),
TextButton(
child: const Text(
'Regístrate',
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SingUpScreen(),
),
);
},
)
],
mainAxisAlignment: MainAxisAlignment.center,
),
],
),
),
),
),
const SizedBox(
height: 12,
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import '../../widgets/toast.dart';
import 'package:etramite_flutter/services/authService.dart' as apiResponse;
import 'package:etramite_flutter/services/toastService.dart' as toast;
Widget buildDialogPage(BuildContext context) { Widget buildDialogPage(BuildContext context) {
TextEditingController _emailController = TextEditingController(); TextEditingController _emailController = TextEditingController();
_handleRecuperarPass(BuildContext context, email) async { _handleRecuperarPass(BuildContext context, email) async {
var _apiResponse = await apiResponse.recuperarPass(context, email); var _apiResponse = {};
print(_apiResponse); print(_apiResponse);
if (_apiResponse == null) { if (_apiResponse == null) {
toast.showToastError("Ha ocurrido algun problema"); showToastError("Ha ocurrido algun problema");
} else { } else {
if (_apiResponse['success'] == false) { if (_apiResponse['success'] == false) {
toast.showToastError(_apiResponse["errorMessage"]); showToastError(_apiResponse["errorMessage"]);
} else { } else {
toast.showToastError(_apiResponse["successMessage"]); showToastError(_apiResponse["successMessage"]);
} }
} }
} }
...@@ -62,7 +60,7 @@ Widget buildDialogPage(BuildContext context) { ...@@ -62,7 +60,7 @@ Widget buildDialogPage(BuildContext context) {
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Email', labelText: 'Email',
prefixIcon: Icon( prefixIcon: Icon(
FontAwesomeIcons.solidEnvelope, Icons.access_time_outlined,
), ),
), ),
), ),
......
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/SharedPref.dart';
import '../../../domain/repositories/auth_repository.dart';
import '../../../domain/usecases/authentication_case_use.dart';
import '../../blocs/login/login_bloc.dart';
import '../../widgets/toast.dart';
import 'recuperarPassword.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _isObscure = true;
dynamic user;
late LoginBloc _loginBloc;
@override
void initState() {
super.initState();
_loginBloc = LoginBloc(
authUseCase: LoginUseCase(
authRepository: context.read<AuthRepository>(),
),
);
getDataUser();
}
/*_handleLoginDB(BuildContext context, usuario, pass) async {
var body = {'username': usuario, 'password': pass};
await showPresent('');
var _apiResponse = await apiResponse.getLoginDB(context, usuario, pass);
/*print('apiiii');
print(_apiResponse);*/
if (_apiResponse == null) {
await dismissPresent();
} else {
await sharedPrefs.save('user', usuario);
await sharedPrefs.save('passw', pass);
await sharedPrefs.save('login', 'yes');
//await sharedPrefs.save('usuario', jsonEncode(_apiResponse['user']));
await sharedPrefs.save('usuario', _apiResponse['user']['nameAndSurname']);
await dismissPresent();
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) => const HomeScreen(),
),
ModalRoute.withName('/home'),
);
}
}*/
getDataUser() {
if (sharedPrefs.containsKey('user') == true &&
sharedPrefs.containsKey('passw') == true) {
setState(() {
_nameController.text = sharedPrefs.read('user');
_passwordController.text = sharedPrefs.read('passw');
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: ListView(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 30, bottom: 30),
child: ClipRRect(
child: Image.asset(
'assets/e-tramite-logo.png',
width: MediaQuery.of(context).size.width / 2.5,
),
),
),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.95,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(5)),
color: Theme.of(context).cardColor,
),
child: Container(
padding: const EdgeInsets.only(
top: 20, bottom: 5, left: 10, right: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text(
'Inicia sesión',
style: TextStyle(fontSize: 14),
),
const SizedBox(
height: 20,
),
TextField(
controller: _nameController,
decoration: const InputDecoration(
//labelText: 'Usuario',
hintText: 'Usuario',
isDense: true,
prefixIcon: Icon(
Icons.person,
size: 22,
),
),
),
const SizedBox(
height: 20,
),
TextField(
obscureText: _isObscure,
controller: _passwordController,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.lock_sharp,
size: 22,
),
isDense: true,
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
size: 22,
),
onPressed: () => setState(
() {
_isObscure = !_isObscure;
},
),
),
hintText: 'Contraseña',
),
),
const SizedBox(
height: 20,
),
TextButton(
child: const Text(
'¿Olvidaste tu contraseña?',
),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return buildDialogPage(context);
},
);
},
),
ElevatedButton(
child: const Text(
'INICIAR SESIÓN',
),
onPressed: () {
print(_nameController.text);
print(_passwordController.text);
if (_nameController.text != '' &&
_passwordController.text != '') {
/*_handleLoginDB(context, _nameController.text,
_passwordController.text);*/
} else {
showToastError('Complete todos los campos');
}
},
),
const SizedBox(
height: 15,
),
],
),
),
),
),
const SizedBox(
height: 12,
)
],
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';
import '../../../core/router.dart';
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Theme.of(context).colorScheme.primary,
child: SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
Image.asset(
'assets/E_Alu_Icon.png',
fit: BoxFit.cover,
width: 40.w,
),
/*Container(
child: Text(
"COPYRIGHT © " + DateTime.now().year.toString(),
//style: FONT_CONST.BOLD_PRIMARY_INFORMATION_TITLE,
),
)*/
],
),
),
),
);
}
void openLogin() {
Future.delayed(Duration(seconds: 3), () {
Navigator.pushNamed(context, AppRouter.LOGIN);
});
}
}
import 'package:etramite_flutter/clases/GoogleAuth.dart';
import 'package:flutter/material.dart';
class GoogleSignInButton extends StatefulWidget {
final Function(dynamic token) onGoogleButtomPressed;
final String contentText;
const GoogleSignInButton(
{Key? key,
required this.onGoogleButtomPressed,
required this.contentText})
: super(key: key);
@override
_GoogleSignInButtonState createState() => _GoogleSignInButtonState();
}
class _GoogleSignInButtonState extends State<GoogleSignInButton> {
bool _isSigningIn = false;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
if (_isSigningIn == false) ...[
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.white),
onPressed: () async {
setState(() {
_isSigningIn = true;
});
var usr = await Authentication.signInWithGoogle(context);
if (usr != null) widget.onGoogleButtomPressed(usr);
setState(() {
_isSigningIn = false;
});
},
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Image.asset(
'assets/google_icon.png',
height: 25,
width: 25,
),
const SizedBox(
width: 15,
),
Text(
widget.contentText,
style: const TextStyle(fontSize: 16, color: Colors.black),
),
],
),
),
] else ...[
CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor,
),
),
],
],
);
}
}
import 'package:flutter/material.dart';
class CustomAnimatedBottomBar extends StatelessWidget {
CustomAnimatedBottomBar({
Key? key,
this.selectedIndex = 0,
this.showElevation = true,
this.iconSize = 22,
this.backgroundColor,
this.itemCornerRadius = 50,
this.containerHeight = 56,
this.animationDuration = const Duration(milliseconds: 270),
this.mainAxisAlignment = MainAxisAlignment.spaceAround,
required this.items,
required this.onItemSelected,
this.curve = Curves.linear,
}) : assert(items.length >= 2 && items.length <= 5),
super(key: key);
final int selectedIndex;
final double iconSize;
final Color? backgroundColor;
final bool showElevation;
final Duration animationDuration;
final List<BottomNavyBarItem> items;
final ValueChanged<int> onItemSelected;
final MainAxisAlignment mainAxisAlignment;
final double itemCornerRadius;
final double containerHeight;
final Curve curve;
@override
Widget build(BuildContext context) {
final bgColor = backgroundColor ?? Theme.of(context).bottomAppBarColor;
return Container(
decoration: BoxDecoration(
color: bgColor,
boxShadow: [
if (showElevation)
const BoxShadow(
color: Colors.black12,
blurRadius: 2,
),
],
),
child: SafeArea(
child: Container(
width: double.infinity,
height: containerHeight,
//alignment: Alignment.center,
//padding: const EdgeInsets.all(4),
child: Row(
mainAxisAlignment: mainAxisAlignment,
crossAxisAlignment: CrossAxisAlignment.center,
children: items.map((item) {
var index = items.indexOf(item);
return GestureDetector(
onTap: () => onItemSelected(index),
child: _ItemWidget(
item: item,
iconSize: iconSize,
isSelected: index == selectedIndex,
backgroundColor: bgColor,
itemCornerRadius: itemCornerRadius,
animationDuration: animationDuration,
curve: curve,
),
);
}).toList(),
),
),
),
);
}
}
class _ItemWidget extends StatelessWidget {
final double iconSize;
final bool isSelected;
final BottomNavyBarItem item;
final Color backgroundColor;
final double itemCornerRadius;
final Duration animationDuration;
final Curve curve;
const _ItemWidget({
Key? key,
required this.item,
required this.isSelected,
required this.backgroundColor,
required this.animationDuration,
required this.itemCornerRadius,
required this.iconSize,
this.curve = Curves.linear,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
selected: isSelected,
child: AnimatedContainer(
width: isSelected
? MediaQuery.of(context).size.width / 3
: MediaQuery.of(context).size.width / 4,
height: double.maxFinite,
duration: animationDuration,
//curve: curve,
//alignment: Alignment.center,
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.primary
: backgroundColor,
// borderRadius: BorderRadius.circular(itemCornerRadius),
),
child: Container(
width: isSelected
? MediaQuery.of(context).size.width / 3
: MediaQuery.of(context).size.width / 4,
// alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconTheme(
data: IconThemeData(
size: iconSize,
color: isSelected
? item.activeColor
: item.inactiveColor == null
? item.activeColor
: item.inactiveColor,
),
child: item.icon,
),
const SizedBox(
height: 5,
),
DefaultTextStyle.merge(
style: TextStyle(
color: item.activeColor,
fontWeight: FontWeight.bold,
fontSize: 12,
),
maxLines: 1,
//textAlign: item.textAlign,
child: item.title,
),
],
),
),
),
);
}
}
class BottomNavyBarItem {
BottomNavyBarItem({
required this.icon,
required this.title,
this.activeColor = Colors.blue,
this.textAlign,
this.inactiveColor,
});
final Widget icon;
final Widget title;
final Color activeColor;
final Color? inactiveColor;
final TextAlign? textAlign;
}
...@@ -14,7 +14,7 @@ Widget textInput(BuildContext context, dynamic titulo, dynamic cuerpo, ...@@ -14,7 +14,7 @@ Widget textInput(BuildContext context, dynamic titulo, dynamic cuerpo,
controller: TextEditingController( controller: TextEditingController(
text: cuerpo.toString(), text: cuerpo.toString(),
), ),
decoration: inputDecorationStyle(titulo.toString(), dense), //decoration: inputDecorationStyle(titulo.toString(), dense),
maxLines: null, maxLines: null,
); );
} }
......
import 'package:flutter/material.dart';
class CustomAppBar extends StatelessWidget {
final VoidCallback onLogoutButtonPress;
const CustomAppBar({required this.onLogoutButtonPress});
@override
Widget build(BuildContext context) {
return SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.blue.shade500, Colors.blue.shade900],
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
flex: 1,
child: Container(),
),
Expanded(
flex: 3,
child: Center(
child: Text(
'HOME',
style: TextStyle(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
),
),
Expanded(
flex: 1,
child: Container(
child: IconButton(
icon: Icon(
Icons.exit_to_app,
color: Colors.white,
size: 30.0,
),
onPressed: onLogoutButtonPress,
),
alignment: Alignment.centerRight,
),
),
],
),
),
);
}
}
import 'dart:convert';
import 'package:ealu_flutter/presentation/widgets/optionsGradient.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/AppTheme.dart';
import '../../core/SharedPref.dart';
class DrawerMenu extends StatelessWidget {
const DrawerMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Drawer(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(topRight: Radius.circular(50)),
),
backgroundColor: Colors.white,
child: Wrap(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12),
child: Center(
child: Image.asset(
'assets/ealu_logo.png',
width: MediaQuery.of(context).size.width * 0.5,
height: MediaQuery.of(context).size.height * 0.23,
),
),
),
_buildDrawerInstitucion(),
optionsGradient(
context, "", MediaQuery.of(context).size.width * 0.08),
/*dividerCommon(
context,
MediaQuery.of(context).size.width * 0.08,
MediaQuery.of(context).size.width * 0.08,
),*/
_buildDrawerItem(
icon: FontAwesomeIcons.bookBookmark,
text: 'Mis Reservas',
size: 22,
onTap: () => {
Navigator.pushReplacementNamed(
context, '/reservasCreadas')
}),
_buildDrawerItem(
icon: FontAwesomeIcons.bookOpen,
text: 'Mis Préstamos',
size: 22,
onTap: () => {
Navigator.pushReplacementNamed(
context, '/prestamosWithFilter')
}),
_buildDrawerItem(
icon: FontAwesomeIcons.moneyBill,
text: 'Mis Multas',
size: 22,
onTap: () =>
{Navigator.pushReplacementNamed(context, '/multas')}),
_buildDrawerItem(
icon: const IconData(0xf5d2, fontFamily: 'MaterialIcons'),
size: 24,
text: 'Nueva Reserva',
onTap: () => {
Navigator.pushReplacementNamed(
context, '/reservarWithFilter')
}),
_buildDrawerItem(
icon: const IconData(0xf521, fontFamily: 'MaterialIcons'),
text: 'Mi Perfil',
size: 26,
onTap: () =>
{Navigator.pushReplacementNamed(context, '/perfil')}),
/*dividerCommon(
context,
MediaQuery.of(context).size.width * 0.08,
MediaQuery.of(context).size.width * 0.08,
),*/
optionsGradient(
context, "", MediaQuery.of(context).size.width * 0.08),
_buildDrawerItem(
icon: FontAwesomeIcons.arrowRightFromBracket,
text: 'Cerrar Sesión',
size: 20,
onTap: () {},
//onTap: () => logout(context),
),
],
),
),
);
}
Widget _buildDrawerInstitucion() {
var ins = jsonDecode(sharedPrefs.read('institucion'));
return ListTile(
dense: true,
contentPadding: const EdgeInsets.only(
left: 28,
right: 25,
),
visualDensity: const VisualDensity(horizontal: -4, vertical: 0),
leading: const Icon(
FontAwesomeIcons.buildingColumns,
size: 22,
color: Color(0xFF99ABC0),
),
title: Text(
ins['nombre'],
style: const TextStyle(
color: Colors.black54,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
);
}
Widget _buildDrawerItem(
{required IconData icon,
required String text,
required GestureTapCallback onTap,
required double size}) {
return GestureDetector(
onTap: onTap,
child: ListTile(
dense: true,
contentPadding: const EdgeInsets.only(
left: 28,
),
visualDensity: const VisualDensity(horizontal: -4, vertical: 0),
leading: Icon(
icon,
size: size,
color: AppTheme.getSecondaryColor(),
),
title: Text(
text,
style: const TextStyle(
color: Colors.black54,
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
);
}
}
import 'package:etramite_flutter/clases/SharedPref.dart';
import 'package:etramite_flutter/screens/LoginScreen.dart';
import 'package:etramite_flutter/services/apiService.dart';
import 'package:etramite_flutter/services/toastService.dart' as toast;
import 'package:flutter/material.dart';
Future<dynamic> getLoginDB(BuildContext context, usuario, password) async {
var snapshot = await ApiService().post(
'login', null, {'username': usuario, 'password': password}).then((resp) {
var respuesta = resp?.statusCode;
// print('response $respuesta');
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
///print("cuerpo de la respuesta post a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado, credenciales inválidas");
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> getLoginGoogle(BuildContext context, token) async {
var snapshot = await ApiService().post(
'login/google',
{'googleIdToken': token},
{'googleIdToken': token},
).then((resp) {
var respuesta = resp?.statusCode;
//print('response $respuesta');
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta post a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado, credenciales inválidas");
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> registrarse(BuildContext context, dynamic body) async {
var snapshot =
await ApiService().post('registrarse', null, body).then((resp) {
var respuesta = resp?.statusCode;
//print('response $respuesta');
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta post a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> recuperarPass(BuildContext context, email) async {
var snapshot =
await ApiService().post('resetpass', null, {'email': email}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta post a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
if (resp?.data != null) {
print('retornara solo data');
return resp?.data;
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<void> logout(BuildContext context) async {
var snapshot = await ApiService().get('login', {'logout': null}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError(
"Verifique su conexión e intente de nuevo.",
);
}
if (respuesta == 200) {
//Navigator.of(context, rootNavigator: true).push(context, '/home');
//print("cuerpo de la respuesta post a ${resp?.statusMessage}");
goLoginPage(context);
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
goLoginPage(BuildContext context) async {
await sharedPrefs.save('login', 'no');
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute<void>(
builder: (BuildContext context) => const LoginScreen(),
),
(Route<dynamic> route) => false,
);
}
//Navigator.of(context).pushNamed(RoutePaths.Login);
\ No newline at end of file
import 'dart:convert';
import 'dart:io';
import 'package:etramite_flutter/services/apiService.dart';
import 'package:etramite_flutter/services/authService.dart';
import 'package:etramite_flutter/services/fileStorage.dart';
import 'package:flutter/material.dart';
import 'package:etramite_flutter/services/toastService.dart' as toast;
Future<dynamic> listaTramitesDisponibles(BuildContext context) async {
var snapshot = await ApiService().get('tipos-tramites/suggest',
{'soloActivos': 'S', 'iDisplayLength': 1000}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listaMatriculas(BuildContext context, dynamic? institu) async {
//print('institucion $institu');
var snapshot = await ApiService()
.get('alummatrics', {'institucionId': institu}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listaCiudades(BuildContext context, String? search) async {
var snapshot = await ApiService().get('ciudades-etramite/suggest',
{'iDisplayLength': 20, 'sSearch': search}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listaColegios(BuildContext context, String? search) async {
var snapshot = await ApiService().get('colegios-ealu/suggest',
{'iDisplayLength': 20, 'sSearch': search}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listaInstituciones(BuildContext context, String? search) async {
var snapshot = await ApiService().get('instituciones/suggest',
{'iDisplayLength': 20, 'iSortCol_0': 1, 'sSearch': search}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listaTramitesDocs(BuildContext context, dynamic? id) async {
//print('institucion $institu');
var snapshot = await ApiService()
.get('tipos-tramites-reqs/by-tipo-tramite/$id', null)
.then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<void> downloadTramiteArchivo(
BuildContext context, idTramite, filename) async {
var savePath = await getSavePath(context) + "/$filename";
var response = await ApiService()
.download('/mis-tramites/tipodoc/formato/$idTramite', 2, savePath);
//print(response!.headers);
var data = response!.data.toString().replaceAll('"', '').replaceAll('\n', '');
var bytes = base64Decode(data);
try {
File file = File(savePath);
var raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(bytes);
await raf.close();
} catch (e) {
print(e);
}
}
Future<dynamic> saveNewTramite(BuildContext context, dynamic data) async {
var snapshot =
await ApiService().post('mis-tramites', null, data).then((resp) {
//print('response ${resp?.data}');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
print(resp);
if (respuesta == 201) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
if (respuesta! > 401 || respuesta < 401) {
return resp?.data;
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
//for ios
import 'dart:io';
import 'package:etramite_flutter/services/toastService.dart' as toast;
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
//for ios
Future<String> requestAppDocumentsDirectory(BuildContext context) async {
await getPermision(context);
var appDocumentsDirectory = await getApplicationDocumentsDirectory();
return appDocumentsDirectory.path;
}
//for android
Future<String> requestExternalStorageDirectory(BuildContext context) async {
await getPermision(context);
/*var externalDocumentsDirectory = ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);*/
var externalDocumentsDirectory = Directory('/storage/emulated/0/Download');
/*var externalDocumentsDirectory =
await getExternalStorageDirectories(type: StorageDirectory.downloads);*/
//print("Lista de directorios $externalDocumentsDirectory");
return externalDocumentsDirectory.path;
}
getPermision(BuildContext context) async {
var status = await Permission.storage.status;
//print("statussss $status");
if (status.isGranted) {
return;
} else {
if (status.isLimited) {
await requestPermision(context);
} else {
await requestPermision(context);
}
}
}
requestPermision(BuildContext context) async {
var request = await Permission.storage.request();
if (request.isGranted) {
return;
} else {
if (request.isDenied || request.isPermanentlyDenied) {
toast.showToastSuccess(
"Debe permitir que se acceda al almacenamiento interno");
} else {
return;
}
}
}
Future<String> getSavePath(BuildContext context) async {
var directorio = Platform.isIOS
? await requestAppDocumentsDirectory(context)
: await requestExternalStorageDirectory(context);
String path = directorio;
//print("directorio, $directorio");
return path;
}
import 'dart:io';
import 'package:etramite_flutter/clases/ConectionApi.dart';
import 'package:etramite_flutter/services/apiService.dart';
import 'package:etramite_flutter/services/authService.dart';
import 'package:flutter/material.dart';
import 'package:etramite_flutter/services/toastService.dart';
Future<ImageProvider> getFoto(context, imgPath) async {
var cookie = await ConectionApi().getCookie();
Map<String, String> headersMap = {'cookie': cookie.first.toString()};
//print(headersMap);
if (imgPath != '') {
return FileImage(
File(imgPath),
);
}
return NetworkImage(
'https://tramites.una.py/etramite-backend/perfil/foto.png',
headers: headersMap,
/*fit: BoxFit.cover,
errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace) {
return Image.asset(
'assets/foto_error.png',
fit: BoxFit.cover,
);
},*/
);
}
Future<dynamic> getDatosPersonales(BuildContext context) async {
var snapshot = await ApiService().get('perfil', null).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> setActualizarDatosPersonales(
BuildContext context, dynamic datos) async {
var snapshot = await ApiService()
.post('perfil/actualizar-datos', null, datos)
.then((resp) {
print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
if (data['success'] == true) {
showToastSuccess(data['successMessage']);
}
return data;
} else {
if (respuesta == 401) {
showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> actualizarContrasenha(
BuildContext context, dynamic datos) async {
var snapshot = await ApiService()
.post('perfil/cambiar-contrasenha', null, datos)
.then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
showToastError("No autorizado");
goLoginPage(context);
}
/*if (respuesta >= 500) {
toast.showToastError("Problemas en el servidor", context, duration: 3);
}*/
return null;
}
}).catchError((error) {
showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
import 'dart:convert';
import 'dart:io';
import 'package:etramite_flutter/services/fileStorage.dart';
import 'package:flutter/material.dart';
import 'package:etramite_flutter/services/apiService.dart';
import 'package:etramite_flutter/services/toastService.dart' as toast;
import 'authService.dart';
Future<dynamic> info(BuildContext context) async {
var snapshot =
await ApiService().get('/core-session/info', null).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> cambiarInstitucion(BuildContext context, id) async {
var snapshot = await ApiService()
.get('cambiar-institucion', {'institucion': id}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> listarTramites(
BuildContext context, int start, int len, String search) async {
var snapshot = await ApiService().get('mis-tramites/datatable',
{'start': start, 'length': len, 'search': search}).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> tramiteDetalle(BuildContext context, id) async {
var snapshot = await ApiService().get('mis-tramites/$id', null).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexión");
print(error);
return null;
});
return snapshot;
}
Future<List<dynamic>> observacionTipoTramite(BuildContext context, id) async {
var snapshot = await ApiService()
.get('tipos-tramites-obs/by-tipo-tramite/$id', null)
.then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print('data $data');
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
}
return null;
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> comentariosTramite(BuildContext context, id) async {
var snapshot = await ApiService()
.get('tramites-comentarios/by-tramite/$id', null)
.then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> enviarComentarioTramite(BuildContext context, data) async {
var snapshot =
await ApiService().post('tramites-comentarios', null, data).then((resp) {
//print('response $resp');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 201) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
toast.showToastSuccess("Comentario Enviado");
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> eliminarComentarioTramite(
BuildContext context, dynamic id) async {
var snapshot =
await ApiService().delete('tramites-comentarios/$id', null).then((resp) {
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 204) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
//var data = resp?.data;
//print(resp);
return {'successMessage': "Comentario borrado con éxito"};
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<void> downloadTramiteArchivoAdjunto(
BuildContext context, idTramite, hash, filename) async {
var savePath = await getSavePath(context) + "/$filename";
//print(savePath);
var response = await ApiService()
.download('public-docsadjuntos/$idTramite/$hash', 1, savePath);
//print(response!.headers);
var data = response!.data.toString().replaceAll('"', '').replaceAll('\n', '');
var bytes = base64Decode(data);
try {
File file = File(savePath);
var raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(bytes);
await raf.close();
} catch (e) {
print(e);
}
}
Future<dynamic> cambiarArchivoAdjunto(dynamic data) async {
var snapshot = await ApiService()
.post('mis-docsadjuntos/cambiar', null, data)
.then((resp) {
print('response ${resp}');
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 200) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
var data = resp?.data;
//print(resp);
return data;
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
}
if (resp!.data != null) {
toast.showToastError(resp.data['errorMessage']);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
Future<dynamic> eliminarTramite(BuildContext context, dynamic id) async {
var snapshot =
await ApiService().delete('mis-tramites/$id', null).then((resp) {
var respuesta = resp?.statusCode;
if (respuesta != null && respuesta < 200) {
toast.showToastError("Verifique su conexión e intente de nuevo.");
}
if (respuesta == 204) {
//print("cuerpo de la respuesta get a ${resp?.statusMessage}");
//var data = resp?.data;
//print(resp);
return {'successMessage': "Trámite borrado con éxito"};
} else {
if (respuesta == 401) {
toast.showToastError("No autorizado");
goLoginPage(context);
}
return null;
}
}).catchError((error) {
toast.showToastError("Verifique su conexion");
print(error);
return null;
});
return snapshot;
}
...@@ -134,6 +134,14 @@ packages: ...@@ -134,6 +134,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.1.2" version: "8.1.2"
flutter_easyloading:
dependency: "direct main"
description:
name: flutter_easyloading
sha256: ba21a3c883544e582f9cc455a4a0907556714e1e9cf0eababfcb600da191d17c
url: "https://pub.dev"
source: hosted
version: "3.0.5"
flutter_lints: flutter_lints:
dependency: "direct dev" dependency: "direct dev"
description: description:
...@@ -142,6 +150,14 @@ packages: ...@@ -142,6 +150,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.1" version: "2.0.1"
flutter_spinkit:
dependency: transitive
description:
name: flutter_spinkit
sha256: b39c753e909d4796906c5696a14daf33639a76e017136c8d82bf3e620ce5bb8e
url: "https://pub.dev"
source: hosted
version: "5.2.0"
flutter_test: flutter_test:
dependency: "direct dev" dependency: "direct dev"
description: flutter description: flutter
...@@ -160,6 +176,14 @@ packages: ...@@ -160,6 +176,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.2.1" version: "8.2.1"
font_awesome_flutter:
dependency: "direct main"
description:
name: font_awesome_flutter
sha256: "959ef4add147753f990b4a7c6cccb746d5792dbdc81b1cde99e62e7edb31b206"
url: "https://pub.dev"
source: hosted
version: "10.4.0"
http_parser: http_parser:
dependency: transitive dependency: transitive
description: description:
......
...@@ -22,6 +22,8 @@ dependencies: ...@@ -22,6 +22,8 @@ dependencies:
dio: ^5.1.1 dio: ^5.1.1
dio_cookie_manager: ^3.0.0 dio_cookie_manager: ^3.0.0
fluttertoast: ^8.2.1 fluttertoast: ^8.2.1
flutter_easyloading: ^3.0.5
font_awesome_flutter: ^10.4.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment