In our exploration of Flutter widgets, we've encountered a variety of powerful tools for building dynamic and responsive user interfaces. As we delve deeper into the world of Flutter development, we come across an essential concept that adds a new layer of versatility to our UI components: the state of a widget. Imagine a dynamic poster that changes its content based on user interaction. Picture a button that alters its appearance after being clicked. These interactive and adaptive behaviors are made possible by understanding and managing the state of widgets.
在探索 Flutter 部件的过程中,我们遇到了各种用于构建动态和响应式用户界面的强大工具。随着我们对 Flutter 开发世界的深入研究,我们遇到了一个重要的概念,它为我们的 UI 组件增添了一层新的多功能性:部件的状态。想象一下,一张动态海报可以根据用户交互改变其内容。想象一个按钮在被点击后会改变其外观。这些交互和自适应行为都是通过理解和管理部件的状态来实现的。
The concept of "state" is at the heart of user interfaces that react to user input, data changes, and other dynamic events. In Flutter, understanding how widgets manage their state empowers us to create apps that feel alive, responsive, and engaging. Just as a football fan's mood changes when their club scores, the state of a widget determines how it behaves in response to user actions.
" 状态 "的概念是用户界面的核心,它能对用户输入、数据变化和其他动态事件做出反应。在 Flutter 中,了解了部件如何管理自己的状态后,我们就能创建出充满活力、反应灵敏、引人入胜的应用程序。就像足球迷在俱乐部进球时情绪会发生变化一样,部件的状态决定了它在响应用户操作时的行为方式。
Understanding the StatelessWidget
了解 StatelessWidget
The term "widget" doesn't just refer to UI elements like buttons or text. It's a broader concept that encompasses any part of the user interface, even the parts that don't visually change. A StatelessWidget
is one of the fundamental building blocks. As its name implies, it represents a widget that doesn't have any internal state that can change after it's built.
" 小部件 "一词不仅仅指按钮或文本等用户界面元素。它是一个更宽泛的概念,包括用户界面的任何部分,甚至是不会发生视觉变化的部分。StatelessWidget 是基本构件之一。顾名思义,它代表了一个在创建后没有任何内部状态可以改变的部件。
How does it work?
它是如何工作的?
Imagine a painting on a canvas. Once the artist has completed the painting, it doesn't change on its own. Similarly, a StatelessWidget
is like a canvas with a beautiful illustration that remains constant. These widgets are excellent for displaying static content, such as text labels, icons, or images. They're lightweight and efficient because Flutter doesn't need to monitor any internal changes.
想象一下画布上的一幅画。一旦画家完成了这幅画,它就不会自己改变。同样,StatelessWidget 就像画布上的美丽插图,保持不变。这些部件非常适合显示静态内容,如文本标签、图标或图像。由于 Flutter 不需要监控任何内部变化,因此它们既轻便又高效。
Format of a StatelessWidget
无状态 Widget 的格式
Creating a StatelessWidget
involves defining a class that extends StatelessWidget
and implementing the required build
method. The build
method is where you define the structure of your widget, specifying how it should look based on its input parameters (also known as "props" in some other UI frameworks).
创建 StatelessWidget 需要定义一个扩展 StatelessWidget 的类,并实现所需的构建方法。在构建方法中,你可以定义 widget 的结构,根据输入参数(在其他一些 UI 框架中也称为 "道具")指定它的外观。
Here's a simplified format of a StatelessWidget
:
下面是无状态 Widget 的简化格式:
dart
class MyStatelessWidget extends StatelessWidget {
// Properties, such as text and color, can be passed as parameters
final String text;
final Color color;
// Constructor to initialize the properties
MyStatelessWidget({required this.text, required this.color});
// The build method defines the widget's appearance
@override
Widget build(BuildContext context) {
return Container(
color: color,
child: Text(text),
);
}
}
In this example, MyStatelessWidget
takes in text
and color
as parameters and uses them to build a Container
with the specified text and background color. Once built, this widget won't change its appearance even if the input parameters change. It's a static snapshot of the UI.
在本例中,MyStatelessWidget 将文本和颜色作为参数,并使用它们创建一个具有指定文本和背景颜色的容器。一旦创建完成,即使输入参数发生变化,该 widget 也不会改变其外观。它是用户界面的静态快照。
When to Use StatelessWidget
何时使用 StatelessWidget
StatelessWidget
is your go-to choice when you need to display content that won't change or respond to user interaction. It's perfect for UI components that remain the same throughout the lifetime of your app. Think of it as a tool for building the "building blocks" of your interface.
当您需要显示不会更改或响应用户交互的内容时,StatelessWidget 是您的首选。它非常适合在应用程序生命周期内保持不变的用户界面组件。可以将其视为构建界面 "积木 "的工具。
Understanding the StatefulWidget
了解 StatefulWidget
Several UI elements are dynamic and change based on user interaction, data updates, or other events. This is where the StatefulWidget
comes into play. Unlike the StatelessWidget
, a StatefulWidget
has an internal state that can change over time. This makes it a powerful tool for creating interactive and responsive user interfaces.
一些用户界面元素是动态的,会根据用户交互、数据更新或其他事件发生变化。这就是 StatefulWidget 发挥作用的地方。与 StatelessWidget 不同,StatefulWidget 具有可随时间变化的内部状态。这使它成为创建交互式和响应式用户界面的强大工具。
How does it work?
它是如何工作的?
Think of a StatefulWidget
as a living organism that can respond to its environment. Just like how a chameleon changes its color to blend with its surroundings, a StatefulWidget
can change its appearance based on the changes in its internal state. For example, a button that toggles between "on" and "off" states is a classic use case of a StatefulWidget
.
把 StatefulWidget 想象成一个能对环境做出反应的活有机体。就像变色龙会改变颜色以融入周围环境一样,StatefulWidget 也能根据内部状态的变化改变外观。例如,在 "开 "和 "关 "状态之间切换的按钮就是一个典型的 StatefulWidget 用例。
Format of a StatefulWidget
StatefulWidget 的格式
Creating a StatefulWidget
involves two classes: one for the widget itself and another for its corresponding state. The widget class extends StatefulWidget
and returns an instance of the state class in its createState
method. The state class extends State
and holds the mutable data for the widget.
创建一个 StatefulWidget 需要两个类:一个用于 widget 本身,另一个用于其相应的状态。widget 类扩展了 StatefulWidget,并在 createState 方法中返回 state 类的实例。状态类扩展了 State,并保存了 widget 的可变数据。
Here's a simplified format of a StatefulWidget
:
下面是一个简化的 StatefulWidget
格式:
dart
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
// Properties that can change over time
bool isActive = false;
// Method to update the state
void toggleActive() {
setState(() {
isActive = !isActive;
});
}
@overrideWidget build(BuildContext context) {
return ElevatedButton(
onPressed: toggleActive,
child: Text(isActive ? 'Active' : 'Inactive'),
);
}
}
In this example, MyStatefulWidget
creates an instance of _MyStatefulWidgetState
as its internal state. The state class holds the isActive
property, which changes when the button is pressed. The toggleActive
method updates the state and triggers a rebuild of the UI. The UI responds to the state change by displaying either "Active" or "Inactive" text on the button.
在本例中,MyStatefulWidget 创建了 _MyStatefulWidgetState 的实例作为其内部状态。状态类持有 isActive 属性,该属性会在按下按钮时发生变化。toggleActive 方法会更新状态并触发用户界面的重建。用户界面会通过在按钮上显示 "Active(活动)"或 "Inactive(非活动)"文本来响应状态变化。
When to use StatefulWidget
?
何时使用 StatefulWidget?
You can use a StatefulWidget
when you need to create UI elements that can change, react to user actions, or display dynamic content. It's the perfect choice for building forms, interactive buttons, sliders, and any component that should update in response to user interactions or data changes.:
当您需要创建可以改变、响应用户操作或显示动态内容的用户界面元素时,可以使用 StatefulWidget。它是构建表单、交互式按钮、滑块以及任何需要根据用户交互或数据变化进行更新的组件的最佳选择:
The setState
Function in a StatefulWidget
有状态部件中的 setState 函数
You often need to update the internal state of the widget to trigger a rebuild of the UI and reflect the changes. This is where the setState
function comes into play. It's a vital method that ensures that your UI is updated properly when the state changes. Imagine watching a Premier League football match where the score is updated in real-time as the game is ongoing. Theexcitement of seeing those score changes happen on screen is similar to how the setState function operates in Flutter.
您经常需要更新部件的内部状态,以触发用户界面的重建并反映变化。这就是 setState 函数发挥作用的地方。这是一个重要的方法,可以确保在状态发生变化时正确更新用户界面。试想一下,在观看英超足球比赛时,比分会随着比赛的进行实时更新。在屏幕上看到比分变化时的激动心情与 Flutter 中 setState 函数的操作类似。
How setState
works?
setState 如何工作?
When you call the setState
function, Flutter schedules a rebuild of the widget's UI. Here is how it works:
当您调用 setState 函数时,Flutter 会安排重建部件的用户界面。工作原理如下
Changing State: When a part of your widget's state changes,you call the setState
function. For instance, you might update a counter, change a boolean value, or modify any other state-related data.
改变状态: 当部件的部分状态发生变化时,您需要调用 setState 函数。例如,您可以更新计数器、更改布尔值或修改任何其他与状态相关的数据。
Mark for Rebuild: The setState
function notifies the Flutter framework that the widget's internal state has changed and that it needs to be rebuilt.
标记重建: setState 函数通知 Flutter 框架,部件的内部状态已发生变化,需要重建。
Build Method Called: The framework then calls the widget's build
method again. Inside the build
method, you create the updated UI based on the new state.
调用构建方法: 然后,框架会再次调用 widget 的构建方法。在构建方法中,您将根据新状态创建更新的用户界面。
UI Update: The new UI is then rendered on the screen,reflecting the changes you made to the state.
Using `setState
Here's a practical example of how to use setState
in a StatefulWidget
:
dart
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _count = 0;
void _incrementCounter() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text('Count: $_count'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
In this example, the _incrementCounter
method uses setState
toincrease the _count
value by one. This change triggers a rebuild of the UI, and the updated count is reflected in the Text
widget.
When to use setState
?
Use setState
whenever you need to modify the internal state of a StatefulWidget
. It's crucial for keeping your UI in sync with the data changes. Keep in mind that setState
should only be used within the widget that extends State
.
Caution and Performance
While setState
is a powerful tool, excessive use of it can lead to performance issues. Since setState
rebuilds the entire widget, using it too frequently can slow down your app. For more complex state management, you might explore state management solutions like Provider, Riverpod, or BLoC. Don't worry, we will explore state management as we build more complex Uis in this book.