StateFul Widget Not Rebuilding When Calling ValidateEvent with TextField onchange function flutter_bloc

I have a textfield with an onchnaged function which calls the validate service then returns the value to the widget.
i used print values to debug the code just to make sure everything was working fine. and they were indeed working. The validate service works and outputs the desired result but the state soesnt get emitted.

This the email_page.dart where the onchaned function is called.

import 'package:campfind/bloc/components/component_bloc.dart';
import 'package:campfind/bloc/components/component_event.dart';
import 'package:flutter/services.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:campfind/locators/locator.dart';
import 'package:campfind/materialui/auth/social_details.dart';
import 'package:campfind/services/auth_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:package_name/materialui/components.dart';
import './password_page.dart';
import './details_page.dart';
import '../../bloc/auth/auth_bloc.dart';
import '../../bloc/auth/auth_event.dart';
import '../../bloc/auth/auth_state.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

class EmailPage extends StatefulWidget {
  @override
  State<EmailPage> createState() => _EmailPageState();
}

class _EmailPageState extends State<EmailPage> {
  final FocusNode _emailFocusNode = FocusNode();
  final TextEditingController _emailController = TextEditingController();
  bool isDisabled = true;
  double borderWidth = 1.0;
  Color borderColor = Colors.grey.shade300;
  final AuthBloc _authBloc = getIt<AuthBloc>();
  final ComponentBloc _componentBloc = getIt<ComponentBloc>();

  @override
  void initState() {
    super.initState();
    _emailFocusNode.addListener(() {
      _authBloc.add(ValidateFieldEvent('name', _emailController.text));
    });
  }

  @override
  void dispose() {
    _emailFocusNode.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthBloc, AuthInputState>(listener: (context, state) {
      final fieldState = state.fields['email'];
      if (fieldState != null && fieldState.errorMessage != null) {
        buildErrorScaffold(fieldState.errorMessage ?? '', context);
      } else if (state.navigationState == NavigationState.toPassword) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => PasswordPage(email: _emailController.text)));
      } else if (state.navigationState == NavigationState.toDetail) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => DetailsPage(email: _emailController.text)));
      } else if (state.navigationState == NavigationState.toSocialDetail) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) =>
                    SocialDetailPage(email: _emailController.text)));
      }
    }, child: BlocBuilder<AuthBloc, AuthInputState>(builder: (context, state) {
      final emailField = state.fields['email'] ?? FieldState();
      print('me and friend ${emailField.isValid}');
      return Scaffold(
        body: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(vertical: 17.0, horizontal: 20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 80),
              Text(
                'Login or sign up. ${emailField.isValid}',
                style: TextStyle(
                    fontSize: 22,
                    color: Theme.of(context).primaryColor,
                    fontWeight: FontWeight.w500),
              ),
              const SizedBox(height: 50),
              EmailTextField(
                onChanged: (email) =>
                    _authBloc.add(ValidateFieldEvent('email', email)),
                focusNode: _emailFocusNode,
                controller: _emailController,
                isDisabled: !emailField.isValid,
                onTapOutside: (event) => _componentBloc.add(KeyboardEvent()),
                errorText: emailField.errorMessage,
              ),
              // BlocBuilder<AuthBloc, AppAuthState>(
              //   builder: (context, state) {
              //     if (state is InvalidState &&
              //         _emailController == state.controller) {
              //       return Text(
              //         state.errorMessage,
              //         style: const TextStyle(color: Colors.red, fontSize: 12),
              //       );
              //     }
              //     return const SizedBox.shrink();
              //   },
              // ),
              const SizedBox(height: 15),
              SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                      onPressed: emailField.isValid
                          ? () {
                              _authBloc
                                  .add(CheckEmailEvent(_emailController.text));
                            }
                          : null,
                      style: ButtonStyle(
                        foregroundColor: WidgetStateProperty.all(
                            Theme.of(context).colorScheme.onPrimary),
                        backgroundColor: WidgetStateProperty.resolveWith<Color>(
                          (Set<WidgetState> states) {
                            return emailField.isValid
                                ? Theme.of(context).colorScheme.primary
                                : Colors.grey;
                          },
                        ),
                        padding: WidgetStateProperty.all(
                            const EdgeInsets.symmetric(vertical: 15)),
                        textStyle: WidgetStateProperty.all(
                            const TextStyle(fontSize: 18)),
                        shape: WidgetStateProperty.all(
                          RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0)),
                        ),
                      ),
                      child: state.isLoading
                          ? LoadingAnimationWidget.inkDrop(
                              color: Theme.of(context).colorScheme.onPrimary,
                              size: 20)
                          : Text(AppLocalizations.of(context)!.proceed))),

              const SizedBox(height: 20),
              const Center(
                  child: Row(
                children: [
                  Text('or continue with'),
                ],
              )),
              const SizedBox(height: 20),
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: _buildSocialButton(
                        'assets/svg/facebook.svg',
                        'Facebook',
                        () => _authBloc.add(SocialSignEvent(
                              provider: SocialAuthProvider.facebook,
                            )),
                        state),
                  ),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    child: _buildSocialButton(
                        'assets/svg/google.svg',
                        'Google',
                        () => _authBloc.add(SocialSignEvent(
                            provider: SocialAuthProvider.google)),
                        state),
                  ),
                  const SizedBox(height: 10),
                  SizedBox(
                    width: double.infinity,
                    child: _buildSocialButton(
                        'assets/svg/apple.svg',
                        'Apple',
                        () => _authBloc.add(SocialSignEvent(
                            provider: SocialAuthProvider.apple)),
                        state),
                  )
                ],
              ),
              const SizedBox(height: 20),
            ],
          ),
        ),
      );
    }));
  }

  Widget _buildSocialButton(String assetPath, String label,
      void Function()? socialAuth, AuthInputState state) {
    return OutlinedButton(
      onPressed: socialAuth,
      style: OutlinedButton.styleFrom(
        foregroundColor: Theme.of(context).primaryColor,
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
        textStyle: const TextStyle(
            fontSize: 16, fontFamily: 'OpenSans', fontWeight: FontWeight.w500),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.0),
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          SvgPicture.asset(assetPath, height: 24),
          const Spacer(),
          Text(label),
        ],
      ),
    );
  }
}

