Stateless 위젯과 Stateful 위젯 비교
동적인 UI를 구축할 때 StatelessWidget과 StatefulWidget을 언제 어떻게 사용하는지 배우며 두 위젯의 핵심적인 차이를 이해합니다.
Stateless 위젯과 Stateful 위젯 비교은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Widgets: The Building Blocks
Flutter UIs are built entirely from widgets. Think of them as LEGO bricks! Everything you see on screen – text, buttons, even layout containers — is a widget.
Widgets describe how your app's UI should look given its current configuration and state. There are two main types of widgets you'll encounter:
- StatelessWidget
- StatefulWidget
StatelessWidget: Static UI
A StatelessWidget is a widget that does not change its appearance or behavior over time. Once it's built, it stays the same.
- It doesn't have any internal "state" to manage.
- Its properties are immutable (cannot be changed after creation).
- It's perfect for displaying static content like text, icons, or images that don't need to react to user input or data changes.
Simple StatelessWidget
Here's a basic StatelessWidget that displays a welcome message. Notice how its content is fixed.
Run this code to see a static "Hello, CoddyKit!" message.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Stateless Demo'),
),
body: const Center(
child: Text(
'Hello, CoddyKit!',
style: TextStyle(fontSize: 24),
),
),
),
);
}
}When to Go Stateless
Use a StatelessWidget when:
- The widget's appearance depends only on its own configuration parameters (passed in its constructor).
- It doesn't need to respond to user interactions (like taps) or internal data changes.
- Examples:
Text,Icon,Image,AppBar,Padding,Row,Column.
These widgets are efficient because Flutter doesn't need to rebuild them if their parent changes, unless their properties explicitly change.
StatefulWidget: Dynamic UI
A StatefulWidget is a widget that can change its appearance and behavior over time, reacting to user input or data changes.
- It has internal "state" that can be modified.
- When its state changes, the widget rebuilds to reflect the new state.
- It's perfect for interactive elements like checkboxes, sliders, or dynamic lists.
Updating UI with setState()
To make a StatefulWidget dynamic, you modify its internal state. When the state changes, you must call the setState() method.
Calling setState() tells Flutter that the internal state of this widget has changed, and it needs to rebuild the UI to reflect the new state.
Without setState(), your state might change, but the UI won't update!
Interactive StatefulWidget
Let's build a simple counter app using a StatefulWidget. Tap the button to increment the number.
Observe how setState() is used to update the _counter variable and rebuild the UI.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Stateful Demo'),
),
body: const Center(
child: CounterWidget(),
),
),
);
}
}
class CounterWidget extends StatefulWidget {
const CounterWidget({super.key});
@override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0; // This is the mutable state
void _incrementCounter() {
setState(() {
_counter++; // Update state
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Count: $_counter',
style: const TextStyle(fontSize: 32),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _incrementCounter,
child: const Text('Increment'),
),
],
);
}
}StatefulWidget's Journey
StatefulWidgets go through a lifecycle. Key moments include:
createState(): Creates the mutable state object.initState(): Called once when the widget is inserted into the widget tree. Good for one-time setup.build(): Called every time the widget needs to display its UI, typically aftersetState().dispose(): Called when the widget is removed from the tree. Good for cleaning up resources.
Understanding these helps manage complex interactions.
Choosing the Right Widget
Here's a quick comparison to help you decide:
- StatelessWidget:
- Immutable properties.
- Doesn't change after creation.
- No internal state.
- Efficient for static content.
- StatefulWidget:
- Mutable state (managed by a `State` object).
- Can change dynamically.
- Responds to user interaction/data.
- Uses
setState()to trigger rebuilds.
Most widgets start as stateless; only make them stateful if they truly need to change dynamically.
Widget Type Challenge
You are building a Flutter app. Which type of widget would you primarily use for a simple icon that, when tapped, changes its color?
Recap: Dynamic vs. Static
Great job! You've learned the fundamental difference between StatelessWidget and StatefulWidget.
- StatelessWidgets are for static UI elements that don't change after they're built.
- StatefulWidgets are for dynamic UI elements that need to react to interactions or data changes, using
setState()to update their appearance.
Choosing the right widget type is crucial for building efficient and maintainable Flutter applications. In the next lesson, we'll dive into basic layout widgets!
자주 묻는 질문
“Stateless 위젯과 Stateful 위젯 비교” 강의는 무료인가요?
네 — “Stateless 위젯과 Stateful 위젯 비교” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“Stateless 위젯과 Stateful 위젯 비교”에서 뭘 배우나요?
동적인 UI를 구축할 때 StatelessWidget과 StatefulWidget을 언제 어떻게 사용하는지 배우며 두 위젯의 핵심적인 차이를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Stateless 위젯과 Stateful 위젯 비교” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Stateless 위젯과 Stateful 위젯 비교
- 기본 레이아웃 위젯
- 대화형 UI 요소
- ListView로 스크롤 가능한 목록 만들기