I am developing a Quotes app as a beginner in flutter.I have multiple page in my app.Right now i want to create an icon button which will perform as a bookmark(Mark as fabourite) for the user.So i added the flutter fabourite button in my app.Initially it stays white and when i touch it ,it becomes red,which i wants.But when i move to another page and get back to the previous one(Where the fabourite icon was added) the button become white...I want it to stay red unles the user touch it again.I just want it to be used as an marked as fabourite icon...What can i do now?
class p1 extends StatefulWidget {
@override
_p1State createState() => _p1State();
}
class _p1State extends State<p1> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body:Stack(
children:<Widget>[
Image(
image:AssetImage("Image/Chowsun1.jpg"),
fit:BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Align(alignment: Alignment.center,
child: Text(' Hello world '
,style: TextStyle(fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900 ) )
),
Align(
alignment: Alignment.bottomLeft,
child: const Text(' 1 ',
style: TextStyle(
fontSize: 25.0,
fontFamily: "MonteCarlo",
color: Colors.white,
fontWeight: FontWeight.w900),
),
),
Align(
alignment: Alignment.bottomCenter,
child: FavoriteButton(
isFavorite: true,
iconSize: 40,
iconDisabledColor: Colors.red,
iconColor: Colors.white,
// iconDisabledColor: Colors.white,
valueChanged: (_isFavorite) {},
)
)])
),
);
}
}
CodePudding user response:
The issue is that you are not storing the state of the _isFavorite
anywhere, that's what we use StatefulWidget
for, is to keep track of state (and changes to it)
At the start of your class, declare a bool to track this value in:
class _p1State extends State<p1> {
bool _isFavorite = false;
then later in your build method:
FavoriteButton(
isFavorite: _isFavorite,
Finally, once you tap the button, you'll need to inform your class that the value has changed:
valueChanged: (isFav) {setState(() { _isFavorite = isFav; })},
Note that I changed the argument in your valueChanged
, because we are now tracking the value in _isFavorite
(the leading underscore indicates it's a privately scoped variable, on the class. And isFav
is scoped only to the valueChanged
method, so it doesn't actually need the leading underscore.