How to set onChanged value of Switch

772 Views Asked by At

I have a switch which toggle the app theme but there is some errors on the code

Switch(value: AppStyleMode.isSwitched, onChanged: (value)=> AppStyleMode.switchMode())

My Theme file

 import 'package:flutter/material.dart';

    class AppStyleMode extends ChangeNotifier {
      bool isSwitched = true; 
      Color primaryBG = Colors.white;
      Color appBarBG = Colors.yellow;
      
    
      switchMode() {
        if (isSwitched == true) {
          primaryBG = Colors.black];
          appBarBG = Colors.grey[400];
         
          isSwitched = false;
        } else {
          //if it is dark mode currently switch to light
          primaryBG = Colors.white;
          appBarBG = Colors.yellow;
      
          isSwitched = true;
        }
    
        notifyListeners();
      }
    }

Errors on Switch :

Switch Error

1

There are 1 best solutions below

0
On

If you are not using any particular state management packages,

First, you would have to create an instance of your AppStyleMode class, so that you can use values from it and also listen to it's changes.

Assuming you have a StatefulWidget,

first define your AppStyleMode in it's State,

class MyState extends State<MyStatefulWidget> {

  late AppStyleMode appStyleMode;

Then in your initState, initialise it and add a listener to it.

void initState () {
  super.initState();
  
  appStyleMode = AppStyleMode();

  // Also add a listener to it and call setState to rebuild your StatefulWidget
  appStleMode.addListener(() => {
    setState(() {});
  });
}

Then you can use it in your build by using your variable appStyleMode like this,

Switch(value: appStyleMode.isSwitched, onChanged: (value) => appStyleMode.switchMode())

I would rather suggest you look into a State management solution like provider or Getx. But it is not compulsory.