class EmailTextField extends StatelessWidget {
  final void Function(String) onChanged;
  final FocusNode focusNode;
  final TextEditingController controller;
  final bool isDisabled;
  final String? errorText;
  final void Function(PointerDownEvent) onTapOutside;

  const EmailTextField(
      {super.key,
      required this.onChanged,
      required this.focusNode,
      required this.controller,
      required this.isDisabled,
      this.errorText,
      required this.onTapOutside});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 14, right: 14),
      decoration: BoxDecoration(
        border: Border.all(
            color: errorText != ''
                ? Colors.red
                : (focusNode.hasFocus ? Colors.black : Colors.grey.shade300),
            width: focusNode.hasFocus ? 2.0 : 1.0),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: TextField(
        focusNode: focusNode,
        controller: controller,
        onChanged: onChanged,
        keyboardType: TextInputType.emailAddress,
        autocorrect: false,
        onTapOutside: onTapOutside,
        decoration: InputDecoration(
          labelText: 'Email',
          labelStyle: TextStyle(color: Theme.of(context).colorScheme.secondary),
          floatingLabelBehavior: FloatingLabelBehavior.always,
          border: InputBorder.none,
          errorText: errorText,
        ),
      ),
    );
  }
}

This is the auth_bloc.dart:

import 'package:package_name/locators/locator.dart';
import 'package:package_name/services/auth_service.dart';
import 'package:package_name/services/date_service.dart';
import 'package:package_name/services/validate_service.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import 'auth_event.dart';
import 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthInputState> {
  final AuthService _authService = getIt<AuthService>();
  final ValidateService _validateService = getIt<ValidateService>();
  final DateService _dateService = getIt<DateService>();

  AuthBloc() : super(AuthInputState(fields: {}, socialValues: {})) {
    on<ValidateFieldEvent>(_onValidateField);
    on<TogglePasswordVisibilityEvent>(_onTogglePasswordVisibility);
    on<SubmitFormEvent>(_onSubmitForm);
    on<ResetFormEvent>(_onResetForm);
    on<SetLoadingEvent>(_onSetLoading);
    on<SetFieldErrorEvent>(_onSetFieldError);
    on<DateSelectedEvent>(_onDateSelected);
    on<CheckEmailEvent>(_checkEmail);
    on<SocialSignEvent>(_socialSignIn);
    on<SocialAuthEvent>(_socialAuth);
  }

  void _onValidateField(
      ValidateFieldEvent event, Emitter<AuthInputState> emit) {
    final updatedField = _validateField(event.fieldName, event.value);
    print(updatedField.borderColor);
    final updatedFields = Map<String, FieldState>.from(state.fields);
    updatedFields[event.fieldName] = updatedField;
    emit(state.copyWith(fields: updatedFields));
    print(
        'Field ${event.fieldName} updated. Valid: ${updatedField.isValid}, Error: ${updatedField.errorMessage}');
  }

  void _onTogglePasswordVisibility(
      TogglePasswordVisibilityEvent event, Emitter<AuthInputState> emit) {
    final passwordField = state.fields[event.fieldName];
    if (passwordField != null) {
      final updatedField =
          passwordField.copyWith(obscureText: !passwordField.obscureText);
      final updatedFields = Map<String, FieldState>.from(state.fields);
      updatedFields[event.fieldName] = updatedField;

      emit(state.copyWith(fields: updatedFields));
    }
  }



  void _onResetForm(ResetFormEvent event, Emitter<AuthInputState> emit) {
    emit(AuthInputState(fields: {}, socialValues: {}));
  }

  void _onSetLoading(SetLoadingEvent event, Emitter<AuthInputState> emit) {
    emit(state.copyWith(isLoading: event.isLoading));
  }



  void _onSetFieldError(
      SetFieldErrorEvent event, Emitter<AuthInputState> emit) {
    final updatedFields = Map<String, FieldState>.from(state.fields);
    final currentField = updatedFields[event.fieldName] ?? FieldState();
    updatedFields[event.fieldName] = currentField.copyWith(
      isValid: false,
      errorMessage: event.errorMessage,
      borderColor: Colors.red,
    );
    emit(state.copyWith(fields: updatedFields));
  }


  FieldState _validateField(String fieldName, String value) {
    final validationFunction = _getValidationFunction(fieldName);
    if (validationFunction == null) {
      print("No validation function found for field: $fieldName");
      return FieldState(isValid: true, value: value);
    }
    return validationFunction(value);
  }

  Function? _getValidationFunction(String fieldName) {
    final validationMap = {
      'email': _validateService.validateEmail,
      'password': _validateService.validatePassword,
      'first_name': _validateService.validateName,
      'last_name': _validateService.validateName,
    };
    return validationMap[fieldName];
  }

  FieldState _defaultValidation(String value) {
    return FieldState(isValid: true);
  }

  Future<void> selectDate(BuildContext context) async {
    final selectedDate = await _dateService.selectDay(context: context);
    add(DateSelectedEvent(selectedDate));
  }
}

