5

What is a zero-argument constructor in Dart flutter?

while creating a bloc in flutter I am receiving the following error

  The superclass 'Bloc<QuoteEvent, QuoteState>' doesn't have a zero argument constructor.
Try declaring a zero argument constructor in 'Bloc<QuoteEvent, QuoteState>', or explicitly invoking a different constructor in 'Bloc<QuoteEvent, QuoteState>'.

kindly guide how to fix it. thanks

below is code

import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';

import 'package:random_quote/repositories/repositories.dart';
import 'package:random_quote/models/models.dart';
import 'package:random_quote/bloc/bloc.dart';

class QuoteBloc extends Bloc<QuoteEvent, QuoteState> {
  final QuoteRepository repository;

  QuoteBloc({@required this.repository}) : assert(repository != null);

  @override
  QuoteState get initialState => QuoteEmpty();

  @override
  Stream<QuoteState> mapEventToState(QuoteEvent event) async* {
    if (event is FetchQuote) {
      yield QuoteLoading();
      try {
        final Quote quote = await repository.fetchQuote();
        yield QuoteLoaded(quote: quote);
      } catch (_) {
        yield QuoteError();
      }
    }
  }
}
Javeed Ishaq
  • 6,024
  • 6
  • 41
  • 60

3 Answers3

6

initialState property was removed from flutter_bloc since v5.0.0. Here is migration guide.

You should use super() constructor instead:

class QuoteBloc extends Bloc<QuoteEvent, QuoteState> {
  final QuoteRepository repository;

  QuoteBloc({@required this.repository}) : 
    assert(this.repository != null),
    super(QuoteEmpty());

  ...
Mol0ko
  • 2,938
  • 1
  • 18
  • 45
3

A zero-argument constructor is literally a constructor that can be invoked with zero arguments. This includes constructors that take only optional arguments.

If you have a derived class that does not explicitly invoke its base class constructor, the derived class's constructors will implicitly invoke the default (unnamed) constructor in the base class with zero arguments. If you need to call a named constructor in the base class or if you need to pass arguments, you will need to invoke the base class constructor explicitly.

In your case, QuoteBloc derives from Bloc<QuoteEvent, QuoteState>, but the QuoteBloc constructor does not explicitly invoke any constructor from Bloc, which apparently does not provide a default, zero-argument constructor.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0
SomeClass();//this is zero argument constructor
SomeClass2(String argument1);//this is one argument constructor
SomeClass3(String argument1,String argument2);//this is 2 argument constructor
Yadu
  • 2,979
  • 2
  • 12
  • 27