6. Flutter - Stateful Widgets
Stateful widgets automatically refreshes whenever data of variables inside its object widget is changed.
1. Create a stateful widget using snippet shortcut "stful"
2. It will create two classes.
class TESTWIDGET extends StatefulWidget {
const TESTWIDGET({Key? key}) : super(key: key);
@override
_TESTWIDGETState createState() => _TESTWIDGETState();
}
class _TESTWIDGETState extends State<TESTWIDGET> {
@override
Widget build(BuildContext context) {
return Container();
}
}
TESTWIDGET // is the initializer widget which creates a state object widget called _TESTWIDGETState.
_TESTWIDGETState // works like a stateless widget but can put variables above @override. Change Container() to widget root that you want to use.
Can use Action Menu to quickly convert a stateless widget into a stateful widget.
Changing variables in a stateful widget:
Use function setState( (){} )
// Inside brackets is a function. setState is a function holding a function. Change variable inside the brackets.
// setState() function triggers the build function of the stateful widget.
Example:
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
Level+=1;
});
},
child: Icon(
Icons.add,
size: 30,
color: Colors.grey[900],
),
backgroundColor: Colors.amberAccent,
),
LIFECYCLE METHODS:
initState()
// calls once when widget is created.
// subscribes to any data streams or objects that could change the data
// can put a one time run function or setup in here which runs only once, where in the build function it will run every build.
// snippet is initState()
// put it above the @override in the class that has the build function.
Build()
// builds the widget tree
// rebuilds whenever the setState((){}) is called
Dispose()
// when widget/state object is destroyed/removed
Comments
Post a Comment