Bloc: Unable to change the state

Created on 5 May 2019  路  2Comments  路  Source: felangel/bloc

Hi thanks for this awesome framework,
however I am updating your basic counter example to the class based state. and facing some error, while throwing new state, the currentstate is always taken as my initialstate, thus I am unable to do any operation on it, can you please help me out?

//My State Class

import `'package:equatable/equatable.dart';`
import 'package:meta/meta.dart';

abstract class CounterState extends Equatable {
  CounterState([List props = const []]) : super(props);
}

class CounterInitial extends CounterState {
  @override
  String toString() => '0';
}

class CounterValue extends CounterState {
  int counterValue;

  CounterValue({@required this.counterValue})
      : assert(counterValue != null),
        super([counterValue]);

  @override
  String toString() =>'$counterValue';
}

// My Bloc


import 'package:bloc/bloc.dart';
import 'package:bloc_form_demo/blocs/counter/counter_event.dart';
import 'package:bloc_form_demo/blocs/counter/counter_state.dart';

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  @override
  CounterState get initialState => CounterInitial();

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    if (event is Increment) {
       yield CounterValue(
          counterValue: (currentState as CounterValue).counterValue + 1); //HERE I AM GETTING ERROR THAT CURRENTSTATE  IS OF TYPE COUNTERINTITAL



  } else if (event is Decrement) {
      yield CounterValue(
          counterValue: (currentState as CounterValue).counterValue - 1);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }
}

//Error Console

I/flutter (19708): EVENT: Counter Increment 
I/flutter (19708): MAPEVENT : event is EVENT: Counter Increment  | state is 0
I/flutter (19708): MAPEVENT 2: EVENT: Counter Increment  is Decrement && 0 is CounterValue
I/flutter (19708): MAPEVENT 1:INSIDE 1
I/flutter (19708): type 'CounterInitial' is not a subtype of type 'CounterValue' in type cast


question

Most helpful comment

thanks a ton for your help, and quick reply

All 2 comments

Hi @satodia-smit 馃憢
Thanks for opening an issue!

Regarding your question, I would think of the counter example as having a single state (CounterState) which has a property value.

I have put together a gist of how I would refactor the counter_bloc to use classes.

Hope that helps 馃憤

thanks a ton for your help, and quick reply

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tigranhov picture tigranhov  路  3Comments

abinvp picture abinvp  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

wheel1992 picture wheel1992  路  3Comments

nhwilly picture nhwilly  路  3Comments