build() 메서드만 사용import 'package:flutter/material.dart';
class MyStatelessWidget extends StatelessWidget {
final String title;
const MyStatelessWidget({super.key, required this.title});
Widget build(BuildContext context) {
return Text(title);
}
}
StatefulWidget (껍데기)State (실제 상태 관리)setState()로 UI 갱신import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
int count =0;
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: [
Text("카운트:$count",style: Theme.of(context).textTheme.displaySmall),
ElevatedButton(
onPressed: (){
count++;
print(count);
},
child: Text("증가",style: Theme.of(context).textTheme.displaySmall)
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int count = 0;
void _increment() {
setState(() {
count++;
});
}
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: _increment,
child: const Text('증가'),
)
],
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int count = 0;
void _increment() {
setState(() {
count++;
});
}
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: _increment,
child: const Text('증가'),
)
],
);
}
}
| 구분 | StatelessWidget | StatefulWidget |
|---|---|---|
| 상태 관리 | ❌ 없음 | ✅ 있음 |
| UI 변경 | ❌ 불가능 | ✅ 가능 |
| 성능 | ✅ 더 빠름 | ❌ 상대적으로 무거움 |
| 구조 | 단순 | 복잡 (State 클래스 필요) |
| 사용 용도 | 정적인 화면 | 동적인 화면 |
setState(() {
// 상태 변경
});
build() 다시 실행됨👉 Stateless = 고정 UI / Stateful = 변화하는 UI
실무에서는:
StatelessWidgetStatefulWidget👉 이렇게 최소 범위로 상태 관리하는 것이 성능에 좋음