Junior
Mis vahe on Stateful ja Stateless vidjetidel?
sobes.tech AI
Vastus AI-lt
-
StatelessWidget:
- Does not have internal state that can change over time.
- Widget parameters are set at creation and remain unchanged throughout its lifecycle.
- Used for displaying static data.
- Rebuild occurs only when the parent widget rebuilds.
- Implemented via the
build()method.
-
StatefulWidget:
- Has internal state (
State) that can change in response to events (user actions, network requests, etc.). - Rebuild occurs when
setState()is called. - Used for creating interactive elements and displaying dynamic data.
- Consists of two parts: the
StatefulWidgetitself and the associatedStateobject.
- Has internal state (
| Attribute | StatelessWidget | StatefulWidget |
|---|---|---|
| State | None | Has mutable state (State) |
| Rebuild | When parent rebuilds | When setState() is called |
| Usage | Static data, non-interactive elements | Interactive elements, dynamic data |
| Implementation | Only the build() method |
createState() and lifecycle methods in State |
// Example StatelessWidget
class MyStatelessWidget extends StatelessWidget {
final String text;
MyStatelessWidget({required this.text});
@override
Widget build(BuildContext context) {
return Text(text); // Simply displays the passed text
}
}
// Example StatefulWidget
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0; // Internal state
void _incrementCounter() {
setState(() {
// Change state and trigger rebuild
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Counter:'),
Text('$_counter'),
ElevatedButton(
onPressed: _incrementCounter, // Method on press
child: Text('Increment'),
),
],
);
}
}