Flutter: can I use setState() with a BLoC architecture?
Asked Answered
S

1

11

My understanding of state management is that calling setState() alone opens up a variety of messy issues, code files become huge and difficult to debug, and it prevents holding a sensible structure to a project. In cases where the widget's appearance changes slightly, it makes little sense to have a complex architecture like BLoC or ScopedModel just to show/hide a widget (for example). However, the way I have understood it is that you can't mix setState() and an architecture together, otherwise what's the point of the architecture?

Let's use BLoC for this question (simply because I happen to be using it), specifically this package. Let's say I have this super simple example code:

class MyWidget extends StatefulWidget {
  @override
  void createState() {
    return _MyWidgetState();
  }
}

class _MyWidgetState extends State<MyWidget>() {
  bool _isShowing = false;
  MyBloc bloc;

  @override
  void initState() {
    super.init();
    bloc = MyBloc();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
      bloc: bloc,
      builder: (context, state) {
        return Column(
          children: <Widget>[
            Text(state.myText),
            if (_isShowing)
              Text("Button has been pressed!"),
            RaisedButton(
              child: Text("Show label"),
              onTap: () => setState(() => _isShowing = true),
            ),
            RaisedButton(
              child: Text("Run event"),
              onTap: () => bloc.add(NewEvent()),
            ),
          ],
        );
      },
    );
  }
}

In the crude example above, is it right/acceptable to mix the BLoC pattern with setState()? Why would I not use BLoC to handle showing the Text widget? Where do I draw the line? What are the pros/cons? Is there a performance difference?

Note: I'm not looking for "just merge the two Text widgets together" answers. I'm looking for purely architectural perspectives.

Seleta answered 18/12, 2019 at 12:46 Comment(1)
AFAIK: BLoC is architecture to separate business logic from the UI part. You can combine setState with the bloc if needed anytime.Namara
S
35

You can.

Architecture like scoped_model/bloc/etc aren't about removing calls to setState. They are about separating concerns and simplifying the implementation

You can and should use setState when it makes sense to use it, such as with animations.

To begin with, even these architectures use setState. You just don't see it, but it's there

Stickle answered 18/12, 2019 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.