initializeHotReload method
Future<void>
initializeHotReload({
- Duration debounceInterval = const Duration(milliseconds: 500),
Implementation
Future<void> initializeHotReload({
Duration debounceInterval = const Duration(milliseconds: 500),
}) async {
if (_reloader != null) return;
if (!_enableHotReload) return;
onHotReloadStatus(HotReloadStatus.initializing);
try {
try {
final info = await dev.Service.getInfo();
if (info.serverUri == null) {
const message = 'VM service URI not available. Hot reload disabled.';
dev.log(message, name: 'HotReload');
onHotReloadStatus(HotReloadStatus.unavailable, detail: message);
return;
}
if (info.serverWebSocketUri != null) {
dev.log(
'DevTools URL: ${info.serverUri}devtools/?uri=${info.serverWebSocketUri}',
name: 'HotReload',
);
}
} catch (e) {
final message = 'Could not retrieve VM service URL: $e';
dev.log(message, name: 'HotReload');
onHotReloadStatus(HotReloadStatus.unavailable, detail: message);
return;
}
final projectRoot = _findProjectRoot();
if (projectRoot == null) {
const message =
'Could not find pubspec.yaml in any ancestor directory. '
'Hot reload disabled.';
dev.log(message, name: 'HotReload');
onHotReloadStatus(HotReloadStatus.unavailable, detail: message);
return;
}
final originalDir = io.Directory.current;
final needsChdir = originalDir.path != projectRoot.path;
if (needsChdir) {
dev.log(
'Changing CWD from ${originalDir.path} to ${projectRoot.path} '
'for HotReloader',
name: 'HotReload',
);
io.Directory.current = projectRoot;
}
try {
_reloader = await HotReloader.create(
automaticReload: true,
debounceInterval: debounceInterval,
onBeforeReload: (ctx) {
if (ctx.event case final event?) {
final message = 'Change detected: ${event.path}';
dev.log(message, name: 'HotReload');
onHotReloadStatus(
HotReloadStatus.changeDetected,
detail: event.path,
);
}
return true;
},
onAfterReload: (ctx) {
switch (ctx.result) {
case HotReloadResult.Failed:
const message = 'Compilation error during hot reload';
dev.log(message, name: 'HotReload', level: 1000);
onHotReloadStatus(HotReloadStatus.failed, detail: message);
case HotReloadResult.Succeeded:
_performReassembleAfterReload();
case HotReloadResult.PartiallySucceeded:
const message = 'Hot reload partially succeeded';
dev.log(message, name: 'HotReload', level: 900);
onHotReloadStatus(HotReloadStatus.failed, detail: message);
case HotReloadResult.Skipped:
dev.log('Hot reload skipped', name: 'HotReload');
}
},
);
} finally {
if (needsChdir) {
io.Directory.current = originalDir;
}
}
dev.log(
'Hot reload active – watching for file changes',
name: 'HotReload',
);
onHotReloadStatus(HotReloadStatus.ready);
} catch (e, stack) {
final message = 'Failed to initialize hot reload: $e';
dev.log(message, name: 'HotReload', level: 1000, stackTrace: stack);
onHotReloadStatus(HotReloadStatus.failed, detail: message);
}
}