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?
CodePudding user response:
You forgot to use notify listeners in your CLS class
class CLS with ChangeNotifier {
bool _pressed = false;
bool detect() {
return _pressed;
}
void pressed() {
_pressed = true;
notifyListeners();
}
}
You should also remove listen:false
from your onPressed
provider listener to be able to react to the changes
ElevatedButton(
onPressed: Provider.of<CLS>(context).detect()
? null
: () => context.read<CLS>().pressed(),
CodePudding user response:
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();
});
}
}