I created a re-usable textfield for my Flutter project but the OnChange method is not working with the re-usable widget. Whenever I tried creating the field directly on the project it works. I am suspecting that the value option that comes with the Textfield onChange is likely the reason for the error. Any help with a solution?
class NumberOnlyTextField extends StatelessWidget{
final controller;
final String hintText;
final bool obscureText;
final bool enableTxtField;
final Function()? onChanged;
const NumberOnlyTextField({
super.key,
required this.controller,
required this.hintText,
required this.obscureText,
required this.enableTxtField,
required this.onChanged,
});
@override
Widget build(BuildContext context){
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: const Color.fromARGB(255, 213, 211, 211)),
borderRadius: BorderRadius.circular(4),
),
child: Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: TextField(
controller: controller,
onChanged: (value) { onChanged; },
obscureText: obscureText,
enabled: enableTxtField,
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp('[0-9]+.?[0-9]*'),
),
],
decoration: InputDecoration(
border: InputBorder.none,
hintText: hintText,
hintStyle: TextStyle(color: Colors.grey[500]),
),
),
),
),
);
}
}
Here is where it is used on another page:
//Amount
NumberOnlyTextField(
controller: amountXController,
onChanged: validateAmount(),
hintText: 'Amount',
obscureText: false,
enableTxtField: true,
),
const SizedBox(height: 10),
2
Answers
you’ll need to update your code as follows.
U are not calling ur onChanged function this why function is not working.
I did this
or
so NumberOnlyTextField now
}
}
And now its working. I tried to print Value changed: when i write something in textfield. And it works !