The superclass 'Bloc<xxx, xxx>' doesn't have a zero argument constructor in dart

Issue

I am a beginner in Dart language development. I try to create a sample flutter application BLOC pattern inspired by this GitHub repo, but I got some error message related to the class inheritance. I am already familiar with the inheritance and superclass and subclass programming in the dot net C# language. But in the case of the dart, I need some advice.

Here is my code:

class UserRegBloc extends Bloc<UserRegEvent, UserRegState> {
  UserRepository userRepository;

   UserRegBloc({@required UserRepository userRepository}) {
   userRepository = UserRepository();
}

@override
UserRegState get initialState => UserRegInitial();

 @override
 Stream<UserRegState> mapEventToState(UserRegEvent event) async* {
   if (event is SignUpButtonPressed) {
     yield UserRegLoading();
       try {
      var user = await userRepository.signUpUserWithEmailPass(
        event.email, event.password);
    print("BLOC : ${user.email}");
    yield UserRegSuccessful(user: user);
  } catch (e) {
    yield UserRegFailure(message: e.toString());
    }
  }
 }
}

enter image description here

Edit

My pubspec.yaml dependencies are below:

enter image description here

Solution

It looks like you need to provide an initial state to the bloc. Something like this:

class UserRegBloc extends Bloc<UserRegEvent, UserRegState> {
  UserRepository userRepository;

   UserRegBloc({@required UserRepository userRepository}) : super(UserRegInitialState()) {
       userRepository = UserRepository();
   }
   // ...
}

where UserRegInitialState is a subclass of UserRegState.

This is the difference due to different versions of the bloc library. Your link project uses flutter_bloc version 3.0 and the version of the same package in your question is 6.1.1. So there is a small difference in code. The error, basically, tells that the base class of UserRegBloc requires one parameter. So you couldn’t declare a subclass without providing that parameter, thus the error.

Answered By – ChessMax

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *