musa sahin
musa sahin

Reputation: 101

calling setState in flutter Bloc listener

I am calling setState in flutter BlocListener. is there any problem doing this?

....
return BlocListener<XBloc, XState>(
      listener: (context, state) {
        if (state is XLoadedState) {
          setState(() {
            name = state.name;
          });
        }....
....

Upvotes: 2

Views: 2747

Answers (1)

magicleon94
magicleon94

Reputation: 5172

It's not a problem but it's kinda useless and anti pattern. And using setState you are forcing everything to rebuild even if it's not necessary.

You could just wrap the widget that uses name into a BlocBuilder<XBloc,XState>, for example like this:

BlocBuilder<XBloc,XState>(
  builder: (context, state){
    if (state is XLoadedState){
      return Text(state.name);
    }else{
      //return something for when state.name is null, I guess
    }
  }
)

You can check more about this here

Upvotes: 0

Related Questions