diff --git a/lib/src/lifecycle_module.dart b/lib/src/lifecycle_module.dart index 217e7c9..b37e0e0 100644 --- a/lib/src/lifecycle_module.dart +++ b/lib/src/lifecycle_module.dart @@ -1124,12 +1124,20 @@ abstract class LifecycleModule extends SimpleModule with Disposable { _activeSpan = _startTransitionSpan('unload'); _willUnloadController.add(this); - await Future.wait(_childModules.toList().map((child) { - child.parentContext = _activeSpan?.context; - return child.unload().whenComplete(() { - child.parentContext = null; - }); - })); + + // We're looping here because it's possible for additional child modules to be added to this list while we are + // unloading the current items. While loadChildModule is guarded from adding new modules after unload starts, + // it contains asynchronous elements that allow a module to be added to this list during the unload. + // Note that items get removed from this list by an event handler listening to their didDispose stream. + while (_childModules.isNotEmpty) { + await Future.wait(_childModules.toList().map((child) { + child.parentContext = _activeSpan?.context; + return child.unload().whenComplete(() { + child.parentContext = null; + }); + })); + } + try { await onUnload(); } catch (error, stackTrace) {