簡體   English   中英

什么是零參數構造函數 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();
      }
    }
  }
}

v5.0.0 開始,從 flutter_bloc中刪除了initialState屬性。 這是遷移指南

您應該改用 super() 構造函數:

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

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

  ...

零參數構造函數實際上是一個可以用零 arguments 調用的構造函數。這包括僅采用可選 arguments 的構造函數。

如果派生類 class 未顯式調用其基類 class 構造函數,則派生類的構造函數將隱式調用基類 class 中的默認(未命名)構造函數,其中值為零 arguments。如果您需要調用基類 class 中的命名構造函數或如果需要傳遞 arguments,則需要顯式調用基 class 構造函數。

在您的情況下, QuoteBloc派生自Bloc<QuoteEvent, QuoteState> ,但QuoteBloc構造函數沒有顯式調用Bloc的任何構造函數,這顯然不提供默認的零參數構造函數。

SomeClass();//this is zero argument constructor
SomeClass2(String argument1);//this is one argument constructor
SomeClass3(String argument1,String argument2);//this is 2 argument constructor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM