无状态与有状态组件
了解 StatelessWidget 与 StatefulWidget 的核心区别,学习在构建动态用户界面时何时以及如何使用它们。
无状态与有状态组件 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!
常见问题解答
「无状态与有状态组件」课时是免费的吗?
是的 — 「无状态与有状态组件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。
「无状态与有状态组件」这节课中我会学到什么?
了解 StatelessWidget 与 StatefulWidget 的核心区别,学习在构建动态用户界面时何时以及如何使用它们。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flutter Mobile Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「无状态与有状态组件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flutter Mobile Development 课中编写并运行代码吗?
能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 无状态与有状态组件
- 基础布局组件
- 交互式用户界面元素
- 使用 ListView 构建可滚动列表