Home > Software design >  How to reach results of a function from another file (TextEditingController, ElevatedButton)
How to reach results of a function from another file (TextEditingController, ElevatedButton)

Time:12-29

I have two files, in the first are a few TextformFields and in the second are buttons. I wanna disable the button when one of the TextformFields is empty.

File 1:

class FormTextState extends State<FormText>{

final TextEditingController inputController1 = TextEditingController();
final TextEditingController inputController2 = TextEditingController();
final TextEditingController inputController3 = TextEditingController();
bool submit1 = false;
bool submit2 = false;
bool submit3 = false;

@override
void initState(){
  super.initState();
  inputController1.addListener(() { setState(() {
    submit1 = inputController1.text.isNotEmpty;
  });
  });

  inputController2.addListener(() { setState(() {
    submit2 = inputController2.text.isNotEmpty;
  });
  });

  inputController3.addListener(() { setState(() {
    submit3 = inputController3.text.isNotEmpty;
  });
  });
}

@override
void dispose(){
  inputController1.dispose();
  inputController2.dispose();
  inputController3.dispose();
  super.dispose();

[...]

}

For each TextFormField the controller is defined as following:

TextFormField(
controller: inputController1,

If I would create the button directly in this file, everything works fine like that:

ElevatedButton(
    onPressed: submit1 && submit2 && submit3 ? () => doSomething() : null,

How can I reach this result from the other file with the buttons? The submit values are not reachable. I imported the file at the beginning, of course.

CodePudding user response:

You could add a function to your class like:

class FormTextState extends State<FormText>{
final Function(String str) stringHandler;

...

and when creating the class

FormTextState(stringHandler: _handler);

Future<void> _handler(String str) async {
print(str);
}

CodePudding user response:

you nee to use the following porperties

 autovalidateMode: AutovalidateMode.onUserInteraction


onChanged: (val) {
                if (formKey.currentState?.validate() == true) {
                  BlocProvider.of<MyDataBloc>(context)
                      .add(ActivateButtonEvent());
                } else {
                  BlocProvider.of<MyDataBloc>(context)
                      .add(DeActivateButtonEvent());
                }
              },

this will work for formtextfield in case that you are using bloc

  • Related