Issue
I want that my icon color, at start grey, when i press it one time starts being pink, and if pressed again then grey (and all the time like that). I've been looking for posts about it but nothing works. I don't get why my icon color is not changing. Here is my code:
IconButton(
icon: Icon(Icons.favorite,
size: 30.0,
color: (isFavourite == true)
? Colors.red
: Color.fromARGB(255, 114, 113, 113)),
onPressed: () {
setState(() {
isFavourite != isFavourite;
});
}),
Thank you!
Solution
You're simply using an incorrect statement in your code.
You're using using comparison:
isFavourite != isFavourite;
so the isFavourite value is not changed.
You need to use:
isFavourite = !isFavourite;
Here is a complete working example using part of your code (you can test it on https://dartpad.dev/):
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Sample",
home: Scaffold(
appBar: AppBar(title: const Text("Sample")),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool isFavourite = false;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.favorite,
size: 30,
color: isFavourite
? Colors.red
: const Color.fromARGB(255, 114, 113, 113),
),
onPressed: () {
setState(() {
isFavourite = !isFavourite;
});
},
),
const Text("Favourite"),
],
);
}
}
Answered By - ישו אוהב אותך
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.