83 lines
2.4 KiB
Dart
83 lines
2.4 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:qpay/http/http.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class LoginScreenModel {
|
|
String username = "";
|
|
String password = "";
|
|
String status = "PENDING";
|
|
|
|
bool isLoading = false;
|
|
String? errorMessage;
|
|
}
|
|
|
|
class LoginController extends ChangeNotifier {
|
|
final Http http = Http();
|
|
final model = LoginScreenModel();
|
|
late SharedPreferences prefs;
|
|
BuildContext context;
|
|
|
|
LoginController(this.context);
|
|
|
|
void _showErrorSnackBar(String? message) {
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text(message.toString()),
|
|
behavior: SnackBarBehavior.floating,
|
|
backgroundColor: Colors.deepOrange,
|
|
),
|
|
);
|
|
});
|
|
}
|
|
|
|
Future<LoginScreenModel> login(String username, String password) async {
|
|
try {
|
|
model.isLoading = true;
|
|
notifyListeners();
|
|
|
|
prefs = await SharedPreferences.getInstance();
|
|
|
|
dynamic response = await http.post('/auth/login', {
|
|
'username': username,
|
|
'password': password,
|
|
});
|
|
logger.i(response.toString());
|
|
|
|
if (response.containsKey('token')) {
|
|
model.status = 'SUCCESS';
|
|
|
|
prefs.setString('token', response['token']);
|
|
prefs.setString('username', username);
|
|
prefs.setString('email', response['email']);
|
|
prefs.setString('firstName', response['firstName']);
|
|
prefs.setString('lastName', response['lastName']);
|
|
prefs.setString('phone', response['phone']);
|
|
prefs.setString('userId', response['uuid']);
|
|
prefs.setString('initials', response['firstName'].substring(0, 1) + response['lastName'].substring(0, 1));
|
|
|
|
return model;
|
|
} else {
|
|
model.errorMessage =
|
|
response['errorMessage'] ??
|
|
"Problem with the transaction. Please try again or contact support";
|
|
_showErrorSnackBar(model.errorMessage);
|
|
}
|
|
} on DioException catch (e, s) {
|
|
logger.e(s);
|
|
_showErrorSnackBar(e.response?.data['errors'][0] ?? "Unknown error");
|
|
} catch (e, s) {
|
|
logger.e(s);
|
|
_showErrorSnackBar(
|
|
"Problem processing that transaction. Please try again or contact support",
|
|
);
|
|
}
|
|
|
|
model.isLoading = false;
|
|
notifyListeners();
|
|
|
|
return model;
|
|
}
|
|
}
|