什么是 Dart flutter 中的零参数构造函数

What is a zero argument constructor in Dart flutter

什么是 Dart flutter 中的零参数构造函数?

在 flutter 中创建 bloc 时收到以下错误

  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>'.

请指导如何修复它。谢谢

下面是代码

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();
      }
    }
  }
}
SomeClass();//this is zero argument constructor
SomeClass2(String argument1);//this is one argument constructor
SomeClass3(String argument1,String argument2);//this is 2 argument constructor

initialState 属性 已从 flutter_bloc since v5.0.0. Here is migration guide 中删除。

您应该改用 super() 构造函数:

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

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

  ...

零参数构造函数字面意思是可以用零参数调用的构造函数。这包括仅采用可选参数的构造函数。

如果您的派生 class 没有 显式 调用其基础 class 构造函数,则派生 class 的构造函数将隐式 使用零参数调用基础 class 中的默认(未命名)构造函数。如果您需要在基础 class 中调用命名构造函数,或者如果您需要传递参数,则需要显式调用基础 class 构造函数。

在你的例子中,QuoteBloc 派生自 Bloc<QuoteEvent, QuoteState>,但 QuoteBloc 构造函数没有显式调用 Bloc 的任何构造函数,这显然不提供默认值, 零参数构造函数。