felangel / bloc

A predictable state management library that helps implement the BLoC design pattern

Home Page:https://bloclibrary.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

setState and emit doesn't work well together. Discovered non-stop/infinite when setState is called.

maxlam79 opened this issue · comments

Hi,

I have encountered an issue with BlocBuilder build function keep being triggered infinitely when with setState being used.

I usually don't call setState when using Bloc. But can't stop other external dependant widgets from having setState called.

Here is a flutter project to re-produce this issue:
https://github.com/maxlam79/flutter_bloc_nonstop_investigate.

Any help is appreciated. Thank you.

For me, it seems that the infinite loop you have created is not related to bloc. Once emit is called, your code is equivalent to the following code:

class _MyHomePageState extends State<MyHomePage> {
  /// Flags & Attributes
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    _incrementCounter();
    return Scaffold(
      body: Text('$_counter'),
    );
  }

  void _incrementCounter() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        _counter++;
      });
    });
  }
}

The _incrementCounter method will get triggered on each execution of the build method, and the build method will get called every time setState is called. So calling _incrementCounter causes an infinite loop.

Thanks for pointing this out Jannik. I guess I would just have find a better way to maneuver both the Bloc characteristic and the setState/build life cycle characteristic.