指定类时未指定 Flutter getter

syl*_*-lo 8 dart flutter

我越来越

[dart] The getter 'currentPickup' isn't defined for the class PickupEvent[undefined_getter]

error on event.currentPickup:

import 'dart:async';

import 'package:bloc/bloc.dart';

import 'pickup.dart';
import '../../../models/models.dart';

class PickupBloc extends Bloc<PickupEvent, PickupState> {

  @override
  Stream<PickupState> mapEventToState(PickupState state, PickupEvent event) async* {
    if (state.isNotRunning) {
      stopwatch.start();
      timer = new Timer.periodic(new Duration(milliseconds: 200), updateTime);
      yield PickupState.running();
    }

    if (state.isRunning) {
      stopwatch.stop();
      timer.cancel();

      _pushPickup(event.currentPickup);

      yield PickupState.done();
    }
  }
Run Code Online (Sandbox Code Playgroud)

When the getter is specified in the PickupEvent class and properly imported in pickup.dart.

import '../../../models/models.dart';

abstract class PickupEvent {}

class ButtonPressed extends PickupEvent {
  final PickupModel currentPickup;

  ButtonPressed({
    @required this.currentPickup
  });
}
Run Code Online (Sandbox Code Playgroud)

Any idea what could cause this ?

Gün*_*uer 14

The error message is correct. ButtonPressed has such a getter, but PickupEvent does not.

You can either add an abstract getter to the base class

abstract class PickupEvent {
  PickupModel get currentPickup;
}
Run Code Online (Sandbox Code Playgroud)

or cast like

_pushPickup((event as ButtonPressed).currentPickup);
Run Code Online (Sandbox Code Playgroud)

if you are sure it will be a ButtonPressed.

You can also do

if(event is ButtonPressed) {
  _pushPickup(event.currentPickup);
}
Run Code Online (Sandbox Code Playgroud)