0

I'm trying to pass parameters to a bloc event following the bloc pattern for set the default counter. I have found this question before, but that is doesn't work.

Flutter BLoc pass parameters

Flutter BLoC - How to pass parameter to event?

main.dart

BlocProvider(
  create: (_) => CounterBloc(),
  child: Counter(total: totalItem)
)

counter_bloc.dart

import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';


enum CounterStatus { decrement, increment }


class CounterEvent {
  final int value;
  final CounterStatus status;

  CounterEvent({@required this.value, @required this.status});
}

class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(1);
  
  @override
  Stream<int> mapEventToState(event) async* {
    if(event.status == CounterStatus.decrement) {
      yield state + event.value - 1;
    } else if(event.status == CounterStatus.increment) {
      yield state + event.value + 1;
    }
  }
}

i want to pass parameter to BLoc event like

FlatButton(
  onPressed: () => context.bloc<CounterBloc>().add(CounterEvent(value = widget.total, status = CounterStatus.decrement)),
  color: Colors.white,
  child: Text("-", style: TextStyle(fontSize: 16), textAlign: TextAlign.center,)
),
FlatButton(
  onPressed: () => context.bloc<CounterBloc>().add(CounterEvent(value = widget.total, status = CounterStatus.increment)),
  color: Colors.white,
  child: Text("+", style: TextStyle(fontSize: 16), textAlign: TextAlign.center,)
),

it's still doesn't work

  • What error do you get ? First think I have noticed is that you use `=` to specify the optional parameters values of the event instead of `:`. Replace `=` with `:` like this `context.bloc().add(CounterEvent(value: widget.total, status: CounterStatus.decrement))` – jorjdaniel Nov 09 '20 at 18:54

0 Answers0