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: HotReloadDemo(),
);
}
}
class HotReloadDemo extends StatefulWidget {
const HotReloadDemo({super.key});
@override
State<HotReloadDemo> createState() => _HotReloadDemoState();
}
class _HotReloadDemoState extends State<HotReloadDemo> {
String displayText = 'Hello World';
Color boxColor = Colors.blue;
void changeText() {
setState(() {
displayText = 'Hello Flutter!';
});
}
void changeColor() {
setState(() {
boxColor = Colors.green;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Hot Reload Demo')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(displayText, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 20),
Container(
width: 100,
height: 100,
color: boxColor,
),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: changeText,
child: const Text('Change Text'),
),
ElevatedButton(
onPressed: changeColor,
child: const Text('Change Color'),
),
],
),
],
),
),
);
}
}
This Flutter app shows a text and a colored box. Two buttons let you change the text and the color.
When you tap 'Change Text', the text changes from 'Hello World' to 'Hello Flutter!'. When you tap 'Change Color', the box color changes from blue to green.
Using hot reload after changing the code updates the UI instantly without losing the current state (like the changed text or color). Using hot restart resets the app to its initial state, so the text and color go back to 'Hello World' and blue.
This helps you see code changes quickly and understand how state works in Flutter.