buildWidget method

  1. @override
Widget buildWidget(
  1. BuildContext context
)
override

build your widget here

Implementation

@override
Widget buildWidget(BuildContext context) {
  InputDecoration decoration = inputDecoration;
  if (widget._controller.floatLabel == true) {
    decoration = decoration.copyWith(
      labelText: widget._controller.label,
    );
  }
  if (widget._controller.errorStyle != null) {
    decoration = decoration.copyWith(
      errorStyle: widget._controller.errorStyle,
    );
  }

  // for password, show the toggle plain text/obscure text
  if ((widget.isPassword() || widget._controller.obscureText == true) &&
      widget._controller.obscureToggle == true) {
    void toggleObscured() {
      bool newObscuredValue = !(widget._controller.obscured ?? true);
      widget._controller.obscured = newObscuredValue;
      widget.setProperty('obscured', newObscuredValue);
      setState(() {});
    }

    decoration = decoration.copyWith(
        suffixIcon: widget._controller.obscureTextWidget != null
            ? GestureDetector(
                onTap: toggleObscured,
                child: scopeManager!.buildWidgetFromDefinition(
                    widget._controller.obscureTextWidget),
              )
            : IconButton(
                icon: Icon(
                  widget._controller.obscured ?? true
                      ? Icons.visibility
                      : Icons.visibility_off,
                  size: ThemeManager().getInputIconSize(context).toDouble(),
                  color: ThemeManager().getInputIconColor(context),
                ),
                onPressed: toggleObscured,
              ));
  } else if (!widget.isPassword() &&
      widget.textController.text.isNotEmpty &&
      widget._controller.enableClearText == true) {
    decoration = decoration.copyWith(
      suffixIcon: IconButton(
        onPressed: _clearSelection,
        icon: const Icon(Icons.close),
      ),
    );
  }

  // Add ending widget if provided
  decoration = InputFieldHelper.addEndingWidget(
      decoration, widget.controller.endingWidget, scopeManager);

  return InputWrapper(
    type: TextInput.type,
    controller: widget._controller,
    widget: InputFieldHelper.createTextFormField(
      key: validatorKey,
      controller: widget.textController,
      focusNode: focusNode,
      validateOnUserInteraction: widget._controller.validateOnUserInteraction,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return widget._controller.required
              ? Utils.translateWithFallback(
                  'ensemble.input.required',
                  widget._controller.requiredMessage ??
                      'This field is required')
              : null;
        }

        // First we're using the validator to validate the TextInput Field
        if (widget._controller.validator != null) {
          ValidationBuilder? builder;
          if (widget._controller.validator?.minLength != null) {
            builder = ValidationBuilder().minLength(
                widget._controller.validator!.minLength!,
                Utils.translateOrNull(
                    'ensemble.input.validation.minimumLength'));
          }
          if (widget._controller.validator?.maxLength != null) {
            builder = (builder ?? ValidationBuilder()).maxLength(
                widget._controller.validator!.maxLength!,
                Utils.translateOrNull(
                    'ensemble.input.validation.maximumLength'));
          }
          if (widget._controller.validator?.regex != null) {
            builder = (builder ?? ValidationBuilder()).regExp(
                RegExp(widget._controller.validator!.regex!),
                widget._controller.validator!.regexError ??
                    Utils.translateWithFallback(
                        'ensemble.input.validation.invalidInput',
                        'This field has invalid value'));
          }
          if (builder != null) {
            return builder.build().call(value);
          }
        }

        // If validator is null, we can use our own validation based on the InputType
        // only applicable for TextInput
        if (!widget.isPassword()) {
          if (widget._controller.inputType == InputType.email.name) {
            if (!EmailValidator.validate(value)) {
              return Utils.translateWithFallback(
                  'ensemble.input.validation.invalidEmailType',
                  'Please enter a valid email address');
            }
          } else if (widget._controller.inputType ==
              InputType.ipAddress.name) {
            if (!InputValidator.ipAddress(value)) {
              return Utils.translateWithFallback(
                  'ensemble.input.validation.invalidIPAddressType',
                  'Please enter a valid IP Address');
            }
          } else if (widget._controller.inputType == InputType.phone.name) {
            if (!InputValidator.phone(value)) {
              return Utils.translateWithFallback(
                  'ensemble.input.validation.invalidPhoneType',
                  "Please enter a valid Phone Number");
            }
          }
        }
        return null;
      },
      inputFormatters: _inputFormatter,
      multiline: widget._controller.multiline,
      minLines: widget._controller.minLines,
      maxLines: widget._controller.maxLines,
      maxLength: widget._controller.maxLength,
      maxLengthEnforcement: widget._controller.maxLengthEnforcement,
      enabled: isEnabled(),
      readOnly: widget._controller.readOnly,
      selectable: widget._controller.selectable,
      onTap: () => showOverlay(context),
      onTapOutside: (_) => removeOverlayAndUnfocus(),
      onFieldSubmitted: (value) => widget.controller.submitForm(context),
      onChanged: (String txt) {
        // If text suddenly increased by more than one character,
        // it could indicate a paste operation
        if (kIsWeb) {
          if (txt != previousText &&
              (txt.length > previousText.length + 1 ||
                  previousText.length > txt.length + 1) &&
              !widget._controller.selectable) {
            widget.textController.text = previousText;
            // Safe text selection with error handling
            TextSelectionHelper.safeSetSelectionFromPosition(
              widget.textController,
              previousText.length,
              usePostFrame: false,
            );
            // Early return to prevent further processing
            return;
          }
        }
        if (txt != previousText) {
          // for performance reason, we dispatch onChange (as well as binding to value)
          // upon EditingComplete (select Done on virtual keyboard) or Focus Out
          didItChange = true;
          previousText = widget.textController.text;

          // we dispatch onKeyPress here
          if (widget._controller.onKeyPress != null) {
            ScreenController().executeAction(
                context, widget._controller.onKeyPress!,
                event: EnsembleEvent(widget));
          }

          if (widget._controller.onDelayedKeyPress != null) {
            InputFieldHelper.executeDelayedAction(
                context,
                widget._controller.onDelayedKeyPress!,
                widget,
                getKeyPressDebouncer());
          }
        }
        setState(() {});
      },
      textStyle: isEnabled()
          ? widget._controller.textStyle
          : widget._controller.textStyle?.copyWith(
              color: Theme.of(context).disabledColor,
            ),
      autofillHints: widget._controller.autofillHints,
      decoration: decoration,
      keyboardAction: widget._controller.keyboardAction,
      keyboardType: widget.keyboardType,
      obscureText: isObscureOrPlainText(),
      enableSuggestions: !widget.isPassword(),
      autocorrect: !widget.isPassword(),
    ),
  );
}