text
stringlengths
1
372
<topic_end>
<topic_start>
step 2: subclass StatefulWidget
the FavoriteWidget class manages its own state,
so it overrides createState() to create a state
object. the framework calls createState()
when it wants to build the widget.
in this example, createState() returns an
instance of _FavoriteWidgetState,
which you’ll implement in the next step.
<code_start>
class FavoriteWidget extends StatefulWidget {
const FavoriteWidget({super.key});
@override
State<FavoriteWidget> createState() => _FavoriteWidgetState();
}
<code_end>
info note
members or classes that start with an underscore
(_) are private. for more information,
see libraries and imports, a section in the
dart language documentation.
<topic_end>
<topic_start>
step 3: subclass state
the _FavoriteWidgetState class stores the mutable data
that can change over the lifetime of the widget.
when the app first launches, the UI displays a solid
red star, indicating that the lake has “favorite” status,
along with 41 likes. these values are stored in the
_isFavorited and _favoriteCount fields:
<code_start>
class _FavoriteWidgetState extends State<FavoriteWidget> {
bool _isFavorited = true;
int _favoriteCount = 41;
// ···
}
<code_end>
the class also defines a build() method,
which creates a row containing a red IconButton,
and text. you use IconButton (instead of icon)
because it has an onPressed property that defines
the callback function (_togglefavorite) for handling a tap.
you’ll define the callback function next.
<code_start>
class _FavoriteWidgetState extends State<FavoriteWidget> {
// ···
@override
widget build(BuildContext context) {
return row(
mainAxisSize: MainAxisSize.min,
children: [
container(
padding: const EdgeInsets.all(0),
child: IconButton(
padding: const EdgeInsets.all(0),
alignment: Alignment.centerRight,
icon: (_isfavorited
? const Icon(Icons.star)
: const Icon(Icons.star_border)),
color: colors.red[500],
onPressed: _toggleFavorite,
),
),
SizedBox(
width: 18,
child: SizedBox(
child: Text('$_favoriteCount'),
),
),
],
);
}
}
<code_end>
lightbulb tip
placing the text in a SizedBox and setting its
width prevents a discernible “jump” when the text changes
between the values of 40 and 41 — a jump would
otherwise occur because those values have different widths.
the _toggleFavorite() method, which is called when the
IconButton is pressed, calls setState().
calling setState() is critical, because this
tells the framework that the widget’s state has
changed and that the widget should be redrawn.
the function argument to setState() toggles the
UI between these two states:
<code_start>
void _toggleFavorite() {
setState(() {
if (_isfavorited) {
_favoriteCount -= 1;
_isFavorited = false;
} else {
_favoriteCount += 1;
_isFavorited = true;
}
});
}
<code_end>