Search code examples
flutterdartbloc

Why state is not updating in cubits?


I am new at flutter ant trying to use bloc/cubit

I have a state inside cubit file and when I try to emit state... state is not changing and I don't understand why

This is my cubit file:

//auth_cubit.dart

import 'package:flutter_bloc/flutter_bloc.dart';

part of 'auth_state.dart'; // here ide returns an error: The part-of directive must be the only directive in a part.

class AuthCubit extends Cubit<AuthState> { // The name 'AuthState' isn't a type so it can't be used as a type argument.
  AuthCubit() : super(AuthState(
    email: "Log in",
    password: null,
    firstName: "",
    lastName: "",
    genderId: 0,
    ageGroupId: 0,
    countryUuid: 0
  ));

  void setCountryUuid(int countryUuid) => emit(AuthState(countryUuid: countryUuid));

}

//auth_state.dart

part of 'auth_cubit.dart';

class AuthState {
  final email;
  final password;
  final firstName;
  final lastName;
  final genderId;
  final ageGroupId;
  final countryUuid;

  const AuthState({
    this.email, //string
    this.password, //string
    this.firstName, //string
    this.lastName, //string
    this.genderId, //int
    this.ageGroupId, //int
    this.countryUuid //int
  });
}

Why does state cannot connect to cubit?


Solution

  • There is error to fix first, see above on the part part (ahah):

    import 'package:flutter_bloc/flutter_bloc.dart';
    
    part 'auth_state.dart'; // Just use part in the cubit
    
    class AuthCubit extends Cubit<AuthState> { // This error should be gone
      AuthCubit() : super(AuthState(
        email: "Log in",
        password: null,
        firstName: "",
        lastName: "",
        genderId: 0,
        ageGroupId: 0,
        countryUuid: 0
      ));
    
      void setCountryUuid(int countryUuid) => emit(AuthState(countryUuid: countryUuid));
    
    }
    

    After that, your cubit should be able to emit new state.