Search code examples
flutterdartflutter-textformfield

The argument type 'String' can't be assigned to the parameter type 'TextEditingController?'


I have above 10 TextFormFields so i created widget that i could not type this same code to every of them

class TextFieldWidget extends StatelessWidget {
  const TextFieldWidget(
      {super.key, required this.countryshortcut, required this.controllername});

  final String countryshortcut;
  final String controllername;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 60.0,
      height: 60,
      child: TextFormField(
        decoration: InputDecoration(
          hintText: countryshortcut,
          counterText: "",
        ),
        maxLength: 2,
        controller: controllername,
        keyboardType: TextInputType.number,
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      ),
    );
  }
}

as you see i need controller and here i get an error

The argument type 'String' can't be assigned to the parameter type 'TextEditingController?'.

I tried solutions from other topics, for example trying to change type of variable from String or changing 'controllername' to 'controllername.text' (the getter text isn't defined) but it didn't work.


Solution

  • While you like to use controller pass TextEditingController

    class TextFieldWidget extends StatelessWidget {
      const TextFieldWidget({
        super.key,
        required this.countryshortcut,
        required this.controller,
      });
    
      final String countryshortcut;
      final TextEditingController controller;
    
      @override
      Widget build(BuildContext context) {
        return SizedBox(
          width: 60.0,
          height: 60,
          child: TextFormField(
            decoration: InputDecoration(
              hintText: countryshortcut,
              counterText: "",
            ),
            maxLength: 2,
            controller: controller,
            keyboardType: TextInputType.number,
            inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          ),
        );
      }
    }
    

    If you like to pass initial value TextEditingController.fromValue(

     final TextEditingController controller =
            TextEditingController.fromValue(TextEditingValue(text: "initValue"));
    
     TextFieldWidget(
      controller: controller,
      countryshortcut: "",
    ),