Widget
Widget
Definition of a Widget:
In Flutter, a widget is a fundamental building block of the user interface. It describes a
part of the UI by providing a configuration for an element. Widgets can represent anything
from a structural element (like a button or menu), a stylistic element (like a font or color
scheme), or an aspect of layout (like padding or alignment).
Types of Widgets:
1. Stateless Widgets: Immutable widgets that do not change once created. They are used
for static content that doesn’t need to update dynamically.
- Example: `Text`, `Icon`.
2. Stateful Widgets: Mutable widgets that maintain a state that may change during the
lifecycle of the widget. They are used for dynamic content that can change in response to
user interactions or other factors.
- Example: `Checkbox`, `Slider`.
Common Widgets:
Text('Hello, Flutter!')
- Container: A versatile widget that can contain other widgets and provide padding,
margins, borders, and background color.
Container(
padding: EdgeInsets.all(16.0),
color: Colors.blue,
child: Text('Hello, Flutter!'),
)
- Row and Column: Layout widgets that arrange their children horizontally (Row) or
vertically (Column).
Row(
children: <Widget>[
Icon(Icons.star),
Text('Star'),
],
)
ListView(
children: <Widget>[
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
],
)
Example Code:
Flutter Page 1
Example Code:
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
void _toggleState() {
setState(() {
_isOn = !_isOn;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
Flutter Page 2
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_isOn ? 'ON' : 'OFF'),
ElevatedButton(
onPressed: _toggleState,
child: Text('Toggle'),
),
],
);
}
}
Widgets in Flutter are used to construct the UI by describing elements and their configuration.
Understanding the difference between stateless and stateful widgets, as well as how to compose
them, is essential for building effective Flutter applications.
Flutter Page 3