Stateless and Stateful Widgets in Flutter
Examples:
- Stateless Widgets:
import 'package:flutter/material.dart';
class MyTextWidget extends StatelessWidget {
final String text;
// Constructor to receive the text as a parameter
MyTextWidget({required this.text});
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('StatelessWidget Example'),
),
body: Center(
child: MyTextWidget(text: 'Hello, Flutter!'), // Using the custom widget
),
),
));
}
Explanation:
In this example:
We create a custom
StatelessWidget
calledMyTextWidget
. It takes aString
as a parameter in its constructor to specify the text to display.Inside the
build
method ofMyTextWidget ,
we return aText
widget that displays the provided text with a specific style.In the
main
function, we use theMyTextWidget
widget within thebody
of aScaffold
to display the text "Hello, Flutter!".
Remember that since MyTextWidget
is a StatelessWidget
, its text
property cannot be changed once the widget is created. If you need a widget with mutable state, you should use a StatefulWidget
.
2. Stateful Widgets:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterApp(),
);
}
}
class CounterApp extends StatefulWidget {
@override
_CounterAppState createState() => _CounterAppState();
}
class _CounterAppState extends State<CounterApp> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StatefulWidget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter:',
style: TextStyle(fontSize: 20.0),
),
Text(
'$counter',
style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: incrementCounter,
child: Text('Increment'),
),
],
),
),
);
}
}
Explanation:
In this example:
We create a custom
StatefulWidget
calledCounterApp
.Inside the
CounterApp
widget, we define an internalcounter
variable, which is used to maintain the count.We define a
incrementCounter
method that increments thecounter
when called. We use thesetState
method to trigger a rebuild of the widget whenever thecounter
changes.In the
build
method ofCounterApp
, we create a simple UI that displays the current count and a button to increment it.The
main
function initializes the app by runningMyApp
, which contains theCounterApp
widget.
When you tap the “Increment” button, it calls the incrementCounter
method, which updates the counter
and triggers a rebuild of the CounterApp
widget, displaying the updated count on the screen. This demonstrates how StatefulWidget
allows you to maintain and update state in your Flutter app.