'TextEditingController is Not Listening to Chanages in TextField I am Using Provider Package to Handle
Class for IsButtonActive
class isButtonActive with ChangeNotifier {
bool _isButtonActive = false;
TextEditingController controller = TextEditingController();
void activeButton() {
controller.addListener(() {
final _isButtonActive = controller.text.isNotEmpty;
this._isButtonActive = _isButtonActive;
});
notifyListeners();
}
get isButtonActive => _isButtonActive;
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
On Textfield Widget Controller is Called With Cosumer
Consumer<isButtonActive>(
builder: (context, mybutton, child) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: appPrimaryColor, // background
onPrimary: Colors.white, // foreground
fixedSize: Size(context.screenWidth * 0.80,
context.screenHeight * 0.07),
onSurface: appPrimaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
onPressed: mybutton.isButtonActive
? () {
mybutton.activeButton();
loginAction(); // Calling the Login fucntion from the HomeScreen to Perform LoginAction
}
: null,
When i Type Something in Textfield Button Show be Active if Clear Textfield button should be Deactive
Solution 1:[1]
You might want to move the notifyListener() instead the listener of your controller.
void activeButton() {
controller.addListener(() {
final _isButtonActive = controller.text.isNotEmpty;
this._isButtonActive = _isButtonActive;
notifyListeners();
});
}
As you didn't provide all your code, I'm not sure.
Make sure your TextField is given the controller of your model.
Also, you are enabling the ElevatedButton only isButtonActive is true. But the I only see mybutton.activeButton(); called in the onPressed of the ElevatedButton which looks inactive by default...
So the user will never be able to click on the button to active it.
Solution 2:[2]
The issue is most probably this function:
void activeButton() {
controller.addListener(() {
final _isButtonActive = controller.text.isNotEmpty;
this._isButtonActive = _isButtonActive;
});
notifyListeners();
}
You are calling the `notifyListeners() only once, when this function is called. What you need is to call it inside the listener like so:
controller.addListener(() {
final _isButtonActive = controller.text.isNotEmpty;
this._isButtonActive = _isButtonActive;
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 | Valentin Vignal |
| Solution 2 | Vandad Nahavandipoor |
