Home > OS >  Pass onSaved(value) from a custom TextFormField widget to another?
Pass onSaved(value) from a custom TextFormField widget to another?

Time:11-12

In order to create a reusable widget that returns a TextFormField, is there a way to pass the onSaved(value) to another widget that needs to be updated when onSaved is called? I think i am almost there with this code, i just get an error when i add the (value) to the class

  class InputName extends StatefulWidget {
  final TextEditingController controller;
   
  final Function(value)? onSaved;
  //this is where i get the error "Undefined class 'value' "

  const InputName({Key? key, required this.controller, this.onSaved}) : super(key: key);

  @override
  State<InputName> createState() => _InputNameState();
}

class _InputNameState extends State<InputName> {
  @override
  Widget build(BuildContext context) {  //inputNameWidget
    return Padding(
      padding: const EdgeInsets.only(left: 16.0, right: 16),
      child: TextFormField(
        keyboardType: TextInputType.text,
        controller: widget.controller,
        style: TextStyle(fontSize: 20, height: 0.6),
        validator: (value) {
          if(value!.isEmpty ){
            return 'Please enter a name';
          }else{
            return null;
          }},
        
        onSaved: (value){
          widget.onSaved?.call(value);
        }

      ),
    );
  }

and the pass the value to the other widget:

InputName(controller: _nameController,
                       onSaved: (value){
                            _categoryName = value!;
                            },

            ),

Update

  class InputName extends StatefulWidget {
  final TextEditingController controller;
  final Function(String)? onSaved;
  final Function(String)? validator;

  const InputName({Key? key, required this.controller,  this.onSaved, this.validator}) : super(key: key);

 //then-->
 validator: (value){
      widget.validator;
    },
    onSaved: (value){
      widget.onSaved;
    }

 //my other widget class
  InputName(
     controller: _nameController,
                onSaved: (value) {
                  _categoryName = value;
                },
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter a name';
                  } else {
                    return null;
                  }
                }),

CodePudding user response:

Change your InputName class to this:

class InputName extends StatefulWidget {
  final TextEditingController controller;
  final String? Function(String?)? validator; //<--- change this
  final Function(String?)? onSaved;//<--- change this

  const InputName({Key? key, required this.controller, this.onSaved, this.validator})
      : super(key: key);

  @override
  State<InputName> createState() => _InputNameState();
}

and also change onSaved and validator in your _InputNameState class:

onSaved: widget.onSaved,
validator: widget.validator,
  • Related