In Flutter, widgets are the building blocks of the user interface. They are classified into two main categories: Stateless Widgets and Stateful Widgets.
Definition:
Use Cases:
import 'package:flutter/material.dart';
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateless Widget Example'),
),
body: Center(
child: Text('Hello, Stateless Widget!'),
),
);
}
}
Definition:
Use Cases:
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful Widget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
setState
functionThe setState
function is a crucial part of managing state in Flutter applications. It is used within stateful widgets to notify the framework that the state of the widget has changed and that the widget needs to be rebuilt with the new state. Here's a detailed explanation of how it works and its significance:
Purpose of setState
The primary purpose of setState
is to trigger a rebuild of the widget tree when the internal state of the widget changes. This ensures that the UI reflects the current state.
How setState
Works
setState
callback function.Key Points to Remember
setState
to update state variables and trigger UI updates in response to user interactions or other events.setState
efficient for updating UI.setState
is executed synchronously, so the state is immediately updated before the UI is rebuilt.