'The way to disable button using provider

I'm using Provider and trying to make buttons disable without StatfulWidgets. But I can't find the way to do it.

What I did:

class CLS with ChangeNotifier {
    bool pressed = false;
    bool detect(return pressed;);
    void pressed(pressed = true;)
}

....

//StatelessWidget
ElevatedButton(
  ...
  onPressed: Provider.of<CLS>(context, listen: false).detect()
             ? null : context.read<CLS>().pressed(),
  ...
)

I know buttons are disabled when onPressed is null. So I want to make it dynamicaly, but buttons color is not changed. CLS.pressed becomes true when button is pressed.

What sohould I do?



Solution 1:[1]

Try using below code. Refer this link for more details. https://stackoverflow.com/a/68418866/16467763

//StatelessWidget

ElevatedButton(
  ...
  onPressed: Provider.of<CLS>(context).isDetect
             ? null : context.read<CLS>().pressed(),
  ...
)

//

class CLS with ChangeNotifier {
    bool _pressed = false;
   
    bool get isDetect => _pressed;

    void pressed() {
       this._pressed  = true;
   
       Future.delayed(Duration(seconds: 0)).then((value) {
          super.notifyListeners();
       });
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DholaHardik