Skip to content

Conversation

omaralmgerbie
Copy link
Contributor

@omaralmgerbie omaralmgerbie commented Aug 11, 2025

This pull request introduces enhancements to the form field components, particularly improving the management and validation of errors programmatically. It also adds a new test to ensure that programmatically set errors are correctly displayed in the UI. Additionally, it includes a minor improvement to the date picker button's theming.

Form field error handling improvements:

  • Added support for programmatically setting and clearing custom error messages in ShadFormBuilderFieldState via a new _customErrorText property and invalidate method. The error state now considers both validation and custom errors, and new getters (errorText, hasError, isValid, valueIsValid, valueHasError) provide more granular state information. The validate method can optionally clear custom errors, and reset now clears custom errors as well. [1] [2] [3]

Testing enhancements:

  • Added a widget test in input_test.dart to verify that programmatically setting an error on ShadInputFormField displays the correct error UI, matching a golden file. [1] [2]

UI theming improvements:

  • Updated ShadDatePicker to use the theme's button decoration as a fallback if none is provided, ensuring more consistent styling.

Pre-launch Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • I read and followed the Flutter Style Guide.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///).
  • I added new tests to check the change I am making.
  • I followed the Data Driven Fixes where supported.
  • All existing and new tests are passing.

If you need help, consider asking for advice on Discord.

Summary by CodeRabbit

  • New Features
    • Programmatic control of form-field errors: set/clear custom error text, new getters for combined validity/error state; UI displays validation or custom errors.
  • Refactor
    • Date picker button styling now falls back to the theme’s button decoration when none is provided.
  • Tests
    • Added golden test verifying programmatic error display for input form fields.

No breaking API changes; existing behavior remains compatible.

Copy link
Contributor

coderabbitai bot commented Aug 11, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Button decoration in the date picker now falls back to the theme when not provided. ShadFormBuilderFieldState gains programmatic custom-error support (new getters, invalidate, validate behavior, reset clears custom error). A golden test was added to assert programmatic error display for ShadInputFormField.

Changes

Cohort / File(s) Summary
Date Picker Theme Fallback
lib/src/components/date_picker.dart
Button decoration now resolves to widget.buttonDecoration ?? theme.datePickerTheme.buttonDecoration; explicit prop still takes precedence. No public API signature changes.
Form Field Programmatic Errors
lib/src/components/form/field.dart
Adds private _customErrorText with public getters (errorText, hasError, isValid, valueIsValid, valueHasError), invalidate(String, {bool revalidate = true}), updated validate({bool clearCustomError = true}), and reset() clears the custom error.
Golden Test for Programmatic Error
test/src/components/input_test.dart
Adds a test that uses a GlobalKey<ShadFormBuilderFieldState<...>> to call invalidate('This field is required'), asserts UI via goldens/input_error.png, and checks state (hasError, errorText, isValid, valueIsValid). New form-related imports added.

Sequence Diagram(s)

sequenceDiagram
  actor App as App/Test
  participant Field as ShadFormBuilderFieldState
  participant Base as Base Validation Logic

  App->>Field: invalidate("This field is required")
  Field->>Field: _customErrorText = "This field is required"
  opt revalidate
    Field->>Base: validate()
    Base-->>Field: baseError/baseValid
  end
  Field-->>App: hasError/errorText reflect composite state

  App->>Field: validate(clearCustomError: true)
  alt clearCustomError == true
    Field->>Field: _customErrorText = null
  end
  Field->>Base: validate()
  Base-->>Field: baseError/baseValid
  Field-->>App: returns (baseValid && _customErrorText == null)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • nank1ro

Poem

I twitch my ears at errors bold,
A tiny carrot message told—
Invalidate, then check again,
Theme-clad buttons, code and pen.
Hop along — the form's not cold. 🥕✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c118203 and 1420615.

📒 Files selected for processing (2)
  • lib/src/components/form/field.dart (3 hunks)
  • test/src/components/input_test.dart (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/src/components/input_test.dart
  • lib/src/components/form/field.dart
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Flutter test
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@omaralmgerbie omaralmgerbie marked this pull request as ready for review August 11, 2025 22:50
@Copilot Copilot AI review requested due to automatic review settings August 11, 2025 22:50
@omaralmgerbie
Copy link
Contributor Author

PR is finished and ready for review.

Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This pull request enhances form field validation by adding support for programmatic error management alongside existing validation errors. It allows developers to set custom error messages on form fields and provides better granular control over error states.

  • Added programmatic error management to ShadFormBuilderFieldState with custom error text support and new validation methods
  • Introduced comprehensive test coverage for programmatic error functionality in input form fields
  • Improved date picker theming to use fallback button decoration from theme

Reviewed Changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 2 comments.

File Description
lib/src/components/form/field.dart Enhanced form field state with programmatic error handling, custom error text management, and improved validation methods
test/src/components/input_test.dart Added widget test to verify programmatic error display functionality with golden file comparison
lib/src/components/date_picker.dart Updated date picker to use theme's button decoration as fallback when none provided

if (clearCustomError) {
setState(() => _customErrorText = null);
}
final isValid = super.validate() && !hasError;
Copy link
Preview

Copilot AI Aug 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The validation logic creates a circular dependency. The hasError getter includes both validation errors and custom errors, so this line will always return false when _customErrorText is set, even if the field value itself is valid. Consider using super.validate() && _customErrorText == null instead.

Suggested change
final isValid = super.validate() && !hasError;
final isValid = super.validate() && _customErrorText == null;

Copilot uses AI. Check for mistakes.


validate(
clearCustomError: false,
);
Copy link
Preview

Copilot AI Aug 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Calling validate() inside invalidate() seems counterintuitive since the purpose is to set an error, not validate. This call with clearCustomError: false appears unnecessary and may cause confusion. Consider removing this call or clarifying its purpose with a comment.

Suggested change
);

