flutter stateful widgte non final field
Flutter Stateful Widget Non-Final Field
In Flutter, a stateful widget is a widget that can change its internal state during its lifetime. Stateful widgets are used when the UI needs to update dynamically in response to user interactions or other events.
When declaring a stateful widget in Flutter, you can use non-final fields to store mutable data within the widget's state. Non-final fields can be modified and updated throughout the widget's lifecycle.
Here's an example of a Flutter stateful widget with a non-final field:
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(
'Counter:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
In this example, the _counter
variable is a non-final field that stores the current count. The _incrementCounter
method is called when the floating action button is pressed, and it updates the _counter
value using the setState
function. The UI is then rebuilt to reflect the updated count.
Please note that this is just a basic example, and you can use non-final fields in more complex ways depending on your specific requirements.