minor login fixes

This commit is contained in:
2026-06-01 14:45:42 +02:00
parent b61d81d84b
commit c86c7fca49
4 changed files with 106 additions and 57 deletions

View File

@@ -7,7 +7,7 @@ RUN apt-get install -y curl git unzip
# define variables # define variables
ARG FLUTTER_SDK=/usr/local/flutter ARG FLUTTER_SDK=/usr/local/flutter
ARG FLUTTER_VERSION=3.35.6 ARG FLUTTER_VERSION=3.44.0
ARG APP=/app/ ARG APP=/app/
#clone flutter #clone flutter

View File

@@ -7,7 +7,7 @@ RUN apt-get install -y curl git unzip
# define variables # define variables
ARG FLUTTER_SDK=/usr/local/flutter ARG FLUTTER_SDK=/usr/local/flutter
ARG FLUTTER_VERSION=3.35.6 ARG FLUTTER_VERSION=3.44.0
ARG APP=/app/ ARG APP=/app/
#clone flutter #clone flutter

View File

@@ -18,13 +18,29 @@ class LoginController extends ChangeNotifier {
final model = LoginScreenModel(); final model = LoginScreenModel();
late SharedPreferences prefs; late SharedPreferences prefs;
BuildContext context; BuildContext context;
bool _disposed = false;
LoginController(this.context); LoginController(this.context);
Future<ApiResponse<LoginScreenModel>> login(String username, String password) async { @override
void dispose() {
_disposed = true;
super.dispose();
}
void _safeNotifyListeners() {
if (!_disposed) {
notifyListeners();
}
}
Future<ApiResponse<LoginScreenModel>> login(
String username,
String password,
) async {
try { try {
model.isLoading = true; model.isLoading = true;
notifyListeners(); _safeNotifyListeners();
prefs = await SharedPreferences.getInstance(); prefs = await SharedPreferences.getInstance();
@@ -35,7 +51,7 @@ class LoginController extends ChangeNotifier {
logger.i(response.toString()); logger.i(response.toString());
model.isLoading = false; model.isLoading = false;
notifyListeners(); _safeNotifyListeners();
if (response.containsKey('token')) { if (response.containsKey('token')) {
model.status = 'SUCCESS'; model.status = 'SUCCESS';
@@ -47,26 +63,32 @@ class LoginController extends ChangeNotifier {
prefs.setString('lastName', response['lastName']); prefs.setString('lastName', response['lastName']);
prefs.setString('phone', response['phone']); prefs.setString('phone', response['phone']);
prefs.setString('userId', response['uuid']); prefs.setString('userId', response['uuid']);
prefs.setString('initials', response['firstName'].substring(0, 1) + response['lastName'].substring(0, 1)); prefs.setString(
'initials',
response['firstName'].substring(0, 1) +
response['lastName'].substring(0, 1),
);
return ApiResponse.success(model); return ApiResponse.success(model);
} else { } else {
model.errorMessage = model.errorMessage =
response['errorMessage'] ?? response['errorMessage'] ??
"Problem with the transaction. Please try again or contact support"; "Problem with the operation. Please try again or contact support";
return ApiResponse.failure(model.errorMessage!); return ApiResponse.failure(model.errorMessage!);
} }
} on DioException catch (e, s) { } on DioException catch (e, s) {
logger.e(s); logger.e(s);
model.isLoading = false; model.isLoading = false;
notifyListeners(); _safeNotifyListeners();
return ApiResponse.failure(e.response?.data['errors'][0] ?? "Unknown error"); return ApiResponse.failure(
e.response?.data['errors'][0] ?? "Unknown error",
);
} catch (e, s) { } catch (e, s) {
logger.e(s); logger.e(s);
model.isLoading = false; model.isLoading = false;
notifyListeners(); _safeNotifyListeners();
return ApiResponse.failure( return ApiResponse.failure(
"Problem processing that transaction. Please try again or contact support", "Problem processing that operation. Please try again or contact support",
); );
} }
} }

View File

@@ -31,6 +31,7 @@ class _LoginScreenState extends State<LoginScreen> {
]; ];
late LoginController _loginController; late LoginController _loginController;
StreamSubscription<GoogleSignInAuthenticationEvent>? _authSubscription;
@override @override
void initState() { void initState() {
@@ -38,26 +39,28 @@ class _LoginScreenState extends State<LoginScreen> {
_loginController = LoginController(context); _loginController = LoginController(context);
googleSignIn = GoogleSignIn.instance; googleSignIn = GoogleSignIn.instance;
if(kIsWeb){ if (kIsWeb) {
googleSignIn.initialize(); googleSignIn.initialize();
googleSignIn.authenticationEvents _authSubscription = googleSignIn.authenticationEvents
.listen(_handleAuthenticationEvent) .handleError(_handleAuthenticationError)
.onError(_handleAuthenticationError); .listen(_handleAuthenticationEvent);
} else {
}else { unawaited(
unawaited(googleSignIn.initialize(serverClientId: dotenv.env['CLIENTID'])); googleSignIn.initialize(serverClientId: dotenv.env['CLIENTID']),
);
} }
} }
Future<void> signInWithGoogle() async { Future<void> signInWithGoogle() async {
if (GoogleSignIn.instance.supportsAuthenticate()){ if (GoogleSignIn.instance.supportsAuthenticate()) {
unawaited(GoogleSignIn.instance.authenticate().then((value) async { _authSubscription?.cancel();
googleSignIn.authenticationEvents unawaited(
.listen(_handleAuthenticationEvent) GoogleSignIn.instance.authenticate().then((value) async {
.onError(_handleAuthenticationError); _authSubscription = googleSignIn.authenticationEvents
.handleError(_handleAuthenticationError)
})); .listen(_handleAuthenticationEvent);
}),
);
} }
} }
@@ -76,15 +79,19 @@ class _LoginScreenState extends State<LoginScreen> {
} }
Future<void> _handleAuthenticationEvent( Future<void> _handleAuthenticationEvent(
GoogleSignInAuthenticationEvent event, GoogleSignInAuthenticationEvent event,
) async { ) async {
if (!mounted) return;
// #docregion CheckAuthorization // #docregion CheckAuthorization
final GoogleSignInAccount? user = // ... final GoogleSignInAccount? user = // ...
// #enddocregion CheckAuthorization // #enddocregion CheckAuthorization
switch (event) { switch (event) {
GoogleSignInAuthenticationEventSignIn() => event.user, GoogleSignInAuthenticationEventSignIn() => event.user,
GoogleSignInAuthenticationEventSignOut() => null, GoogleSignInAuthenticationEventSignOut() => null,
}; };
if (user == null || !mounted) return;
// Check for existing authorization. // Check for existing authorization.
// #docregion CheckAuthorization // #docregion CheckAuthorization
@@ -94,9 +101,29 @@ class _LoginScreenState extends State<LoginScreen> {
// #enddocregion CheckAuthorization // #enddocregion CheckAuthorization
print(user); print(user);
saveUser(user as GoogleSignInAccount); saveUser(user);
await _loginController.login(user.email, user.id); if (!mounted) return;
final response = await _loginController.login(user.email, user.id);
if (response.isSuccess) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Login successful!"),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.green,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(response.error ?? "Login failed"),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.deepOrange,
),
);
}
if (!mounted) return;
context.go('/'); context.go('/');
} }
@@ -106,6 +133,7 @@ class _LoginScreenState extends State<LoginScreen> {
@override @override
void dispose() { void dispose() {
_authSubscription?.cancel();
_loginController.dispose(); _loginController.dispose();
super.dispose(); super.dispose();
} }
@@ -120,12 +148,12 @@ class _LoginScreenState extends State<LoginScreen> {
key: _formKey, key: _formKey,
child: Center( child: Center(
child: LayoutBuilder( child: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final maxWidth = constraints.maxWidth > ResponsivePolicy.md final maxWidth = constraints.maxWidth > ResponsivePolicy.md
? ResponsivePolicy.md.toDouble() ? ResponsivePolicy.md.toDouble()
: constraints.maxWidth; : constraints.maxWidth;
return SizedBox( return SizedBox(
width: maxWidth, width: maxWidth,
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
@@ -158,7 +186,9 @@ class _LoginScreenState extends State<LoginScreen> {
// Divider with "or" text // Divider with "or" text
Row( Row(
children: [ children: [
Expanded(child: Divider(color: Colors.grey.shade300)), Expanded(
child: Divider(color: Colors.grey.shade300),
),
Padding( Padding(
padding: EdgeInsets.symmetric(horizontal: 16), padding: EdgeInsets.symmetric(horizontal: 16),
child: Text( child: Text(
@@ -170,28 +200,30 @@ class _LoginScreenState extends State<LoginScreen> {
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
Expanded(child: Divider(color: Colors.grey.shade300)), Expanded(
child: Divider(color: Colors.grey.shade300),
),
], ],
), ),
SizedBox(height: 30), SizedBox(height: 30),
// Social Login Buttons // Social Login Buttons
if(GoogleSignIn.instance.supportsAuthenticate()) if (GoogleSignIn.instance.supportsAuthenticate())
_buildGoogleButton() _buildGoogleButton()
else ...<Widget>[ else ...<Widget>[if (kIsWeb) web.renderButton()],
if (kIsWeb)
web.renderButton()
],
SizedBox(height: 40), SizedBox(height: 40),
TextButton( TextButton(
onPressed: () { onPressed: () {
context.go('/'); context.go('/');
}, },
child: Text('Continue as guest?', style: TextStyle(fontSize: 14)), child: Text(
'Continue as guest?',
style: TextStyle(fontSize: 14),
),
), ),
], ],
), ),
); );
} },
), ),
), ),
), ),
@@ -200,7 +232,7 @@ class _LoginScreenState extends State<LoginScreen> {
); );
} }
Widget _buildGoogleButton(){ Widget _buildGoogleButton() {
return Skeletonizer( return Skeletonizer(
enabled: _loading, enabled: _loading,
child: Row( child: Row(
@@ -210,11 +242,7 @@ class _LoginScreenState extends State<LoginScreen> {
onPressed: () { onPressed: () {
signInWithGoogle(); signInWithGoogle();
}, },
icon: Image.asset( icon: Image.asset('assets/google.png', width: 20, height: 20),
'assets/google.png',
width: 20,
height: 20,
),
label: Text('Google', style: TextStyle(fontSize: 16)), label: Text('Google', style: TextStyle(fontSize: 16)),
style: OutlinedButton.styleFrom( style: OutlinedButton.styleFrom(
padding: EdgeInsets.symmetric(vertical: 16), padding: EdgeInsets.symmetric(vertical: 16),
@@ -230,5 +258,4 @@ class _LoginScreenState extends State<LoginScreen> {
), ),
); );
} }
} }