skip to Main Content

Using forms, I want to create a reusable TextFormField but I don’t get the Save value on my Main widget. I don’t want write same style for every TextFormField and which will make the page lengthy so I decided to create a widget and call it where needed.

Reusable TextFormField Code

    class AuthTextfields extends StatelessWidget {
  const AuthTextfields(
      {super.key,
      required this.inputType,
      required this.autoCorrect,
      required this.enableSuggestion,
      required this.labTxt,
      required this.iconData,
      required this.saveTxt,
      required this.vaildCheck,
      required this.formGlobal});

  final TextInputType inputType;
  final bool autoCorrect;
  final bool enableSuggestion;
  final String labTxt;
  final IconData iconData;
  final String Function(String vaildTxt) vaildCheck;
  final void Function(String txt) saveTxt;
  final Key formGlobal;

  @override
  Widget build(BuildContext context) {
    return Form(
      key: formGlobal,
      child: TextFormField(
        style: TextStyle(color: Colors.white),
        keyboardType: inputType,
        autocorrect: autoCorrect,
        enableSuggestions: enableSuggestion,
        decoration: InputDecoration(
            labelText: labTxt,
            border: const OutlineInputBorder(),
            prefixIcon: Icon(
              iconData,
              color: Theme.of(context).colorScheme.primary,
            )),
        validator: (value) {
          return vaildCheck(value!);
        },
        onSaved: (newValue) => saveTxt(newValue!),
      ),
    );
  }
}

Try to getting the Data by below code:

  final formGlobal = GlobalKey<FormState>();
  String userName = "";

AuthTextfields(
        inputType: TextInputType.name,
        autoCorrect: false,
        enableSuggestion: false,
        labTxt: "User Name",
        iconData: Icons.account_circle_rounded,
        vaildCheck: (value) {
          if (value == "" ||
              value.trim().isEmpty ||
              value.trim().length < 3) {
            return "Please add A Valid Name with at least 3 Character";
          }
          return "";
        },
        formGlobal: formGlobal,
        saveTxt: (String txt) {
          setState(() {
            userName == txt;
          });
        },
      ),
      const Gap(20),
      ElevatedButton.icon(
        onPressed: () {
          final isValid = formGlobal.currentState!.validate();
          FocusScope.of(context).unfocus();

          if (!isValid) {
            return;
          }
          formGlobal.currentState!.save;
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text("hello$userName")));
        },
        label: const Text("Save"),
      ),

Why ScaffoldMessenger can’t show the value I input on TextField?

2

Answers


  1. Change the value assignment while set your username in AuthTextfields saveTxt code.

    Your code is:

    saveTxt: (String txt) {
      setState(() {
        userName == txt;
      });
    },
    

    Change the code using the assignment keyword (=). Not the equal to operator (==). Like below:

    saveTxt: (String txt) {
      setState(() {
        userName = txt;
      });
    },
    

    Hopefully it can solve your problem, Thanks 😉

    Login or Signup to reply.
  2. Here are some fixes and improvements for your Flutter code:

    1. Fixing the saveTxt Callback: In the saveTxt callback of AuthTextfields, you are using the equality operator (==) instead of the assignment operator (=) to update the userName. Also, make sure to call setState to update the state of your widget tree.

    2. Correctly Calling save in the Form: You need to call the save method on the form key (formGlobal.currentState!.save()), not just accessing it directly.

    Here’s the updated code with these fixes:

    onPressed: () {
    final isValid = formGlobal.currentState!.validate();
    FocusScope.of(context).unfocus();
    
    if (!isValid) {
      return;
    }
    formGlobal.currentState!.save(); // Correctly calling the 'save' method
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text("Hello $userName")));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search