skip to Main Content

Hi fellas Im new in Flutter/Dart Programming. Im trying to build an app that includes dynamic TextFormField. Validator does not returning text in the screen. Could you give me an explanation so i could build my app in the correct way.


import 'package:camework/global/styles.dart';
import 'package:camework/repos/surveyRepo/surveyRepo.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../../../global/appLocatizations.dart';


class DefaultQuestion extends StatefulWidget {
  const DefaultQuestion({Key? key}) : super(key: key);

  @override
  State<DefaultQuestion> createState() => _DefaultQuestionState();
}

class _DefaultQuestionState extends State<DefaultQuestion> {
  TextEditingController surveyTextController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    SurveyRepo surveyRepo = Provider.of<SurveyRepo>(context);
    var questionType = surveyRepo.surveyQuestion!.questionType!.mask!;
    return TextFormField(
      decoration: ProjectStyles.textFieldDecoration(null, null, null),
      keyboardType: keyboardType(questionType),
      inputFormatters: [inputFormat(questionType)],
      autofocus: true,
      onChanged: (String? value) {
        if (value != null && value != "") {
          setState(() {
            surveyTextController.text = value;
            surveyRepo.textQuestionTrigger(value);
          });
        }
      },
      key: _formKey,
      validator: (value) {
        if (value != null) {
          if (value.isEmpty) {

`THIS IS NOT WORKING`

            return AppLocalizations.of(context)!.translate("thisFieldCannotBeEmpty");
          }
        }
      },
      controller: surveyTextController,
    );
  }
}

`

2

Answers


  1. You can use a validator using the validator property.

    Like that

    TextFormField(
    validator: EmailValidator(errorText: ‘enter a valid email address’)
    );

    Login or Signup to reply.
  2. _formKey is used for the key of Form Widget. Not for the TextFormField.

    see example from documentation : https://docs.flutter.dev/cookbook/forms/validation

    return Form(
      key: _formKey, // <= Use here
      child: TextFormField(
        // rest of property
        //...
        validator : (val) {
         // your  function for validation
        }
      )
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search