乐闻世界logo
搜索文章和话题

What is the relation between stateful and stateless widgets in Flutter?

1个答案

1

In Flutter, Stateful Widgets and Stateless Widgets are two fundamental types for building user interfaces, each with distinct roles and characteristics in managing the display and updates of data on the page.

Stateless Widgets

Stateless Widgets are immutable, meaning their properties cannot change— all values are final. They are typically used when a UI component remains static throughout its lifecycle. For example, a simple display label or icon, which does not require updates after creation based on user interaction or other factors.

Example:

dart
class MyTextWidget extends StatelessWidget { final String text; MyTextWidget({this.text}); Widget build(BuildContext context) { return Text(text); } }

In this example, MyTextWidget simply displays the incoming text without any internal state changes.

Stateful Widgets

Unlike Stateless Widgets, Stateful Widgets can change their state throughout their lifecycle. This allows them to update displayed content based on user interaction or data changes. They contain a State object that holds mutable information during the widget's lifecycle, and they trigger UI rebuilds by calling setState when data changes.

Example:

dart
class MyCounterWidget extends StatefulWidget { _MyCounterWidgetState createState() => _MyCounterWidgetState(); } class _MyCounterWidgetState extends State<MyCounterWidget> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } Widget build(BuildContext context) { return Column( children: <Widget>[ Text('You have pushed the button this many times:'), Text('$_counter', style: Theme.of(context).textTheme.headline4), RaisedButton( onPressed: _incrementCounter, child: Text('Increment'), ), ], ); } }

In this example, MyCounterWidget is a Stateful Widget with an internal state _counter. When the button is pressed, _counter increments, and calling setState rebuilds the UI to reflect the latest value.

Relationship Summary

Overall, Stateless Widgets are used for displaying static information, while Stateful Widgets implement interactive and dynamic UI components. Understanding these differences helps organize code and manage UI elements effectively, enabling the creation of more dynamic and user-responsive applications.

2024年8月8日 00:49 回复

你的答案