refactor: Improve LoginController and LoginScreen structure and readability

This commit is contained in:
Vaibhav Surve 2025-05-31 10:43:39 +05:30
parent ad4b24dd78
commit 08991f2095
2 changed files with 228 additions and 217 deletions

View File

@ -6,51 +6,65 @@ import 'package:marco/helpers/widgets/my_form_validator.dart';
import 'package:marco/helpers/widgets/my_validators.dart'; import 'package:marco/helpers/widgets/my_validators.dart';
class LoginController extends MyController { class LoginController extends MyController {
MyFormValidator basicValidator = MyFormValidator(); // Form validator
final MyFormValidator basicValidator = MyFormValidator();
bool showPassword = false, isChecked = false; // UI states
RxBool isLoading = false.obs; // Add reactive loading state final RxBool isLoading = false.obs;
final RxBool showPassword = false.obs;
final RxBool isChecked = false.obs;
// Dummy credentials
final String _dummyEmail = "admin@marcoaiot.com"; final String _dummyEmail = "admin@marcoaiot.com";
final String _dummyPassword = "User@123"; final String _dummyPassword = "User@123";
@override @override
void onInit() { void onInit() {
basicValidator.addField('username', required: true, label: "User_Name", validators: [MyEmailValidator()], controller: TextEditingController(text: _dummyEmail));
basicValidator.addField('password', required: true, label: "Password", validators: [MyLengthValidator(min: 6, max: 10)], controller: TextEditingController(text: _dummyPassword));
super.onInit(); super.onInit();
basicValidator.addField(
'username',
required: true,
label: "User_Name",
validators: [MyEmailValidator()],
controller: TextEditingController(text: _dummyEmail),
);
basicValidator.addField(
'password',
required: true,
label: "Password",
validators: [MyLengthValidator(min: 6, max: 10)],
controller: TextEditingController(text: _dummyPassword),
);
} }
void onChangeCheckBox(bool? value) { void onChangeCheckBox(bool? value) {
isChecked = value ?? isChecked; isChecked.value = value ?? isChecked.value;
update();
} }
void onChangeShowPassword() { void onChangeShowPassword() {
showPassword = !showPassword; showPassword.toggle();
update();
} }
Future<void> onLogin() async { Future<void> onLogin() async {
if (basicValidator.validateForm()) { if (!basicValidator.validateForm()) return;
// Set loading to true
isLoading.value = true; isLoading.value = true;
update();
final errors = await AuthService.loginUser(basicValidator.getData());
var errors = await AuthService.loginUser(basicValidator.getData());
if (errors != null) { if (errors != null) {
basicValidator.addErrors(errors); basicValidator.addErrors(errors);
basicValidator.validateForm(); basicValidator.validateForm();
basicValidator.clearErrors(); basicValidator.clearErrors();
} else { } else {
String nextUrl = Uri.parse(ModalRoute.of(Get.context!)?.settings.name ?? "").queryParameters['next'] ?? "/home"; final currentRoute = ModalRoute.of(Get.context!)?.settings.name ?? "";
final nextUrl = Uri.parse(currentRoute).queryParameters['next'] ?? "/home";
Get.toNamed(nextUrl); Get.toNamed(nextUrl);
} }
// Set loading to false after the API call is complete
isLoading.value = false; isLoading.value = false;
update();
}
} }
void goToForgotPassword() { void goToForgotPassword() {

View File

@ -20,11 +20,11 @@ class LoginScreen extends StatefulWidget {
} }
class _LoginScreenState extends State<LoginScreen> with UIMixin { class _LoginScreenState extends State<LoginScreen> with UIMixin {
late LoginController controller; late final LoginController controller;
@override @override
void initState() { void initState() {
controller = Get.put(LoginController()); controller = Get.put(LoginController(), tag: 'login_controller');
super.initState(); super.initState();
} }
@ -32,13 +32,14 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AuthLayout( return AuthLayout(
child: GetBuilder<LoginController>( child: GetBuilder<LoginController>(
init: controller,
tag: 'login_controller', tag: 'login_controller',
builder: (controller) { builder: (_) {
return Obx(() { return Obx(() {
return controller.isLoading.value if (controller.isLoading.value) {
? Center(child: CircularProgressIndicator()) // Show loading spinner when isLoading is true return const Center(child: CircularProgressIndicator());
: Form( }
return Form(
key: controller.basicValidator.formKey, key: controller.basicValidator.formKey,
child: SingleChildScrollView( child: SingleChildScrollView(
padding: MySpacing.xy(2, 40), padding: MySpacing.xy(2, 40),
@ -65,104 +66,64 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
), ),
MySpacing.height(20), MySpacing.height(20),
/// Welcome Text /// Welcome
Center( Center(child: MyText.bodyLarge("Welcome Back!", fontWeight: 600)),
child: MyText.bodyLarge("Welcome Back!", fontWeight: 600),
),
MySpacing.height(4), MySpacing.height(4),
Center( Center(child: MyText.bodySmall("Please sign in to continue.")),
child: MyText.bodySmall("Please sign in to continue."),
),
MySpacing.height(20), MySpacing.height(20),
/// Email Field /// Email
MyText.bodySmall("Email Address", fontWeight: 600), MyText.bodySmall("Email Address", fontWeight: 600),
MySpacing.height(8), MySpacing.height(8),
Material( _buildInputField(
elevation: 2, controller.basicValidator.getController('username')!,
shadowColor: contentTheme.secondary.withAlpha(30),
borderRadius: BorderRadius.circular(12),
child: TextFormField(
validator:
controller.basicValidator.getValidation('username'), controller.basicValidator.getValidation('username'),
controller:
controller.basicValidator.getController('username'),
keyboardType: TextInputType.emailAddress,
style: MyTextStyle.labelMedium(),
decoration: InputDecoration(
hintText: "Enter your email", hintText: "Enter your email",
hintStyle: MyTextStyle.bodySmall(xMuted: true), icon: LucideIcons.mail,
filled: true, keyboardType: TextInputType.emailAddress,
fillColor: theme.cardColor,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(2),
borderSide: BorderSide.none,
),
prefixIcon: const Icon(LucideIcons.mail, size: 18),
contentPadding: MySpacing.xy(12, 16),
),
),
), ),
MySpacing.height(16), MySpacing.height(16),
/// Password Field Label /// Password
MyText.bodySmall("Password", fontWeight: 600), MyText.bodySmall("Password", fontWeight: 600),
MySpacing.height(8), MySpacing.height(8),
Material( Obx(() {
elevation: 2, return _buildInputField(
shadowColor: contentTheme.secondary.withAlpha(25), controller.basicValidator.getController('password')!,
borderRadius: BorderRadius.circular(12),
child: TextFormField(
validator:
controller.basicValidator.getValidation('password'), controller.basicValidator.getValidation('password'),
controller:
controller.basicValidator.getController('password'),
keyboardType: TextInputType.visiblePassword,
obscureText: !controller.showPassword,
style: MyTextStyle.labelMedium(),
decoration: InputDecoration(
hintText: "Enter your password", hintText: "Enter your password",
hintStyle: MyTextStyle.bodySmall(xMuted: true), icon: LucideIcons.lock,
filled: true, obscureText: !controller.showPassword.value,
fillColor: theme.cardColor, suffix: IconButton(
border: OutlineInputBorder( icon: Icon(
borderRadius: BorderRadius.circular(2), controller.showPassword.value
borderSide: BorderSide.none,
),
prefixIcon: const Icon(LucideIcons.lock, size: 18),
suffixIcon: InkWell(
onTap: controller.onChangeShowPassword,
child: Icon(
controller.showPassword
? LucideIcons.eye ? LucideIcons.eye
: LucideIcons.eye_off, : LucideIcons.eye_off,
size: 18, size: 18,
), ),
onPressed: controller.onChangeShowPassword,
), ),
contentPadding: MySpacing.all(3), );
), }),
),
),
MySpacing.height(16), MySpacing.height(16),
/// Remember Me + Forgot Password /// Remember me + Forgot password
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
InkWell( Obx(() {
onTap: () => controller return InkWell(
.onChangeCheckBox(!controller.isChecked), onTap: () =>
controller.onChangeCheckBox(!controller.isChecked.value),
child: Row( child: Row(
children: [ children: [
Checkbox( Checkbox(
value: controller.isChecked.value,
onChanged: controller.onChangeCheckBox, onChanged: controller.onChangeCheckBox,
value: controller.isChecked,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
), ),
fillColor: WidgetStatePropertyAll( fillColor: WidgetStatePropertyAll(contentTheme.secondary),
contentTheme.secondary),
checkColor: contentTheme.onPrimary, checkColor: contentTheme.onPrimary,
visualDensity: getCompactDensity, visualDensity: getCompactDensity,
materialTapTargetSize: materialTapTargetSize:
@ -172,7 +133,8 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
MyText.bodySmall("Remember Me"), MyText.bodySmall("Remember Me"),
], ],
), ),
), );
}),
MyButton.text( MyButton.text(
onPressed: controller.goToForgotPassword, onPressed: controller.goToForgotPassword,
elevation: 0, elevation: 0,
@ -188,7 +150,7 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
), ),
MySpacing.height(28), MySpacing.height(28),
/// Login Button /// Login button
Center( Center(
child: MyButton.rounded( child: MyButton.rounded(
onPressed: controller.onLogin, onPressed: controller.onLogin,
@ -205,7 +167,7 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
), ),
MySpacing.height(16), MySpacing.height(16),
/// Register Link /// Request demo
Center( Center(
child: MyButton.text( child: MyButton.text(
onPressed: () { onPressed: () {
@ -213,8 +175,7 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
}, },
elevation: 0, elevation: 0,
padding: MySpacing.xy(12, 8), padding: MySpacing.xy(12, 8),
splashColor: splashColor: contentTheme.secondary.withAlpha(30),
contentTheme.secondary.withAlpha(30),
child: MyText.bodySmall( child: MyText.bodySmall(
"Request a Demo", "Request a Demo",
color: contentTheme.secondary, color: contentTheme.secondary,
@ -232,4 +193,40 @@ class _LoginScreenState extends State<LoginScreen> with UIMixin {
), ),
); );
} }
Widget _buildInputField(
TextEditingController controller,
FormFieldValidator<String>? validator, {
required String hintText,
required IconData icon,
TextInputType keyboardType = TextInputType.text,
bool obscureText = false,
Widget? suffix,
}) {
return Material(
elevation: 2,
shadowColor: contentTheme.secondary.withAlpha(30),
borderRadius: BorderRadius.circular(12),
child: TextFormField(
controller: controller,
validator: validator,
obscureText: obscureText,
keyboardType: keyboardType,
style: MyTextStyle.labelMedium(),
decoration: InputDecoration(
hintText: hintText,
hintStyle: MyTextStyle.bodySmall(xMuted: true),
filled: true,
fillColor: theme.cardColor,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(2),
borderSide: BorderSide.none,
),
prefixIcon: Icon(icon, size: 18),
suffixIcon: suffix,
contentPadding: MySpacing.xy(12, 16),
),
),
);
}
} }