Samuella M. Aglago
Samuella M. Aglago

Reputation: 105

Icon not changing on onPressed

I am working on a larger project but do not know why this small part has kept me almost a whole day.

import 'package:flutter/material.dart';

void main() {
  runApp(const AllTests());
}

class AllTests extends StatefulWidget {
  const AllTests({Key? key}) : super(key: key);

  @override
  _AllTestsState createState() => _AllTestsState();
}

class _AllTestsState extends State<AllTests> {

  IconData play = Icons.play_circle_filled;
  onPressed(){
    if(play == Icons.play_circle_filled){
      play == Icons.pause_circle_filled_rounded;
    } else {
      play == Icons.play_circle_filled;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children:  [
              IconButton(
                icon: Icon(
                  play,
                  size: 80,
                  color: Colors.black,
                ), 
                onPressed: () {
                  setState(() {
                    print('hello');
                    onPressed();
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

I just tried removing the const keyword before AllTests() but it is still now working. I have also tried putting the function directly into the onPressed of IconButton.

the hello gets printed into the console, but the icon does not change. what could be wrong?

Upvotes: 3

Views: 94

Answers (2)

Abbasihsn
Abbasihsn

Reputation: 2171

You have used the == operator instead of the = operator. use this instead:

onPressed(){
if(play == Icons.play_circle_filled){
    play = Icons.pause_circle_filled_rounded;

} else {
    play = Icons.play_circle_filled;
}
}

Upvotes: 1

MaNDOOoo
MaNDOOoo

Reputation: 1555

Use the = operator not the ==.

onPressed() {
  if(play == Icons.play_circle_filled){
    play = Icons.pause_circle_filled_rounded;
  } else {
    play = Icons.play_circle_filled;
  }
}

Upvotes: 1

Related Questions