All posts

Fix Infinite Loop in Flutter

Resolve infinite loop issues in Flutter apps caused by setState in build methods, recursive widget rebuilds, and stream listener loops.

Why Flutter Apps Get Stuck in Infinite Loops

Flutter's reactive rebuild system means calling setState at the wrong time can trigger an endless cycle of builds. Your app freezes, the UI becomes unresponsive, and you might see a "setState() called during build" warning in the console.

The Most Common Cause

Calling setState (or modifying a ChangeNotifier) inside the build method:

// BAD — triggers infinite rebuild
@override
Widget build(BuildContext context) {
  setState(() {
    counter++;
  });
  return Text('$counter');
}

The Fix

Move state mutations to event handlers or lifecycle methods:

@override
void initState() {
  super.initState();
  counter = 0;
}

void _increment() {
  setState(() {
    counter++;
  });
}

@override
Widget build(BuildContext context) {
  return ElevatedButton(
    onPressed: _increment,
    child: Text('$counter'),
  );
}

Another Trap: StreamBuilder Without Proper Keys

A StreamBuilder placed inside a widget that recreates its stream on every build also causes infinite loops:

// BAD — new stream on every build
StreamBuilder(stream: FirebaseFirestore.instance.collection('items').snapshots(), ...)

// GOOD — create stream once in initState
late final Stream _itemStream;
@override
void initState() {
  super.initState();
  _itemStream = FirebaseFirestore.instance.collection('items').snapshots();
}

With Bugsly's Flutter SDK, these kinds of runaway rebuilds surface as performance anomalies, helping you spot the offending widget before users file complaints.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free