onPressed 图标没有改变

Icon not changing on onPressed

我正在做一个更大的项目,但不知道为什么这个小部分让我花了将近一整天的时间。

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();
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

我刚刚尝试删除 AllTests() 之前的 const 关键字,但它现在仍然有效。 我也试过直接把函数放到IconButton的onPressed里。

hello 被打印到控制台,但图标没有改变。有什么问题吗?

使用 = 运算符而不是 ==

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

您使用了 == 运算符而不是 = 运算符。用这个代替:

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

} else {
    play = Icons.play_circle_filled;
}
}