This is the Auth_event.dart code:

import 'package:campfind/services/auth_service.dart';
import 'package:equatable/equatable.dart';

abstract class AuthEvent extends Equatable {
  const AuthEvent();

  @override
  List<Object?> get props => [];
}



// TEXT FIELD EVENTS
class ValidateFieldEvent extends AuthEvent {
  final String fieldName;
  final String value;

  ValidateFieldEvent(this.fieldName, this.value);
  @override
  List<Object> get props => [fieldName, value];
}

class DateSelectedEvent extends AuthEvent {

  final DateTime? selectedDate;
  const DateSelectedEvent(this.selectedDate);
  @override
  List<Object?> get props => [selectedDate];
}

class TogglePasswordVisibilityEvent extends AuthEvent {
  final String fieldName;

  TogglePasswordVisibilityEvent(this.fieldName);
}

class ResetFormEvent extends AuthEvent {}

class SetLoadingEvent extends AuthEvent {
  final bool isLoading;

  SetLoadingEvent(this.isLoading);
}

class SetFieldErrorEvent extends AuthEvent {
  final String fieldName;
  final String errorMessage;

  SetFieldErrorEvent(this.fieldName, this.errorMessage);
}


finally this is the auth_state.dart code:

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';

abstract class AppAuthState extends Equatable {
  const AppAuthState();

  @override
  List<Object?> get props => [];
}

class AuthInitial extends AppAuthState {}

enum NavigationState { initial, toPassword, toDetail, toSocialDetail }

class AuthInputState extends AppAuthState {
  final Map<String, FieldState> fields;
  final bool isLoading;
  final bool gLoading;
  final bool aLoading;
  final bool fLoading;
  final bool isAuthenticated;
  final NavigationState navigationState;
  final Map<String, SocialAuthState> socialValues;

  AuthInputState(
      {required this.fields,
      this.isLoading = false,
      this.gLoading = false,
      this.aLoading = false,
      this.fLoading = false,
      this.isAuthenticated = false,
      this.navigationState = NavigationState.initial,
      required this.socialValues});
  
