Stateful Widget
A stateful widget is dynamic:it can change its appearance in response to events triggered by user interactions. Checkbox, Form, and TextField are examples of stateful widgets. Stateful widgets subclass StatefulWidget. |
Stateless
A stateless widget never changes. Icon, IconButton, and Text are examples of stateless widgets. Stateless widgets subclass StatelessWidget. |
Managing State
class TapboxA extends StatefulWidget {
TapboxA({Key key}) : super(key: key);
@override
_TapboxAState createState() => _TapboxAState();
}
class _TapboxAState extends State<TapboxA> {
bool _active = false;
void _handleTap() {
setState(() {
_active = !_active;
});
}
|
|
|
Example Stateful Implementation
class _FavoriteWidgetState extends State<FavoriteWidget> {
// ยทยทยท
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (_isFavorited ? Icon(Icons.star) : Icon(Icons.star_border)),
color: Colors.red[500],
onPressed: _toggleFavorite,
),
),
SizedBox(
width: 18,
child: Container(
child: Text('$_favoriteCount'),
),
),
|
Managing State
lass ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
|
Parent widget manages state
|
|
Navigation
Push new route |
Navigator.push( context, MaterialPageRoute(builder: (context) => SecondRoute()), ); }
|
Return to old route |
onPressed: () { Navigator.pop(context); }
|
Define routes |
routes: { '/': (context) => FirstScreen(), '/second': (context) => SecondScreen(), },
|
Push data to new screen |
Navigator.push( context, MaterialPageRoute( builder: (context) => DetailScreen(todo: todos[index]), ),
|
Return data from screen |
RaisedButton( onPressed: () { // The Yep button returns "Yep!" as the result. Navigator.pop(context, 'Yep!'); }, child: Text('Yep!'), );
|
|