Search code examples
flutterdartflutter-layoutflutter-state

SpeedDial: change color on click


I'm trying to do so that if I click on a SpeedDialChild (button) then the color of it changes, but even if the value of fun.switchTakePhoto changes from true to false (and vice versa) the color remains red for some reason.


class MainPage extends StatefulWidget {
  Home createState() => Home();
}
 
@immutable
class Home extends State<MainPage> {
  //Home({super.key});
  var fun = FunctionManager();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => ChangePWD()),
            );
          },
          child: const Text('Change password'),
        ),
      ),
      floatingActionButton: SpeedDial(
          icon: Icons.settings,
          backgroundColor: Colors.amber,
          children: [
            SpeedDialChild(
              child: const Icon(Icons.photo_camera),
              label: 'Activate/Deactivate: Take Photo',
              backgroundColor: fun.switchSendPhoto == true
                  ? const Color.fromARGB(255, 109, 255, 64)
                  : const Color.fromARGB(255, 255, 64, 64),
              onTap: () {
                setState(() {
                  fun.switchTakePhoto = !fun.switchTakePhoto;
                });
              },
            ),
          ]),
    );
  }
}
 
class FunctionManager {
  bool switchTakePhoto = true;
  bool switchSendPhoto = false;
  bool switchRec = true;
  bool switchPlay = true;
  bool switchNotifications = true;
}

Solution

  • The issue might be with data class. I've solve this way.

    class FunctionManager {
      final bool switchSendPhoto;
      FunctionManager({
        this.switchSendPhoto = false,
      });
    
      FunctionManager copyWith({
        bool? switchTakePhoto,
      }) {
        return FunctionManager(
          switchSendPhoto: switchTakePhoto ?? switchSendPhoto,
        );
      }
    }
    

    A state-level variaable like

      FunctionManager fun = FunctionManager()
    

    And update data

    onTap: () {
       fun = fun.copyWith(switchTakePhoto: !fun.switchSendPhoto);
        setState(() {});
      },
    

    Same goes for others