大家好,今天我们来学习一下服务器如何热重载,关于热重载这个特性,只要是运行在DartVM下都可以实现热重载,嗯嗯,这样说,大家应该能明白Flutter为什么能够热重载了吧,Flutter实际也是运行在一个DartVM的环境之下,下次我会介绍快照,好了,我们来开始学习服务器热重载吧!
热重载其实就是将一个文件加入到监听中,如果有改变,就会对程序进行更新,我们可以集成jaguar_hotreload这个包,添加之后,就可以实现无需重启服务器进行更新了
pub get
命令
image.png
debounceInterval
用于更新间隔,如果在间隔内更新,会等待下一次才更新,默认为1秒vmServiceUrl
指定一个vm service的地址addPackageDependencies()
监听.packages
里面的所有文件addGlob()
使用正则监听addFile ()
添加单个文件监听addPackagePath
添加包路径监听addUri()
使用uri添加监听addPath()
添加监听路径(运行的.dart
文件为跟目录)go()
执行监听reloader.onReload
进行手动触发监听--enable-vm-service
或者 --observe
进行启用,例如:dart --observe main.dart
,所以:实现热重载需要启用DartVM服务 这一句比较重点,先记下
热重载的部分代码:
/// Reloads the application Future<void> reload() async { print('Reloading the application...'); // Get vm service _client ??= await vmServiceConnectUri(vmServiceUrl); // Find main isolate id to reload it final vm = await _client.getVM(); final ref = vm.isolates.first; // Reload final rep = await _client.reloadSources(ref.id); if (!rep.success) throw Exception('Reloading failed! Reason: $rep'); _onReload.add(DateTime.now()); }
添加如下代码:
main() => runService();
runService() async {
final reloader = HotReloader(debounceInterval: const Duration(seconds: 10));
reloader.addPath('.');//添加当前项目进行监听
await reloader.go();
Jaguar()
..get('/', (Context ctx) => 'Hello World')
..log.onRecord.listen(print)
..serve(logRequests: true);
}
然后我们使用命令行启用服务器
dart --enable-vm-service bin/main.dart
image.png
然后,我们请求以下服务器
image.png
我们来改一下代码看看,将Hello World
改为 'Hello Rhyme'
main() => runService();
runService() async {
final reloader = HotReloader(debounceInterval: const Duration(seconds: 10));
reloader.addPath('.');
await reloader.go();
Jaguar()
//edit
..get('/', (Context ctx) => 'Hello Rhyme')
//edit
..log.onRecord.listen(print)
..serve(logRequests: true);
}
可以看到,控制台输出了Reloading the application...
image.png
然后刷新一下页面
image.png
emmm...出现bug了我们来看看dart-lang
的sdk里面的一个wiki,大家应该明白。
image.png
在DartVM热重载中,只会改变程序的行为,而不能改变程序的状态,所以我们在定义Jaguar的时候,已经把(Context ctx) => 'Hello World'
这个状态定义到堆栈中,再次热重载的时候,并不会发生改变,我们再修改一下程序看看
main() => runService();
runService() async {
final reloader = HotReloader(debounceInterval: const Duration(seconds: 10));
reloader.addPath('.');
await reloader.go();
Jaguar()
//edit
..get('/', (Context ctx) => sayhello())
//edit
..log.onRecord.listen(print)
..serve(logRequests: true);
}
//new
sayhello() => 'Hello World';
//new
我们在这里将字符串搬到一个方法里面,这样,堆栈只记录这个方法,当热重载的时候,方法再次被搜索的时候,返回的字符串变了,就能实现热重载 我们重新运行看看
dart --enable-vm-service bin/main.dart
image.png
然后,我们请求以下服务器
image.png
我们来改一下这个方法的返回看看
image.png
可以看到,我们成功的实现了热重载。。