Stateful Widgets
Initialization of StatefulWidget
We use a "stful" snippet.
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
Click counter example
import 'package:flutter/material.dart';
void main() {
runApp(const App());
}
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
int counter = 0;
void onClick() {
setState(() {
counter = counter + 1;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Click count',
style: TextStyle(
fontSize: 30,
)),
Text(
'$counter',
style: const TextStyle(fontSize: 30),
),
IconButton(
iconSize: 50,
onPressed: onClick,
icon: const Icon(
Icons.add_box_sharp,
))
],
)),
),
);
}
}
flutter update UI: setState is basically calling the 'build' method again with the new data.