Repository: flutter
Issue: Stack overflow on hot reload with thousands-deep widget tree
Labels: c: crash,tool,framework,t: hot reload,a: error message,has reproducible steps,P2,found in release: 3.10,found in release: 3.12,team-framework,triaged-framework

### Is there an existing issue for this?

- [X] I have searched the [existing issues](https://github.com/flutter/flutter/issues)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### Steps to reproduce

We found an issue when hot reloading our app, only on iOS. It's a real app we're are developing, it's not just an example. This app builds a lot of widgets and we found what causing this issue is the number of widgets in the tree.

The solution provided by #85026 (using a `LayoutBuilder`) does not work in this case.

### Expected results

We should not have an error while hot reloading our app just because we have a lot of widgets in the tree.

This issue is also happening on Android with a real device but with a much higher number of widgets (4600+ widgets)

### Actual results

<details><summary>We have this error popping in the console</summary>

```console
Reassembling main.dart$main-1313196637183679 failed: ext.flutter.reassemble: (-32000) Server error
{"exception":"Stack Overflow","stack":"#0      Element.dirty (package:flutter/src/widgets/framework.dart:4587:3)\n#1      BuildOwner.scheduleBuildFor.<anonymous closure> (package:flutter/src/widgets/framework.dart:2528:20)\n#2      BuildOwner.scheduleBuildFor (package:flutter/src/widgets/framework.dart:2544:6)\n#3      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4651:12)\n#4      Element.reassemble (package:flutter/src/widgets/framework.dart:3403:7)\n#5      Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6      ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#7      Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#8      StatefulElement.reassemble (package:flutter/src/widgets/framework.dart:5095:11)\n#9      Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#10     _LayoutBuilderElement.visitChildren (package:flutter/src/widgets/layout_builder.dart:67:14)\n#11     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#12     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#13     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#14     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#15     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#16     SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6363:14)\n#17     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#18     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#19     _LayoutBuilderElement.visitChildren (package:flutter/src/widgets/layout_builder.dart:67:14)\n#20     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#21     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#22     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#23     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#24     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#25     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#26     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#27     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#28     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#29     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#30     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#31     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#32     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#33     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#34     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#35     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#36     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#37     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#38     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#39     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#40     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#41     Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#42     Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#43     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n...\n...\n#6120   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6121   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6122   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6123   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6124   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6125   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6126   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6127   StatefulElement.reassemble (package:flutter/src/widgets/framework.dart:5095:11)\n#6128   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6129   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6130   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6131   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6132   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6133   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6134   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6135   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6136   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6137   StatefulElement.reassemble (package:flutter/src/widgets/framework.dart:5095:11)\n#6138   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6139   ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5020:14)\n#6140   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6141   Element.reassemble.<anonymous closure> (package:flutter/src/widgets/framework.dart:3408:13)\n#6142   RenderObjectToWidgetElement.visitChildren (package:flutter/src/widgets/binding.dart:1130:14)\n#6143   Element.reassemble (package:flutter/src/widgets/framework.dart:3406:5)\n#6144   BuildOwner.reassemble (package:flutter/src/widgets/framework.dart:3135:12)\n#6145   WidgetsBinding.performReassemble (package:flutter/src/widgets/binding.dart:946:19)\n#6146   BindingBase.lockEvents (package:flutter/src/foundation/binding.dart:558:41)\n#6147   BindingBase.reassembleApplication (package:flutter/src/foundation/binding.dart:598:12)\n#6148   BindingBase.registerSignalServiceExtension.<anonymous closure> (package:flutter/src/foundation/binding.dart:635:23)\n#6149   BindingBase.registerServiceExtension.<anonymous closure> (package:flutter/src/foundation/binding.dart:856:32)\n#6150   _RootZone.runUnary (dart:async/zone.dart:1660:54)\n#6151   _FutureListener.handleValue (dart:async/future_impl.dart:147:18)\n#6152   Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:767:45)\n#6153   Future._propagateToListeners (dart:async/future_impl.dart:796:13)\n#6154   Future._complete (dart:async/future_impl.dart:558:7)\n#6155   new Future.delayed.<anonymous closure> (dart:async/future.dart:421:16)\n#6156   Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)\n#6157   _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)\n#6158   _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)\n#6159   _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)\n","method":"ext.flutter.reassemble"}

════════ Exception caught by Flutter framework ═════════════════════════════════
The following StackOverflowError was thrown during a service extension callback for "ext.flutter.reassemble":
Stack Overflow

When the exception was thrown, this was the stack
#0      Element.dirty
#1      BuildOwner.scheduleBuildFor.<anonymous closure>
#2      BuildOwner.scheduleBuildFor
#3      Element.markNeedsBuild
#4      Element.reassemble
#5      Element.reassemble.<anonymous closure>
#6      ComponentElement.visitChildren
#7      Element.reassemble
#8      StatefulElement.reassemble
#9      Element.reassemble.<anonymous closure>
#10     _LayoutBuilderElement.visitChildren
#11     Element.reassemble
#12     Element.reassemble.<anonymous closure>
#13     ComponentElement.visitChildren
#14     Element.reassemble
#15     Element.reassemble.<anonymous closure>
#16     SingleChildRenderObjectElement.visitChildren
#17     Element.reassemble
#18     Element.reassemble.<anonymous closure>
#19     _LayoutBuilderElement.visitChildren
#20     Element.reassemble
#21     Element.reassemble.<anonymous closure>
#22     ComponentElement.visitChildren
#23     Element.reassemble
#24     Element.reassemble.<anonymous closure>
#25     ComponentElement.visitChildren
#26     Element.reassemble
#27     Element.reassemble.<anonymous closure>
#28     ComponentElement.visitChildren
#29     Element.reassemble
#30     Element.reassemble.<anonymous closure>
#31     ComponentElement.visitChildren
#32     Element.reassemble
#33     Element.reassemble.<anonymous closure>
#34     ComponentElement.visitChildren
#35     Element.reassemble
#36     Element.reassemble.<anonymous closure>
#37     ComponentElement.visitChildren
#38     Element.reassemble
#39     Element.reassemble.<anonymous closure>
#40     ComponentElement.visitChildren
#41     Element.reassemble
#42     Element.reassemble.<anonymous closure>
#43     ComponentElement.visitChildren
...
...
#6120   Element.reassemble
#6121   Element.reassemble.<anonymous closure>
#6122   ComponentElement.visitChildren
#6123   Element.reassemble
#6124   Element.reassemble.<anonymous closure>
#6125   ComponentElement.visitChildren
#6126   Element.reassemble
#6127   StatefulElement.reassemble
#6128   Element.reassemble.<anonymous closure>
#6129   ComponentElement.visitChildren
#6130   Element.reassemble
#6131   Element.reassemble.<anonymous closure>
#6132   ComponentElement.visitChildren
#6133   Element.reassemble
#6134   Element.reassemble.<anonymous closure>
#6135   ComponentElement.visitChildren
#6136   Element.reassemble
#6137   StatefulElement.reassemble
#6138   Element.reassemble.<anonymous closure>
#6139   ComponentElement.visitChildren
#6140   Element.reassemble
#6141   Element.reassemble.<anonymous closure>
#6142   RenderObjectToWidgetElement.visitChildren
#6143   Element.reassemble
#6144   BuildOwner.reassemble
#6145   WidgetsBinding.performReassemble
#6146   BindingBase.lockEvents
#6147   BindingBase.reassembleApplication
#6148   BindingBase.registerSignalServiceExtension.<anonymous closure>
#6149   BindingBase.registerServiceExtension.<anonymous closure>
#6159   _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)
(elided 9 frames from class _Timer, dart:async, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════
Application finished.
Exited
```

</details>

### Code sample

<details><summary>Code sample</summary>

```dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('StackOverflow HotReload')),
      body: const Provider(
        count: 1852, // Maybe higher on another computer/device
        child: Center(
          child: DepthTreeResetter(
            debugDepthTreeCount: true,
            child: SizedBox(),
          ),
        ),
      ),
    );
  }
}

class Provider extends StatelessWidget {
  const Provider({
    required this.count,
    required this.child,
    Key? key,
  }) : super(key: key);

  final int count;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    Widget wrappedChild = child;
    for (int i = 0; i < count; i++) {
      if (i % 100 == 0) {
        wrappedChild = DepthTreeResetter(child: wrappedChild);
      }
      wrappedChild = Container(child: wrappedChild);
    }

    return wrappedChild;
  }
}

class DepthTreeResetter extends StatelessWidget {
  const DepthTreeResetter({
    super.key,
    this.debugDepthTreeCount = false,
    required this.child,
  });

  final Widget child;
  final bool debugDepthTreeCount;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (_, __) {
        if (debugDepthTreeCount) {
          return _DepthTreeCounter(child: child);
        }
        return child;
      },
    );
  }
}

class _DepthTreeCounter extends StatefulWidget {
  const _DepthTreeCounter({
    required this.child,
  });

  final Widget child;

  @override
  _DepthTreeCounterState createState() => _DepthTreeCounterState();
}

class _DepthTreeCounterState extends State<_DepthTreeCounter> {
  @override
  void initState() {
    super.initState();
    int count = 0;
    context.visitAncestorElements((element) {
      count++;
      return true;
    });
    print('DEPTH TREE COUNT: $count');
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

```

</details>


### Screenshots or Video

<details>
<summary>Screenshots / Video demonstration</summary>

[Upload media here]

</details>


### Logs

<details><summary>Logs</summary>

```console
[Paste your logs here]
```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.7.12, on macOS 12.5.1 21G83 darwin-arm64, locale fr-FR)
    • Flutter version 3.7.12 on channel stable at /Users/xxxxxxx/dev/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 4d9e56e694 (9 weeks ago), 2023-04-17 21:47:46 -0400
    • Engine revision 1a65d409c7
    • Dart version 2.19.6
    • DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/xxxxxxx/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.0)
    • Xcode at /Applications/Xcode-14.0.0.app/Contents/Developer
    • Build 14A309
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.75.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.66.0

[✓] Connected device (4 available)
    • IN2023 (mobile)            • 87950fce                             • android-arm64  • Android 13 (API 33)
    • iPhone 13 Pro Max (mobile) • F7BD4E2B-91F5-47DA-9594-0D808C2C260C • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • macOS (desktop)            • macos                                • darwin-arm64   • macOS 12.5.1 21G83 darwin-arm64
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 114.0.5735.133

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
```

</details>