5 A Program
5 A Program
void main() {
runApp(MyApp());
}
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
),
);
}
}
CounterDisplay(this.count);
@override
Widget build(BuildContext context) {
return Text(
'Counter Value: $count',
style: TextStyle(fontSize: 20),
);
}
}
CounterButton(this.onPressed);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}
Output
When you click on increment counter,it displays
Explanation
This line imports the Material Design package from Flutter, which provides ready-to-use
widgets like Scaffold, AppBar, ElevatedButton, and others.
2. Main Function
dart
CopyEdit
void main() {
runApp(MyApp());
}
The main() function is the entry point of the Flutter application. It runs the app by
calling runApp(), which takes a widget (in this case, MyApp) as an argument and makes it
the root widget of the app.
5. _MyHomePageState Class
dart
CopyEdit
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
),
);
}
}
CounterDisplay(this.count);
@override
Widget build(BuildContext context) {
return Text(
'Counter Value: $count',
style: TextStyle(fontSize: 20),
);
}
}
CounterButton(this.onPressed);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}
The MyApp widget sets up the MaterialApp, and the home page is MyHomePage.
MyHomePage is a StatefulWidget that maintains a counter variable, which can be
changed by pressing the button.
CounterDisplay is a StatelessWidget that simply displays the current counter value.
CounterButton is another StatelessWidget that takes an onPressed callback to
increment the counter.
When the button is pressed, incrementCounter() is called, which updates the state and
triggers a rebuild of the widget, showing the new counter value.