  AuthInputState copyWith({
    Map<String, FieldState>? fields,
    bool? isLoading,
    bool? gLoading = false,
    bool? aLoading = false,
    bool? fLoading = false,
    bool? isAuthenticated,
    NavigationState? navigationState,
    Map<String, SocialAuthState>? socialValues,
  }) {
    return AuthInputState(
      fields: fields ?? this.fields,
      isLoading: isLoading ?? this.isLoading,
      gLoading: gLoading ?? this.gLoading,
      aLoading: aLoading ?? this.aLoading,
      fLoading: fLoading ?? this.fLoading,
      isAuthenticated: isAuthenticated ?? this.isAuthenticated,
      navigationState: navigationState ?? this.navigationState,
      socialValues: socialValues ?? this.socialValues,
    );
  }
  @override
  List<Object> get props => [isLoading, gLoading, aLoading, fLoading, isAuthenticated, navigationState, socialValues];
}

class SocialAuthState{
  final String? accessToken;
  final String? idToken;
  final String? provider;

  SocialAuthState({this.accessToken, this.idToken, this.provider});

  SocialAuthState copyWith({
    String? accessToken,
    String? idToken,
    String? provider,
  }) {
    return SocialAuthState(
        accessToken: accessToken ?? '',
        idToken: idToken ?? '',
        provider: provider ?? '');
  }
}

class FieldState {
  final bool isValid;
  final String? errorMessage;
  final Color borderColor;
  final double borderWidth;
  final bool obscureText;
  final String value;

  FieldState({
    this.isValid = false,
    this.errorMessage = '',
    this.borderColor = Colors.grey,
    this.borderWidth = 1.0,
    this.obscureText = false,
    this.value = '',
  });

  FieldState copyWith(
      {bool? isValid,
      String? errorMessage,
      Color? borderColor,
      double? borderWidth,
      bool? obscureText,
      String? value}) {
    return FieldState(
        isValid: isValid ?? this.isValid,
        errorMessage: errorMessage ?? this.errorMessage,
        borderColor: borderColor ?? this.borderColor,
        borderWidth: borderWidth ?? this.borderWidth,
        obscureText: obscureText ?? this.obscureText,
        value: value ?? this.value);
  }
}

class AuthenticatedState extends AppAuthState {
  const AuthenticatedState();

  @override
  List<Object> get props => [];
}

class UnauthenticatedState extends AppAuthState {}

class AuthFailureState extends AppAuthState {
  final String errorMessage;
  const AuthFailureState(this.errorMessage);
  @override
  List<Object> get props => [errorMessage];
}

class NavigateToPasswordState extends AppAuthState {}

class NavigateToDetailState extends AppAuthState {}

class NavigateToSocialDetailState extends AppAuthState {}

class AuthDateSelectedState extends AppAuthState {
  final DateTime selectedDate;
  AuthDateSelectedState(this.selectedDate);
}



Also the validate_service.dart just incase:

import 'package:flutter/material.dart';

import '../bloc/auth/auth_state.dart';

class ValidateService {
  FieldState validateEmail(String email) {
    final regex = RegExp(r'^[^@]+@[^@]+.[^@]+');
    bool isValid = regex.hasMatch(email);
    print(isValid);
    String? errorMessage = isValid ? null : 'Invalid email address';
    print(errorMessage);
    return FieldState(
      isValid: isValid,
      value: email,
      errorMessage: errorMessage,
      borderColor: isValid ? Colors.black : Colors.red,
    );
  }

  FieldState validatePassword(String password) {
    if (password.isEmpty) {
      return FieldState(
        isValid: false,
        errorMessage: 'Password is required',
        borderColor: Colors.red,
      );
    }

    if (password.length < 8) {
      return FieldState(
        isValid: false,
        errorMessage: 'Password must be at least 8 characters long',
        borderColor: Colors.red,
      );
    }
    final RegExp passwordRegExp =
        RegExp(r'^(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$');
    if (!passwordRegExp.hasMatch(password)) {
      return FieldState(
        isValid: false,
        errorMessage:
            'Password must contain at least one uppercase letter, one number, and one special character',
        borderColor: Colors.red,
      );
    }
    return FieldState(
      isValid: true,
      errorMessage: '',
      borderColor: Colors.green,
    );
  }

  FieldState validateName(String name) {
    bool isValid = name.length < 3;
    String errorMessage = isValid ? '' : 'Name must be atleast 3 letters';
    return FieldState(
      isValid: isValid,
      errorMessage: errorMessage,
      borderColor: isValid ? Colors.black : Colors.red,
    );
  }
}

i apologise for the long code.
This is my first uestion on stack overflow.
I have re written the code so many times but still doesnt work.

New contributor

Great Daddy Dragon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật