Flutter 热加载和热重启的区别
2023-12-04 本文已影响0人
小冰山口
随便写了个demo, 修改widget的颜色, 开启hot reload 发现并没有什么改变. 只有hot restart才有反应
import 'package:flutter/material.dart';
void main() {
runApp(build());
}
Widget build() {
return MaterialApp(
home: Scaffold(
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(100, 100)),
child: Container(
color: Colors.yellow,
width: 30,
height: 30,
),
),
),
));
}
跟记忆中的好像有点不太一样
那热加载(hot reload)和热重启(hot restart)有什么区别呢?
·Hot reload loads code changes into the VM and re-builds the widget tree, preserving the app state; it doesn't rerun main( ) or initState().(command\ in Intellij and Android Studio,^F5 in VSCode)
·Hot restart loads code changes into the VM, and restarts the Flutter app, losing the app state. (↑command\ in IntelliJ and Android Studio,↑commandF5 in VSCode)
热加载(hot reload)加载代码修改到虚拟机, 重新build了widget树, 保留了app状态, 它不会重走main方法和initState方法(但会走build方法)
热重启(hot restart)加载代码修改到虚拟机, 重启了Flutter app, 丢失了app状态, 它会重走main方法
那么回到我上面的demo, 我这个widget是在main里面加载的, 但是hot reload并不会重走main, 所以改变是不会生效的. 但当你的改变在build方法里时, 就可以生效