▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
▲▼▲▼▲▼
tags : #coding #flutter #widget
references : Widget
▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼▲▼
▲▼▲▼▲▼
A StatelessWidget is one of the fundamental building blocks in Flutter for creating user
interfaces. Here’s a comprehensive overview of StatelessWidget :
Overview
A StatelessWidget is a widget that describes part of the user interface by building a
constellation of other widgets that describe the user interface more concretely. Widgets are the
central class hierarchy in the Flutter framework. A StatelessWidget is immutable, meaning
that once it is built, it cannot change. If the widget needs to change based on user interaction or
other factors, a StatefulWidget should be used instead.
Key Characteristics
1. Immutability: The configuration of a StatelessWidget does not change over time. This
means that all properties of a StatelessWidget are final.
2. Single Build Method: A StatelessWidget only has one method to override:
build(BuildContext context) . This method describes the part of the user interface
represented by this widget.
Lifecycle
A StatelessWidget goes through the following lifecycle stages:
1. Constructor Call: The constructor of the StatelessWidget is called to create an instance.
2. build() Method: The build method is called to describe the widget in terms of other,
lower-level widgets.
Example
Here’s a simple example of a StatelessWidget :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('StatelessWidget Example'),
),
body: Center(
child: MyStatelessWidget(),
),
),
);
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
'Hello, Flutter!',
style: TextStyle(fontSize: 24),
);
Usage :
Static Content: StatelessWidget is ideal for static content that does not change after the
widget is built, such as text labels, icons, static lists, etc.
Performance: Since StatelessWidget does not change, it can be more efficient in terms
of performance compared to StatefulWidget .
Best Practices :
1. Keep it Simple: Since StatelessWidget does not have internal state, keep the logic
simple and focus on UI representation.
2. Pure Functions: The build method should be a pure function, meaning it should not have
any side effects and should return the same output given the same input.
3. Composability: Break down complex UIs into smaller, reusable StatelessWidget s.
Comparison with StatefulWidget :
State Management: Use StatefulWidget if you need to manage state, handle user
interactions, or work with animations. StatefulWidget has an associated State object
that can be changed over time.
Rebuilds: StatefulWidget can trigger rebuilds based on state changes, while
StatelessWidget rebuilds only when its parent widget rebuilds.