Copilot uses AI. Check for mistakes.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
lib/src/components/form/field.dart (4)

160-165: Doc nit: clarify and tighten wording for errorText

Minor wording tweak for clarity.

-/// Returns the current error text,
-/// As it might be validation error or programmatically set.
+/// Returns the current error text.
+/// It may come from validation or be set programmatically.

166-170: Simplify hasError check to avoid redundant getter usage

errorText != null is sufficient but calls the getter; prefer a direct check to avoid recomputation.

-bool get hasError => super.hasError || errorText != null;
+bool get hasError => super.hasError || _customErrorText != null;

235-243: Defaulting validate() to clear custom errors may be surprising; consider default=false

Calling Form.of(context).validate() will (by default) clear programmatic errors before validating, which may not be what consumers expect. Recommend not clearing custom errors unless explicitly requested.

-bool validate({
-  bool clearCustomError = true,
-}) {
-  if (clearCustomError) {
-    setState(() => _customErrorText = null);
-  }
+bool validate({
+  bool clearCustomError = false,
+}) {
+  if (clearCustomError && _customErrorText != null) {
+    setState(() => _customErrorText = null);
+  }
   final isValid = super.validate() && !hasError;
   return isValid;
}

If the current default is intentional, please confirm the desired behavior for ShadForm.of(context)?.validate() so we can document it accordingly.


246-253: Consider a convenience clear method and optional revalidation control

invalidate both sets the error and revalidates. Two enhancements:

  • Add a clearCustomError() helper.
  • Optionally allow skipping revalidation to avoid a second setState when not needed.

Add a helper method (outside the selected range):

void clearCustomError() {
  if (_customErrorText != null) {
    setState(() => _customErrorText = null);
  }
}

Optionally extend invalidate:

-void invalidate(String errorText) {
-  setState(() => _customErrorText = errorText);
-
-  validate(
-    clearCustomError: false,
-  );
-}
+void invalidate(String errorText, {bool revalidate = true}) {
+  setState(() => _customErrorText = errorText);
+  if (revalidate) {
+    validate(clearCustomError: false);
+  }
+}
test/src/components/input_test.dart (1)

31-60: Programmatic error golden — LGTM; add state assertions for robustness

The golden covers UI; adding state assertions improves test intent and detects regressions even if goldens drift.

       // Programmatically set an error on the field
       key.currentState!.invalidate('This field is required');
       await tester.pumpAndSettle();

+      // Sanity-check state to catch regressions beyond the golden image.
+      expect(key.currentState!.hasError, isTrue);
+      expect(key.currentState!.errorText, 'This field is required');
+      expect(key.currentState!.isValid, isFalse);
+      // Base value has no validator in this test, so valueIsValid should be true.
+      expect(key.currentState!.valueIsValid, isTrue);

       expect(
         find.byType(ShadInputFormField),
         matchesGoldenFile('goldens/input_error.png'),
       );

Optional follow-ups:

  • Add a test that reset() clears the programmatic error.
  • Add a test that clarifies validate(clearCustomError: X) behavior, especially what happens when Form.of(context)!.validate() is called without args.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf6bc32 and c118203.

⛔ Files ignored due to path filters (1)
  • test/src/components/goldens/input_error.png is excluded by !**/*.png
📒 Files selected for processing (3)
  • lib/src/components/date_picker.dart (1 hunks)
  • lib/src/components/form/field.dart (3 hunks)
  • test/src/components/input_test.dart (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-05-13T09:57:53.516Z
Learnt from: nank1ro
PR: nank1ro/flutter-shadcn-ui#352
File: docs/src/content/docs/index.md:129-135
Timestamp: 2025-05-13T09:57:53.516Z
Learning: The shadcn_ui package uses `WidgetStatePropertyAll` in theme configurations (such as `ScrollbarThemeData`) instead of Flutter's native `MaterialStatePropertyAll`. This is intentional and correct according to the package maintainer.

Applied to files:

  • lib/src/components/date_picker.dart
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Flutter test
🔇 Additional comments (6)
lib/src/components/date_picker.dart (1)

1165-1166: Theme fallback for button decoration — LGTM

Using the theme’s datePickerTheme.buttonDecoration when widget.buttonDecoration is null aligns with the rest of the theming strategy and keeps behavior consistent.

lib/src/components/form/field.dart (4)

137-137: Private custom error store — LGTM

Introducing _customErrorText as the single source of truth for programmatic errors is clear and contained.


171-175: isValid override — LGTM

Combining base validity with absence of custom error is correct and expected.


176-181: Expose base-only validity/error — LGTM

valueIsValid/valueHasError cleanly separate base validator results from programmatic error state.


223-226: reset clears custom error — LGTM

Clearing _customErrorText on reset is consistent. Thanks for guarding setState behind a null check.

test/src/components/input_test.dart (1)

5-7: Imports for form field testing — LGTM

@omaralmgerbie
Copy link
Contributor Author

@nank1ro, the PR is ready. Could you please review it? 😇🙏

Copy link
Owner

@nank1ro nank1ro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @omaralmgerbie 🙏 however it is completely useless now that we have forceErrorText

ShadInputFormField(
   forceErrorText: 'Forced error text',
   ...
),

Feel free to close it if you agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants