# Accessibility
Source: https://docs.thehuxdesign.com/advanced/accessibility
Making your Hux UI applications accessible to all users
## Overview
Hux UI is built with accessibility in mind, featuring WCAG AA compliance and best practices for inclusive design.
## Built-in Accessibility Features
* **WCAG AA Contrast** - Automatic contrast calculation ensures 4.5:1 contrast ratios
* **HuxWCAG Utilities** - Public API for WCAG 2.1 compliant contrast calculations in custom components
* **Semantic Roles** - Proper ARIA roles and labels for screen readers
* **Keyboard Navigation** - Full keyboard support for all interactive components
* **Focus Management** - Visible focus indicators and logical tab order
## WCAG Utilities
Hux UI provides the `HuxWCAG` utility class for WCAG 2.1 compliant contrast calculations. All Hux components use these utilities internally, but they're also available for your custom components.
Learn how to use HuxWCAG utilities for accessible custom components
## Best Practices
* Always provide meaningful labels for form inputs
* Use semantic colors (success, destructive) appropriately
* Test with screen readers and keyboard navigation
* Ensure sufficient color contrast ratios using `HuxWCAG` utilities for custom components
* Use `HuxWCAG.meetsContrastAA()` to validate color combinations before applying them
# Customization
Source: https://docs.thehuxdesign.com/advanced/customization
Advanced customization techniques for Hux UI components
## Overview
Learn advanced customization techniques for modifying Hux UI components beyond the standard theming system. This guide covers component wrapping, style overrides, composition patterns, and creating custom variants.
## Component Wrapping
### Wrapping with Decorators
Wrap Hux components with additional styling or behavior:
```dart theme={null}
// Add custom shadow and border
Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
offset: Offset(0, 4),
),
],
borderRadius: BorderRadius.circular(12),
),
child: HuxButton(
onPressed: () {},
child: Text('Wrapped Button'),
),
)
```
### Custom Padding and Margins
Add custom spacing around components:
```dart theme={null}
Padding(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: HuxInput(
label: 'Email',
hint: 'Enter your email',
),
)
```
## Style Overrides
### Using Theme Extensions
Override component styles through theme extensions:
```dart theme={null}
final customTheme = HuxTheme.lightTheme.copyWith(
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
);
```
### Custom Color Overrides
Override colors on individual components:
```dart theme={null}
HuxButton(
onPressed: () {},
primaryColor: Colors.deepPurple,
child: Text('Custom Color'),
)
HuxBadge(
label: 'New',
variant: HuxBadgeVariant.primary,
// Custom styling through theme tokens
)
```
## Composition Patterns
### Building Custom Components
Create reusable components by composing Hux UI components:
```dart theme={null}
class CustomActionButton extends StatelessWidget {
final String label;
final IconData icon;
final VoidCallback onPressed;
final bool isDestructive;
const CustomActionButton({
required this.label,
required this.icon,
required this.onPressed,
this.isDestructive = false,
});
@override
Widget build(BuildContext context) {
return HuxButton(
onPressed: onPressed,
variant: isDestructive
? HuxButtonVariant.outline
: HuxButtonVariant.primary,
icon: icon,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 18),
SizedBox(width: 8),
Text(label),
],
),
);
}
}
```
### Custom Form Fields
Create specialized input components:
```dart theme={null}
class EmailInput extends StatelessWidget {
final String? label;
final String? hint;
final ValueChanged? onChanged;
final String? Function(String?)? validator;
const EmailInput({
this.label,
this.hint,
this.onChanged,
this.validator,
});
@override
Widget build(BuildContext context) {
return HuxInput(
label: label ?? 'Email',
hint: hint ?? 'Enter your email address',
prefixIcon: Icon(LucideIcons.mail),
keyboardType: TextInputType.emailAddress,
onChanged: onChanged,
validator: validator ?? (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!value.contains('@')) {
return 'Please enter a valid email';
}
return null;
},
);
}
}
```
## Custom Variants
### Creating Button Variants
Extend button functionality with custom variants:
```dart theme={null}
class CustomButton extends StatelessWidget {
final VoidCallback? onPressed;
final Widget child;
final bool isGradient;
const CustomButton({
required this.onPressed,
required this.child,
this.isGradient = false,
});
@override
Widget build(BuildContext context) {
if (isGradient) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.purple],
),
borderRadius: BorderRadius.circular(8),
),
child: HuxButton(
onPressed: onPressed,
variant: HuxButtonVariant.ghost,
child: child,
),
);
}
return HuxButton(
onPressed: onPressed,
child: child,
);
}
}
```
### Custom Card Variants
Create specialized card components:
```dart theme={null}
class StatCard extends StatelessWidget {
final String title;
final String value;
final IconData icon;
final Color? color;
const StatCard({
required this.title,
required this.value,
required this.icon,
this.color,
});
@override
Widget build(BuildContext context) {
return HuxCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
title,
style: TextStyle(
color: HuxTokens.textSecondary(context),
fontSize: 14,
),
),
Icon(
icon,
color: color ?? HuxTokens.primary(context),
size: 20,
),
],
),
SizedBox(height: 8),
Text(
value,
style: TextStyle(
color: HuxTokens.textPrimary(context),
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
],
),
);
}
}
```
## Advanced Styling
### Custom Animations
Add custom animations to components:
```dart theme={null}
class AnimatedButton extends StatefulWidget {
final VoidCallback? onPressed;
final Widget child;
const AnimatedButton({
required this.onPressed,
required this.child,
});
@override
_AnimatedButtonState createState() => _AnimatedButtonState();
}
class _AnimatedButtonState extends State
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation _scale;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 100),
);
_scale = Tween(begin: 1.0, end: 0.95).animate(_controller);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => _controller.forward(),
onTapUp: (_) {
_controller.reverse();
widget.onPressed?.call();
},
onTapCancel: () => _controller.reverse(),
child: ScaleTransition(
scale: _scale,
child: HuxButton(
onPressed: widget.onPressed,
child: widget.child,
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
```
### Conditional Styling
Apply styles based on state or conditions:
```dart theme={null}
HuxButton(
onPressed: () {},
variant: isActive
? HuxButtonVariant.primary
: HuxButtonVariant.outline,
primaryColor: isActive
? Colors.green
: null,
child: Text(isActive ? 'Active' : 'Inactive'),
)
```
## Best Practices
Prefer wrapping and composing components rather than modifying their internals:
```dart theme={null}
// ✅ Good - Composition
Container(
decoration: BoxDecoration(...),
child: HuxButton(...),
)
// ❌ Avoid - Modifying internal implementation
```
Create reusable wrapper components for common patterns:
```dart theme={null}
// Create once, use everywhere
class PrimaryActionButton extends StatelessWidget {
// Custom implementation
}
```
Always use HuxTokens for colors to maintain theme consistency:
```dart theme={null}
// ✅ Good
color: HuxTokens.textPrimary(context)
// ❌ Avoid
color: Colors.black
```
Maintain accessibility when customizing:
```dart theme={null}
// Ensure proper contrast ratios
// Use semantic colors from HuxTokens
// Maintain keyboard navigation
```
## Examples
See how to compose multiple Hux components
Learn to create custom component variants
Basic theming and design tokens
Deep dive into advanced theming
# Advanced Theming
Source: https://docs.thehuxdesign.com/advanced/theming
Deep dive into advanced theming techniques and customization
## Overview
Advanced theming techniques for power users who want to deeply customize Hux UI themes and create complex design systems. This guide covers Material 3 seed colors, custom theme extensions, brand-specific themes, and advanced token usage.
For basic theming, see the [Theming guide](/theming).
## Material 3 Seed Colors
### Using Seed Colors
Hux UI automatically detects and respects Material 3 seed colors, enabling full Material 3 theming integration:
```dart theme={null}
MaterialApp(
theme: HuxTheme.lightTheme.copyWith(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
),
darkTheme: HuxTheme.darkTheme.copyWith(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.dark,
),
),
home: MyApp(),
)
```
### Custom Seed Color Integration
All Hux components automatically use the custom seed color when provided:
```dart theme={null}
// Buttons, charts, toggles, and other components
// automatically use the seed color
HuxButton(
onPressed: () {},
child: Text('Uses seed color'),
// No need to specify primaryColor - uses seed automatically
)
HuxChart.line(
data: chartData,
xField: 'x',
yField: 'y',
// Automatically uses seed color
)
```
## Custom Theme Extensions
### Creating Theme Extensions
Extend Hux themes with custom properties:
```dart theme={null}
// Define custom theme extension
@immutable
class CustomColors extends ThemeExtension {
final Color brandPrimary;
final Color brandSecondary;
final Color accent;
const CustomColors({
required this.brandPrimary,
required this.brandSecondary,
required this.accent,
});
@override
ThemeExtension copyWith({
Color? brandPrimary,
Color? brandSecondary,
Color? accent,
}) {
return CustomColors(
brandPrimary: brandPrimary ?? this.brandPrimary,
brandSecondary: brandSecondary ?? this.brandSecondary,
accent: accent ?? this.accent,
);
}
@override
ThemeExtension lerp(
ThemeExtension? other,
double t,
) {
if (other is! CustomColors) return this;
return CustomColors(
brandPrimary: Color.lerp(brandPrimary, other.brandPrimary, t)!,
brandSecondary: Color.lerp(brandSecondary, other.brandSecondary, t)!,
accent: Color.lerp(accent, other.accent, t)!,
);
}
}
// Use in your app
final customTheme = HuxTheme.lightTheme.copyWith(
extensions: [
CustomColors(
brandPrimary: Colors.blue,
brandSecondary: Colors.blueAccent,
accent: Colors.orange,
),
],
);
```
### Accessing Theme Extensions
Use custom theme extensions in your widgets:
```dart theme={null}
class CustomWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final customColors = Theme.of(context).extension();
return Container(
color: customColors?.brandPrimary ?? Colors.blue,
child: Text('Custom themed content'),
);
}
}
```
## Brand-Specific Themes
### Creating Brand Themes
Create complete brand-specific theme configurations:
```dart theme={null}
class BrandTheme {
static ThemeData get lightTheme {
return HuxTheme.lightTheme.copyWith(
colorScheme: ColorScheme.fromSeed(
seedColor: Color(0xFF1E40AF), // Brand blue
brightness: Brightness.light,
),
appBarTheme: AppBarTheme(
backgroundColor: Color(0xFF1E40AF),
foregroundColor: Colors.white,
elevation: 0,
),
cardTheme: CardTheme(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
);
}
static ThemeData get darkTheme {
return HuxTheme.darkTheme.copyWith(
colorScheme: ColorScheme.fromSeed(
seedColor: Color(0xFF3B82F6), // Lighter brand blue for dark
brightness: Brightness.dark,
),
appBarTheme: AppBarTheme(
backgroundColor: Color(0xFF1E3A8A),
foregroundColor: Colors.white,
elevation: 0,
),
);
}
}
```
### Multi-Brand Support
Support multiple brands in a single app:
```dart theme={null}
enum AppBrand { primary, secondary, enterprise }
class ThemeManager {
static ThemeData getTheme(AppBrand brand, bool isDark) {
switch (brand) {
case AppBrand.primary:
return isDark ? BrandTheme.darkTheme : BrandTheme.lightTheme;
case AppBrand.secondary:
return isDark ? SecondaryBrandTheme.darkTheme : SecondaryBrandTheme.lightTheme;
case AppBrand.enterprise:
return isDark ? EnterpriseTheme.darkTheme : EnterpriseTheme.lightTheme;
}
}
}
```
## Advanced Token Usage
### Custom Token Functions
Create helper functions for complex token combinations:
```dart theme={null}
class CustomTokens {
/// Get a gradient color based on theme
static List getGradientColors(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return isDark
? [HuxColors.black, HuxColors.black90]
: [HuxColors.white, HuxColors.black5];
}
/// Get shadow color with proper opacity
static Color getShadowColor(BuildContext context) {
return HuxTokens.textPrimary(context).withOpacity(0.1);
}
/// Get border color for focused state
static Color getFocusedBorderColor(BuildContext context) {
return HuxTokens.primary(context);
}
}
```
### Dynamic Token Calculation
Calculate tokens based on runtime values:
```dart theme={null}
class AdaptiveTokens {
/// Get text color that adapts to background brightness
static Color getAdaptiveTextColor(
BuildContext context,
Color backgroundColor,
) {
// Use HuxWCAG for contrast calculation
return HuxWCAG.getContrastingTextColor(
backgroundColor: backgroundColor,
context: context,
);
}
/// Get surface color with custom opacity
static Color getSurfaceWithOpacity(
BuildContext context,
double opacity,
) {
final baseColor = HuxTokens.surfacePrimary(context);
return baseColor.withOpacity(opacity);
}
}
```
## Theme Inheritance
### Extending Base Themes
Create theme variations by extending base themes:
```dart theme={null}
class CompactTheme {
static ThemeData fromBase(ThemeData base) {
return base.copyWith(
// Reduce padding and spacing
cardTheme: base.cardTheme?.copyWith(
margin: EdgeInsets.all(8),
),
// Smaller text sizes
textTheme: base.textTheme.apply(
fontSizeFactor: 0.9,
),
);
}
}
// Usage
final compactLightTheme = CompactTheme.fromBase(HuxTheme.lightTheme);
final compactDarkTheme = CompactTheme.fromBase(HuxTheme.darkTheme);
```
### Conditional Theme Properties
Apply theme properties conditionally:
```dart theme={null}
ThemeData buildTheme({
required bool isDark,
required bool isHighContrast,
required bool isCompact,
}) {
var theme = isDark ? HuxTheme.darkTheme : HuxTheme.lightTheme;
if (isHighContrast) {
theme = theme.copyWith(
// Increase contrast ratios
colorScheme: theme.colorScheme.copyWith(
primary: theme.colorScheme.primary.withOpacity(1.0),
),
);
}
if (isCompact) {
theme = CompactTheme.fromBase(theme);
}
return theme;
}
```
## Advanced Color Schemes
### Custom Color Palettes
Define complete custom color palettes:
```dart theme={null}
class CustomColorScheme {
static const Color primary = Color(0xFF6366F1);
static const Color secondary = Color(0xFF8B5CF6);
static const Color accent = Color(0xFFEC4899);
static const Color success = Color(0xFF10B981);
static const Color warning = Color(0xFFF59E0B);
static const Color error = Color(0xFFEF4444);
static ColorScheme get lightColorScheme {
return ColorScheme.light(
primary: primary,
secondary: secondary,
tertiary: accent,
error: error,
);
}
static ColorScheme get darkColorScheme {
return ColorScheme.dark(
primary: primary,
secondary: secondary,
tertiary: accent,
error: error,
);
}
}
// Apply to theme
final customTheme = HuxTheme.lightTheme.copyWith(
colorScheme: CustomColorScheme.lightColorScheme,
);
```
## Best Practices
Use Material 3 seed colors for automatic color generation:
```dart theme={null}
// ✅ Good - Automatic color scheme
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)
// ⚠️ Use custom schemes only when needed
```
Use theme extensions for brand-specific colors:
```dart theme={null}
// ✅ Good - Extensible and type-safe
final colors = Theme.of(context).extension();
```
Always use HuxTokens for semantic colors:
```dart theme={null}
// ✅ Good - Theme-aware
HuxTokens.textPrimary(context)
// ❌ Avoid - Hardcoded
Colors.black
```
Always test custom themes in both light and dark modes:
```dart theme={null}
// Test light mode
theme: customLightTheme,
themeMode: ThemeMode.light,
// Test dark mode
darkTheme: customDarkTheme,
themeMode: ThemeMode.dark,
```
## Examples
Start with basic theming concepts
Learn component customization techniques
See dynamic theme switching in action
Explore the complete design system
# WCAG Utilities
Source: https://docs.thehuxdesign.com/advanced/wcag
WCAG 2.1 compliant contrast calculation utilities for accessibility
## Overview
`HuxWCAG` provides WCAG (Web Content Accessibility Guidelines) 2.1 compliant utilities for calculating color contrast ratios and determining accessible text colors. These utilities ensure your custom components meet accessibility standards.
Hux UI components automatically use these utilities internally, but they're also available as a public API for your custom components.
## Basic Usage
### Get Contrasting Text Color
The most common use case is determining the appropriate text color for a background:
```dart theme={null}
import 'package:hux/hux.dart';
final textColor = HuxWCAG.getContrastingTextColor(
backgroundColor: Colors.blue,
context: context,
);
// Use in your custom component
Text(
'Accessible text',
style: TextStyle(color: textColor),
)
```
This method automatically compares white and black text against your background color and returns the one with better contrast (meeting WCAG AA's 4.5:1 minimum requirement).
## API Reference
### `getContrastingTextColor`
Determines the appropriate text color based on WCAG AA contrast requirements.
**Parameters:**
* `backgroundColor` (required) - The background color to check against
* `context` (required) - BuildContext for theme-aware color tokens
**Returns:** `Color` - The text color with better contrast ratio
**Example:**
```dart theme={null}
final buttonColor = Colors.deepPurple;
final textColor = HuxWCAG.getContrastingTextColor(
backgroundColor: buttonColor,
context: context,
);
HuxButton(
onPressed: () {},
primaryColor: buttonColor,
child: Text('Button', style: TextStyle(color: textColor)),
)
```
### `calculateContrastRatio`
Calculates the contrast ratio between two colors according to WCAG guidelines.
**Parameters:**
* `color1` - First color
* `color2` - Second color
**Returns:** `double` - Contrast ratio between 1 and 21 (higher = better contrast)
**WCAG Requirements:**
* **Normal text**: Minimum 4.5:1 ratio
* **Large text** (18pt+ or 14pt+ bold): Minimum 3:1 ratio
**Example:**
```dart theme={null}
final ratio = HuxWCAG.calculateContrastRatio(
Colors.blue,
Colors.white,
);
if (ratio >= 4.5) {
print('Meets WCAG AA for normal text');
}
```
### `getRelativeLuminance`
Calculates the relative luminance of a color according to WCAG guidelines.
**Parameters:**
* `color` - The color to calculate luminance for
**Returns:** `double` - Luminance value between 0 (black) and 1 (white)
**Implementation Details:**
* Uses ITU-R BT.709 coefficients for accurate calculation
* Applies proper gamma correction for sRGB color space
* Follows WCAG 2.1 specification exactly
**Example:**
```dart theme={null}
final luminance = HuxWCAG.getRelativeLuminance(Colors.blue);
print('Luminance: $luminance'); // Value between 0 and 1
```
### `meetsContrastAA`
Checks if two colors meet WCAG AA contrast requirements.
**Parameters:**
* `foreground` (required) - Text/foreground color
* `background` (required) - Background color
* `isLargeText` (optional) - Whether text is large (18pt+ or 14pt+ bold). Default: `false`
**Returns:** `bool` - `true` if contrast meets WCAG AA requirements
**Example:**
```dart theme={null}
// Check normal text
final accessible = HuxWCAG.meetsContrastAA(
foreground: Colors.black,
background: Colors.white,
); // Returns true
// Check large text (lower threshold)
final largeTextAccessible = HuxWCAG.meetsContrastAA(
foreground: Colors.grey.shade700,
background: Colors.white,
isLargeText: true,
);
```
## Use Cases
### Custom Components
Use HuxWCAG utilities in your custom components to ensure accessibility:
```dart theme={null}
class MyCustomCard extends StatelessWidget {
final Color cardColor;
@override
Widget build(BuildContext context) {
final textColor = HuxWCAG.getContrastingTextColor(
backgroundColor: cardColor,
context: context,
);
return Container(
color: cardColor,
child: Text(
'Card content',
style: TextStyle(color: textColor),
),
);
}
}
```
### Form Validation
Validate color combinations before applying them:
```dart theme={null}
void validateColorScheme(Color foreground, Color background) {
if (!HuxWCAG.meetsContrastAA(
foreground: foreground,
background: background,
)) {
throw ArgumentError(
'Colors do not meet WCAG AA contrast requirements (4.5:1)'
);
}
}
```
### Dynamic Theming
Calculate accessible colors for dynamic themes:
```dart theme={null}
Color getAccessibleAccent(Color baseColor, BuildContext context) {
// Check if base color provides enough contrast
if (HuxWCAG.calculateContrastRatio(
baseColor,
HuxTokens.surfacePrimary(context),
) < 4.5) {
// Adjust color if needed
return baseColor.withValues(alpha: 0.8);
}
return baseColor;
}
```
## Technical Details
### WCAG 2.1 Compliance
All calculations follow the official [WCAG 2.1 specification](https://www.w3.org/TR/WCAG21/):
* **Relative Luminance**: Uses ITU-R BT.709 coefficients (0.2126, 0.7152, 0.0722)
* **Gamma Correction**: Proper sRGB gamma correction applied
* **Contrast Formula**: `(L1 + 0.05) / (L2 + 0.05)` where L1 is lighter, L2 is darker
### Accuracy
HuxWCAG uses manual calculation rather than Flutter's `computeLuminance()` for:
* ✅ Exact WCAG 2.1 compliance
* ✅ Consistent results across all platforms
* ✅ Proper gamma correction for sRGB
### Performance
All methods are static and optimized for performance:
* No object instantiation required
* Pure mathematical calculations
* Suitable for real-time use in build methods
## Integration with Hux Components
Hux UI components automatically use these utilities internally:
* **HuxButton** - Primary buttons use `getContrastingTextColor()` automatically
* **HuxDropdown** - Text color adapts to primary color variants
* **HuxBadge** - Badge text color calculated for all variants
* **HuxToggle** - Icon and text colors adapt to background
* **HuxCheckbox** - Checkmark color adapts to primary color
* **HuxPagination** - Selected page text color calculated
You don't need to use HuxWCAG manually for Hux components - they handle it automatically. Use these utilities when creating custom components or extending Hux UI.
**Pro Tip**: Hux UI components handle WCAG compliance automatically. Only use HuxWCAG utilities when creating custom components or when you need fine-grained control over accessibility calculations.
# Alert (Deprecated)
Source: https://docs.thehuxdesign.com/components/alert
This component is being renamed to Snackbar for better clarity
> **⚠️ Deprecation Notice**: This component is being renamed to "Snackbar" for better clarity and user experience. The `HuxAlert` class name in your code remains unchanged - this is just a documentation improvement.
>
> **📖 New Documentation**: See [Snackbar](/components/snackbar) for the updated and improved documentation.
>
> **🔄 Migration**: No code changes required. Your existing `HuxAlert` usage will continue to work exactly as before.
***
## Overview
**This documentation has been moved to [Snackbar](/components/snackbar).**
HuxAlert is a message box component that provides clear communication to users through semantic variants (info, success, error) and dismissible functionality. It automatically adapts to light and dark themes while maintaining excellent readability and accessibility.
**Please visit the [Snackbar](/components/snackbar) page for complete and up-to-date documentation.**
## Basic Usage
### Info Alert
```dart theme={null}
HuxAlert(
variant: HuxAlertVariant.info,
title: 'Information',
message: 'This is an informational message for the user.',
showIcon: true,
)
```
### Success Alert
```dart theme={null}
HuxAlert(
variant: HuxAlertVariant.success,
title: 'Success!',
message: 'Operation completed successfully.',
showIcon: true,
onDismiss: () {
// Handle dismissal
},
)
```
### Error Alert
```dart theme={null}
HuxAlert(
variant: HuxAlertVariant.destructive,
title: 'Error',
message: 'Something went wrong. Please try again.',
showIcon: true,
onDismiss: () {
// Handle dismissal
},
)
```
## Properties
### Core Properties
* `variant` - Alert type (info, success, destructive)
* `title` - Alert heading text
* `message` - Main alert content
* `showIcon` - Whether to display the variant icon
### Behavior Properties
* `onDismiss` - Callback when dismiss button is clicked
* `dismissible` - Whether the alert can be dismissed (default: true)
## Variants
### Info Alert (`HuxAlertVariant.info`)
* **Purpose**: General information and updates
* **Icon**: Information icon
* **Colors**: Theme-aware info colors
* **Use Case**: System updates, helpful tips, general notices
### Success Alert (`HuxAlertVariant.success`)
* **Purpose**: Positive confirmations and achievements
* **Icon**: Checkmark icon
* **Colors**: Theme-aware success colors
* **Use Case**: Form submissions, completed actions, positive feedback
### Destructive Alert (`HuxAlertVariant.destructive`)
* **Purpose**: Errors, warnings, and critical information
* **Icon**: Warning/error icon
* **Colors**: Theme-aware destructive colors
* **Use Case**: Error messages, validation failures, critical warnings
## Styling & Layout
### Dimensions
* **Max Width**: 600px (prevents overly wide alerts)
* **Padding**: Consistent internal spacing
* **Border Radius**: Rounded corners for modern appearance
### Color System
* **Background**: `HuxTokens.surfaceSuccess(context)` / `HuxTokens.surfaceDestructive(context)`
* **Text**: `HuxTokens.textSuccess(context)` / `HuxTokens.textDestructive(context)`
* **Border**: Theme-aware border colors
* **Icon**: Matches text color for consistency
### Typography
* **Title**: Prominent heading with medium weight
* **Message**: Readable body text with proper line height
* **Icon**: Appropriately sized variant icons
## States
### Default State
* Fully visible with all content
* Interactive dismiss button (if dismissible)
* Proper contrast and readability
### Dismissed State
* Smooth fade-out animation
* Removed from layout
* Callback triggered for state management
## Accessibility
### Screen Reader Support
* Proper semantic labeling
* Variant announcements
* Dismiss button descriptions
### Keyboard Navigation
* Tab key support
* Enter/Space key activation for dismiss
* Focus management
### Visual Design
* High contrast ratios
* Clear visual hierarchy
* Consistent iconography
## Examples
See HuxAlert in action within forms
Different alert variants and use cases
## Related Components
* [HuxBadge](/components/badge) - Status indicators and notification counters
* [HuxInput](/components/input) - Form input components
* [HuxButton](/components/buttons) - Action buttons for forms
# Avatar
Source: https://docs.thehuxdesign.com/components/avatar
User profile images and avatar groups with gradient variants
## Overview
Hux UI provides avatar components for displaying user profile images:
* **HuxAvatar** - Circular user images with initials fallback and built-in caching
* **HuxAvatarGroup** - Display multiple avatars with overlapping layouts
### Features
* **Built-in Image Caching** - Network images use Flutter's built-in caching for better performance
* **Loading States** - Smooth loading indicators while images load
* **Error Handling** - Graceful fallback to initials when images fail to load
* **Offline Support** - Cached images work offline
## Component Variants
### Basic Avatar
Simple avatar with name and initials:
```dart theme={null}
HuxAvatar(
name: 'John Doe',
size: HuxAvatarSize.medium,
)
```
### Avatar with Network Image
Avatar with network profile image (automatically cached):
```dart theme={null}
HuxAvatar(
name: 'Jane Smith',
imageUrl: 'https://example.com/profile.jpg',
size: HuxAvatarSize.large,
)
```
**Features:**
* Automatic image caching for better performance
* Wireframe loading state while downloading
* Graceful fallback to initials if image fails to load
### Avatar with Local Asset Image
Avatar with local asset image (instant loading):
```dart theme={null}
HuxAvatar(
name: 'Local User',
assetImage: 'assets/avatar.png',
size: HuxAvatarSize.large,
)
```
**Features:**
* Instant loading (no network required)
* Always available (bundled with app)
* Perfect for default avatars or placeholder images
### Network vs Asset Images
| Feature | Network Image (`imageUrl`) | Asset Image (`assetImage`) |
| ---------------- | --------------------------- | ----------------------------- |
| **Loading** | Shows wireframe placeholder | Instant |
| **Availability** | Requires internet | Always available |
| **Updates** | Can be updated remotely | Requires app update |
| **App Size** | No impact | Increases app size |
| **Use Case** | User profile photos | Default avatars, placeholders |
### Gradient Avatar
Avatar with beautiful gradient background:
```dart theme={null}
HuxAvatar(
useGradient: true,
gradientVariant: HuxAvatarGradient.bluePurple,
size: HuxAvatarSize.medium,
)
```
### Small Avatar
Compact avatar for tight spaces:
```dart theme={null}
HuxAvatar(
name: 'Bob',
size: HuxAvatarSize.small,
)
```
### Large Avatar
Prominent avatar for important displays:
```dart theme={null}
HuxAvatar(
name: 'Alice',
size: HuxAvatarSize.large,
)
```
### Extra Large Avatar
Hero avatar for main displays:
```dart theme={null}
HuxAvatar(
name: 'CEO',
size: HuxAvatarSize.extraLarge,
useGradient: true,
gradientVariant: HuxAvatarGradient.purplePink,
)
```
### Avatar Group
Multiple avatars with overlapping layout:
```dart theme={null}
HuxAvatarGroup(
avatars: [
HuxAvatar(useGradient: true, gradientVariant: HuxAvatarGradient.bluePurple),
HuxAvatar(useGradient: true, gradientVariant: HuxAvatarGradient.tealCyan),
HuxAvatar(useGradient: true, gradientVariant: HuxAvatarGradient.orangeRed),
],
overlap: true,
maxVisible: 3,
)
```
### Spaced Avatar Group
Multiple avatars with spacing between them:
```dart theme={null}
HuxAvatarGroup(
avatars: [
HuxAvatar(name: 'Team A'),
HuxAvatar(name: 'Team B'),
HuxAvatar(name: 'Team C'),
],
overlap: false,
spacing: 8.0,
)
```
## HuxAvatar
### With Gradient
```dart theme={null}
HuxAvatar(
useGradient: true,
gradientVariant: HuxAvatarGradient.bluePurple,
size: HuxAvatarSize.medium,
)
```
### Sizes
* `small` - Compact avatar
* `medium` - Standard avatar (default)
* `large` - Prominent avatar
* `extraLarge` - Hero avatar
### Gradient Variants
* `bluePurple` - Blue to purple gradient
* `greenBlue` - Green to blue gradient
* `orangeRed` - Orange to red gradient
* `purplePink` - Purple to pink gradient
* `tealCyan` - Teal to cyan gradient
## HuxAvatarGroup
Display multiple avatars with overlapping or spaced layouts.
```dart theme={null}
HuxAvatarGroup(
avatars: [
HuxAvatar(name: 'Alice'),
HuxAvatar(name: 'Bob'),
HuxAvatar(useGradient: true, gradientVariant: HuxAvatarGradient.greenBlue),
],
overlap: true,
maxVisible: 3,
)
```
Complete avatar documentation is coming soon. See the [example app](https://github.com/lofidesigner/hux/tree/main/example) for more usage patterns.
# Badge
Source: https://docs.thehuxdesign.com/components/badge
Status indicators and notification counters with semantic variants
## Overview
`HuxBadge` is a versatile component for displaying status indicators, notification counters, and labels throughout your application. It provides semantic variants for different contexts while maintaining consistent styling and excellent accessibility.
## Basic Usage
### Primary Badge
```dart theme={null}
HuxBadge(
label: 'New',
variant: HuxBadgeVariant.primary,
)
```
### Success Badge
```dart theme={null}
HuxBadge(
label: 'Active',
variant: HuxBadgeVariant.success,
)
```
### Notification Counter
```dart theme={null}
HuxBadge(
label: '5',
variant: HuxBadgeVariant.number,
)
```
### Custom Color Badge
```dart theme={null}
HuxBadge(
label: 'Custom',
customColor: Colors.purple,
)
```
## Properties
### Core Properties
* `label` - Text content displayed in the badge
* `variant` - Visual style variant
* `size` - Badge size (small, medium, large)
### Customization Properties
* `customColor` - Custom background color (overrides variant)
## Variants
### Primary Badge
Main actions and primary states with theme-aware primary colors.
```dart theme={null}
HuxBadge(
label: 'New',
variant: HuxBadgeVariant.primary,
)
```
* **Purpose**: Main actions and primary states
* **Colors**: Theme-aware primary colors
* **Use Case**: Main features, primary actions
### Secondary Badge
Secondary information and states with theme-aware secondary colors.
```dart theme={null}
HuxBadge(
label: 'Info',
variant: HuxBadgeVariant.secondary,
)
```
* **Purpose**: Secondary information and states
* **Colors**: Theme-aware secondary colors
* **Use Case**: Secondary features, additional info
### Outline Badge
Subtle indicators with transparent background and borders.
```dart theme={null}
HuxBadge(
label: 'Draft',
variant: HuxBadgeVariant.outline,
)
```
* **Purpose**: Subtle indicators with borders
* **Colors**: Transparent background with borders
* **Use Case**: Subtle status indicators
### Success Badge
Positive states and confirmations with theme-aware success colors.
```dart theme={null}
HuxBadge(
label: 'Active',
variant: HuxBadgeVariant.success,
)
```
* **Purpose**: Positive states and confirmations
* **Colors**: Theme-aware success colors
* **Use Case**: Completed tasks, positive status
### Destructive Badge
Errors and critical states with theme-aware destructive colors.
```dart theme={null}
HuxBadge(
label: 'Error',
variant: HuxBadgeVariant.destructive,
)
```
* **Purpose**: Errors and critical states
* **Colors**: Theme-aware destructive colors
* **Use Case**: Error states, critical warnings
### Number Badge
Notification counters and numbers with theme-aware number colors.
```dart theme={null}
HuxBadge(
label: '5',
variant: HuxBadgeVariant.number,
)
```
* **Purpose**: Notification counters and numbers
* **Colors**: Theme-aware number colors
* **Use Case**: Notification counts, item quantities
## Size Variants
### Small Badge
* **Height**: 20px
* **Font Size**: 11px
* **Horizontal Padding**: 8px
* **Vertical Padding**: 4px
```dart theme={null}
HuxBadge(
label: 'New',
variant: HuxBadgeVariant.primary,
size: HuxBadgeSize.small,
)
```
### Medium Badge ⭐ **Default**
* **Height**: 24px
* **Font Size**: 12px
* **Horizontal Padding**: 12px
* **Vertical Padding**: 6px
```dart theme={null}
HuxBadge(
label: 'Info',
variant: HuxBadgeVariant.secondary,
size: HuxBadgeSize.medium,
)
```
### Large Badge
* **Height**: 28px
* **Font Size**: 14px
* **Horizontal Padding**: 16px
* **Vertical Padding**: 8px
```dart theme={null}
HuxBadge(
label: 'Active',
variant: HuxBadgeVariant.success,
size: HuxBadgeSize.large,
)
```
## Styling & Colors
### Background Colors
* **Primary**: `HuxTokens.primary(context)`
* **Secondary**: `HuxTokens.buttonSecondaryBackground(context)`
* **Success**: `HuxTokens.surfaceSuccess(context)`
* **Destructive**: `HuxTokens.surfaceDestructive(context)`
* **Custom**: User-defined color
### Text Colors
* **Primary**: Auto-calculated for optimal contrast
* **Secondary**: `HuxTokens.buttonSecondaryText(context)`
* **Success**: `HuxTokens.textSuccess(context)`
* **Destructive**: `HuxTokens.textDestructive(context)`
* **Custom**: Auto-calculated for optimal contrast
### Border Colors
* **Primary**: `HuxTokens.borderSecondary(context)`
* **Secondary**: `HuxTokens.buttonSecondaryBorder(context)`
* **Success**: `HuxTokens.borderSecondary(context)`
* **Destructive**: `HuxTokens.borderSecondary(context)`
* **Custom**: User-defined color
## States
### Default State
* Fully visible with normal styling
* Proper contrast and readability
* Interactive and accessible
### Custom Color State
* User-defined background color
* Automatically calculated text color
* Maintains accessibility standards
## Accessibility
### Screen Reader Support
* Proper semantic labeling
* Variant announcements
* Content descriptions
### Visual Design
* High contrast ratios
* Clear visual hierarchy
* Consistent sizing
### Touch Targets
* Appropriate sizing for mobile
* Clear visual feedback
* Proper spacing
## Examples
See HuxBadge in different contexts
Badge usage for notifications
## Related Components
* [HuxAlert](/components/alert) - Message boxes for user feedback
* [HuxButton](/components/buttons) - Action buttons
* [HuxAvatar](/components/avatar) - User profile components
# Bottom Sheet
Source: https://docs.thehuxdesign.com/components/bottom-sheet
Mobile-first modal component for menus, forms, and general content
## Overview
`HuxBottomSheet` is a mobile-first modal component that slides up from the bottom of the screen. It is designed to be thumb-friendly and support drag gestures, making it the standard way to present options, forms, and content on mobile devices.
The package also includes `HuxActionSheet`, a specialized version of the bottom sheet for presenting a list of actionable items, similar to iOS-style action sheets.
## Basic Usage
### Standard Bottom Sheet
```dart theme={null}
showHuxBottomSheet(
context: context,
title: 'Information',
child: Text('This is a bottom sheet with some content.'),
);
```
### Action Sheet
```dart theme={null}
showHuxActionSheet(
context: context,
title: 'Share Options',
actions: [
HuxActionSheetItem(
label: 'Email',
icon: LucideIcons.mail,
onTap: () => shareViaEmail(),
),
HuxActionSheetItem(
label: 'Copy Link',
icon: LucideIcons.link,
onTap: () => copyLink(),
),
],
);
```
## HuxBottomSheet
### Sizes
Control the height of the bottom sheet using fixed variants:
* `HuxBottomSheetSize.small` - Takes \~25-30% of screen height
* `HuxBottomSheetSize.medium` - Takes \~50% of screen height (Default)
* `HuxBottomSheetSize.large` - Takes \~85% of screen height
* `HuxBottomSheetSize.fullscreen` - Takes the full screen height
```dart theme={null}
showHuxBottomSheet(
context: context,
title: 'Large Sheet',
size: HuxBottomSheetSize.large,
child: MyComplexForm(),
);
```
### Header Options
You can customize the header with a title, subtitle, and control buttons:
* `title`: Main heading text
* `subtitle`: Supporting text below the title
* `showDragHandle`: Whether to show the top drag indicator (Default: true)
* `showCloseButton`: Whether to show a close action in the header (Default: false)
```dart theme={null}
showHuxBottomSheet(
context: context,
title: 'Settings',
subtitle: 'Configure your app experience',
showCloseButton: true,
child: SettingsList(),
);
```
### Action Buttons
Bottom sheets can include a row of action buttons at the bottom:
```dart theme={null}
showHuxBottomSheet(
context: context,
title: 'Confirm Delete',
child: Text('Are you sure you want to delete this item?'),
actions: [
HuxButton(
onPressed: () => Navigator.pop(context),
variant: HuxButtonVariant.secondary,
child: Text('Cancel'),
),
HuxButton(
onPressed: () => deleteItem(),
child: Text('Delete'),
),
],
);
```
## HuxActionSheet
`showHuxActionSheet` is optimized for lists of actions. Each item is represented by a `HuxActionSheetItem`.
### Destructive Actions
Mark actions as destructive to style them with the theme's destructive color:
```dart theme={null}
HuxActionSheetItem(
label: 'Delete Record',
icon: LucideIcons.trash2,
isDestructive: true,
onTap: () => deleteRecord(),
)
```
### Disabled Actions
Actions can be disabled if they are currently unavailable:
```dart theme={null}
HuxActionSheetItem(
label: 'Share (Login required)',
icon: LucideIcons.share2,
isDisabled: true,
onTap: () {},
)
```
## API Reference
### showHuxBottomSheet Properties
| Property | Type | Default | Description |
| ----------------- | -------------------- | ------------ | --------------------------------- |
| `context` | `BuildContext` | **required** | The current build context |
| `title` | `String?` | `null` | Optional header title |
| `subtitle` | `String?` | `null` | Optional header subtitle |
| `child` | `Widget?` | `null` | Main content widget |
| `actions` | `List?` | `null` | Action buttons at the bottom |
| `size` | `HuxBottomSheetSize` | `medium` | Height variant of the sheet |
| `showDragHandle` | `bool` | `true` | Whether to show the top handle |
| `showCloseButton` | `bool` | `false` | Whether to show close button |
| `isDismissible` | `bool` | `true` | Whether tapping outside dismisses |
| `enableDrag` | `bool` | `true` | Whether drag gestures are enabled |
### showHuxActionSheet Properties
| Property | Type | Default | Description |
| ------------- | -------------------------- | ------------ | ----------------------------- |
| `context` | `BuildContext` | **required** | The current build context |
| `actions` | `List` | **required** | List of action items |
| `title` | `String?` | `null` | Optional header title |
| `subtitle` | `String?` | `null` | Optional header subtitle |
| `cancelLabel` | `String` | `'Cancel'` | Label for the cancel button |
| `showCancel` | `bool` | `true` | Whether to show cancel button |
## Accessibility
* **Focus Management**: The bottom sheet handles focus trapping and restoration.
* **Gestures**: Drag handle provides a visual hint for dismissible content.
* **Contrast**: All text and icons follow theme-aware contrast rules.
* **Semantic Roles**: Action items use proper list and button semantics.
# Breadcrumbs
Source: https://docs.thehuxdesign.com/components/breadcrumbs
Hierarchical navigation that shows the current location and path.
## Overview
`HuxBreadcrumbs` displays the navigation trail for the current page. It adapts to light/dark themes and supports icons, sizes, and overflow.
## Basic Usage
```dart theme={null}
HuxBreadcrumbs(
items: [
HuxBreadcrumbItem(
label: 'Home',
icon: LucideIcons.home,
onTap: () => context.showHuxSnackbar(
message: 'Home',
variant: HuxSnackbarVariant.info,
),
),
HuxBreadcrumbItem(label: 'Products', onTap: () {}),
HuxBreadcrumbItem(label: 'Smartphones', onTap: () {}),
HuxBreadcrumbItem(label: 'iPhone 15 Pro', onTap: () {}, isActive: true),
],
)
```
## Variants
`HuxBreadcrumbVariant` controls the separator style:
### Default
Uses the `/` text separator.
```dart theme={null}
HuxBreadcrumbs(
variant: HuxBreadcrumbVariant.default_,
items: [...],
)
```
### Icon
Uses a chevron icon separator.
```dart theme={null}
HuxBreadcrumbs(
variant: HuxBreadcrumbVariant.icon,
items: [...],
)
```
## Sizes
Control spacing and typography with `HuxBreadcrumbSize`:
```dart theme={null}
HuxBreadcrumbs(size: HuxBreadcrumbSize.small, items: [...])
HuxBreadcrumbs(size: HuxBreadcrumbSize.medium, items: [...]) // default
HuxBreadcrumbs(size: HuxBreadcrumbSize.large, items: [...])
```
## Overflow
Collapse long paths with an overflow token.
```dart theme={null}
HuxBreadcrumbs(
maxItems: 3,
overflowIndicator: Text('...'),
items: [...],
)
```
## API Reference
### HuxBreadcrumbs Properties
| Property | Type | Default | Description |
| ------------------- | ------------------------- | ---------- | ----------------------------------- |
| `items` | `List` | — | Breadcrumbs to render |
| `variant` | `HuxBreadcrumbVariant` | `default_` | Visual style |
| `size` | `HuxBreadcrumbSize` | `medium` | Spacing and typography |
| `maxItems` | `int?` | `null` | Collapse middle items when exceeded |
| `overflowIndicator` | `Widget?` | `null` | Custom widget for overflow token |
### HuxBreadcrumbItem
| Property | Type | Default | Description |
| ------------ | -------------- | ------- | -------------------------- |
| `label` | `String` | — | Text label |
| `onTap` | `VoidCallback` | — | Called when item is tapped |
| `icon` | `IconData?` | `null` | Optional leading icon |
| `isDisabled` | `bool` | `false` | Non-interactive appearance |
| `isActive` | `bool` | `false` | Marks the current page |
## Accessibility
* Items are accessible via semantics and keyboard focus
* Active item is visually distinguished; disabled items announce properly
# Button
Source: https://docs.thehuxdesign.com/components/buttons
Customizable button component with multiple variants, sizes, and loading states
## Overview
`HuxButton` is a versatile button component that provides multiple visual variants, sizes, loading states, and automatic WCAG AA contrast compliance. It adapts seamlessly to light and dark themes.
## Basic Usage
```dart theme={null}
HuxButton(
onPressed: () => print('Button pressed!'),
child: Text('Primary Button'),
)
```
## Variants
HuxButton supports four visual variants through the `HuxButtonVariant` enum:
### Primary
The default variant with a filled background using the primary color.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Primary'),
variant: HuxButtonVariant.primary, // Default
)
```
### Secondary
A subtle variant with a light background and border.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Secondary'),
variant: HuxButtonVariant.secondary,
)
```
### Outline
A transparent button with only a border outline.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Outline'),
variant: HuxButtonVariant.outline,
)
```
### Ghost
A minimal transparent button without borders.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Ghost'),
variant: HuxButtonVariant.ghost,
)
```
## Sizes
Control button dimensions with three size options:
### Small
Compact size for tight spaces (32px height).
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Small'),
size: HuxButtonSize.small,
)
```
### Medium
Default size for most use cases (40px height).
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Medium'),
size: HuxButtonSize.medium, // Default
)
```
### Large
Prominent size for important actions (48px height).
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Large'),
size: HuxButtonSize.large,
)
```
## States
### Loading State
Display a loading indicator while processing.
```dart theme={null}
class LoadingButtonExample extends StatefulWidget {
@override
_LoadingButtonExampleState createState() => _LoadingButtonExampleState();
}
class _LoadingButtonExampleState extends State {
bool _isLoading = false;
void _handlePress() async {
setState(() {
_isLoading = true;
});
// Simulate async operation
await Future.delayed(Duration(seconds: 2));
setState(() {
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return HuxButton(
onPressed: _isLoading ? null : _handlePress,
isLoading: _isLoading,
child: Text('Submit'),
);
}
}
```
### Disabled State
Disable button interaction.
```dart theme={null}
HuxButton(
onPressed: null, // or use isDisabled: true
child: Text('Disabled Button'),
isDisabled: true,
)
```
## Icons
Add icons to enhance button meaning:
### Icon with Text
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Save'),
icon: FeatherIcons.save,
)
```
### Icon-only Button
```dart theme={null}
HuxButton(
onPressed: () {},
child: Icon(FeatherIcons.heart),
size: HuxButtonSize.small,
)
```
### Square Icon-only Button
```dart theme={null}
HuxButton(
onPressed: () {},
child: SizedBox(width: 0), // Icon-only with no text
icon: FeatherIcons.heart,
size: HuxButtonSize.medium,
width: HuxButtonWidth.fixed,
widthValue: 40, // Square button: 40x40
)
```
## Width Control
Control button width behavior with the `HuxButtonWidth` enum:
### Hug Content (Default)
Button width matches its content.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Short Text'),
// width: HuxButtonWidth.hug (default)
)
```
### Expand to Fill
Button takes full available width.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Full Width'),
width: HuxButtonWidth.expand,
)
```
### Fixed Width
Button has a specific width.
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Fixed Width'),
width: HuxButtonWidth.fixed,
widthValue: 200, // 200px width
)
```
## Custom Colors
### Using Preset Colors
```dart theme={null}
// Indigo theme
HuxButton(
onPressed: () {},
child: Text('Indigo Button'),
primaryColor: HuxColors.getPresetColor('indigo'),
)
// Green theme
HuxButton(
onPressed: () {},
child: Text('Green Button'),
primaryColor: HuxColors.getPresetColor('green'),
)
// Pink theme
HuxButton(
onPressed: () {},
child: Text('Pink Button'),
primaryColor: HuxColors.getPresetColor('pink'),
)
```
### Custom Colors
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Custom Purple'),
primaryColor: Color(0xFF6366F1),
)
HuxButton(
onPressed: () {},
child: Text('Custom Orange'),
primaryColor: Colors.deepOrange,
)
```
## API Reference
### HuxButton Properties
| Property | Type | Default | Description |
| -------------- | ------------------ | ------------ | --------------------------------------------- |
| `onPressed` | `VoidCallback?` | **required** | Callback triggered when button is pressed |
| `child` | `Widget` | **required** | The child widget to display inside the button |
| `variant` | `HuxButtonVariant` | `primary` | Visual variant of the button |
| `size` | `HuxButtonSize` | `medium` | Size variant of the button |
| `isLoading` | `bool` | `false` | Whether to show loading indicator |
| `isDisabled` | `bool` | `false` | Whether the button is disabled |
| `icon` | `IconData?` | `null` | Optional icon to display before text |
| `primaryColor` | `Color?` | `null` | Custom primary color (overrides theme) |
### HuxButtonVariant Enum
* `HuxButtonVariant.primary` - Filled background with primary color
* `HuxButtonVariant.secondary` - Light background with border
* `HuxButtonVariant.outline` - Transparent with border only
* `HuxButtonVariant.ghost` - Transparent without border
### HuxButtonSize Enum
* `HuxButtonSize.small` - 32px height, compact padding
* `HuxButtonSize.medium` - 40px height, standard padding
* `HuxButtonSize.large` - 48px height, generous padding
## Common Patterns
### Form Buttons
```dart theme={null}
Row(
children: [
Expanded(
child: HuxButton(
onPressed: () {},
child: Text('Cancel'),
variant: HuxButtonVariant.outline,
),
),
SizedBox(width: 12),
Expanded(
child: HuxButton(
onPressed: () {},
child: Text('Submit'),
variant: HuxButtonVariant.primary,
),
),
],
)
```
### Action Buttons
```dart theme={null}
Column(
children: [
HuxButton(
onPressed: () {},
child: Text('Primary Action'),
variant: HuxButtonVariant.primary,
size: HuxButtonSize.large,
),
SizedBox(height: 12),
HuxButton(
onPressed: () {},
child: Text('Secondary Action'),
variant: HuxButtonVariant.secondary,
),
SizedBox(height: 8),
HuxButton(
onPressed: () {},
child: Text('Cancel'),
variant: HuxButtonVariant.ghost,
),
],
)
```
### Button Grid
```dart theme={null}
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
children: [
HuxButton(
onPressed: () {},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(FeatherIcons.camera),
SizedBox(height: 8),
Text('Camera'),
],
),
variant: HuxButtonVariant.outline,
),
HuxButton(
onPressed: () {},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(FeatherIcons.image),
SizedBox(height: 8),
Text('Gallery'),
],
),
variant: HuxButtonVariant.outline,
),
],
)
```
## Accessibility
HuxButton includes several accessibility features:
### Automatic Contrast
Text color is automatically calculated to ensure WCAG AA compliance (4.5:1 contrast ratio) against any background color.
### Semantic Roles
Buttons include proper semantic roles for screen readers.
### Focus States
Keyboard navigation support with visible focus indicators.
### Disabled States
Proper disabled state handling for assistive technologies.
## Best Practices
* Use **Primary** for the main action on a screen
* Use **Secondary** for important but not primary actions
* Use **Outline** for secondary actions that need visual weight
* Use **Ghost** for subtle actions like "Cancel" or "Skip"
* Use **Large** for important call-to-action buttons
* Use **Medium** for most standard interactions
* Use **Small** for compact interfaces or secondary actions
```dart theme={null}
// Always disable the button during loading
HuxButton(
onPressed: _isLoading ? null : _handlePress,
isLoading: _isLoading,
child: Text('Submit'),
)
```
* Use action-oriented labels: "Save", "Delete", "Continue"
* Avoid generic labels: "OK", "Submit", "Button"
* Keep labels concise but descriptive
## Examples
See buttons in action within forms
Learn how to handle async operations
Apply custom colors and themes
Ensure your buttons are accessible
# Card
Source: https://docs.thehuxdesign.com/components/cards
Flexible card component with headers, actions, and tap handling
## Overview
`HuxCard` provides a flexible container component for displaying content with optional headers, titles, and actions.
## Component Variants
### Basic Card
Simple card with title and content:
```dart theme={null}
HuxCard(
title: 'Card Title',
child: Text('Card content goes here'),
)
```
### Card with Subtitle
Card with additional subtitle text:
```dart theme={null}
HuxCard(
title: 'Design System Update',
subtitle: 'Version 2.1.0 • 2 hours ago',
child: Text('New components and improved accessibility features'),
)
```
### Card with Action
Card with action button in header:
```dart theme={null}
HuxCard(
title: 'Project Dashboard',
action: IconButton(
icon: Icon(FeatherIcons.moreVertical),
onPressed: () => _showProjectMenu(),
),
child: Text('View project analytics and team performance'),
)
```
### Interactive Card
Card with tap handling:
```dart theme={null}
HuxCard(
title: 'View Analytics',
child: Text('Tap to see detailed performance metrics'),
onTap: () => _navigateToAnalytics(),
)
```
### Nested Cards
Card containing other cards:
```dart theme={null}
HuxCard(
title: 'Parent Card',
child: Column(
children: [
HuxCard(
title: 'Child Card 1',
child: Text('Nested content'),
),
HuxCard(
title: 'Child Card 2',
child: Text('More nested content'),
),
],
),
)
```
## Basic Usage
## With Actions
```dart theme={null}
HuxCard(
title: 'Settings',
action: IconButton(
icon: Icon(FeatherIcons.settings),
onPressed: () {},
),
child: Text('Configure your preferences'),
onTap: () => print('Card tapped'),
)
```
## Properties
* `title` - Card title text
* `subtitle` - Optional subtitle text
* `action` - Optional action widget (usually IconButton)
* `child` - Main content widget
* `onTap` - Tap handler for the entire card
Complete HuxCard documentation is coming soon. See the [example app](https://github.com/lofidesigner/hux/tree/main/example) for more usage patterns.
# Chart
Source: https://docs.thehuxdesign.com/components/charts
Beautiful data visualization with line and bar charts
## Overview
`HuxChart` provides beautiful data visualization components powered by the cristalyse package, with automatic theme adaptation and smooth animations.
## Component Variants
### Line Charts
Display data trends over time with smooth line charts:
```dart theme={null}
HuxChart.line(
data: [
{'x': 1, 'y': 10},
{'x': 2, 'y': 20},
{'x': 3, 'y': 15},
{'x': 4, 'y': 25},
],
xField: 'x',
yField: 'y',
title: 'Sales Over Time',
subtitle: 'Monthly data',
primaryColor: Colors.blue,
)
```
### Bar Charts
Visualize categorical data with responsive bar charts:
```dart theme={null}
HuxChart.bar(
data: [
{'category': 'Product A', 'value': 30},
{'category': 'Product B', 'value': 45},
{'category': 'Product C', 'value': 25},
{'category': 'Product D', 'value': 35},
],
xField: 'category',
yField: 'value',
title: 'Product Sales',
subtitle: 'Current quarter',
)
```
### Small Charts
Compact charts for dashboards and tight spaces:
```dart theme={null}
HuxChart.line(
data: chartData,
xField: 'date',
yField: 'revenue',
size: HuxChartSize.small,
title: 'Revenue Trend',
)
```
### Large Charts
Full-size charts for detailed analysis:
```dart theme={null}
HuxChart.bar(
data: chartData,
xField: 'month',
yField: 'sales',
size: HuxChartSize.large,
title: 'Annual Sales Analysis',
subtitle: 'Detailed monthly breakdown',
)
```
### Themed Charts
Charts that automatically adapt to your app's theme:
```dart theme={null}
HuxChart.line(
data: chartData,
xField: 'date',
yField: 'users',
primaryColor: HuxTokens.primary(context),
title: 'User Growth',
)
```
## Features
* **Theme Aware** - Automatically adapts to light/dark themes
* **Responsive** - Adjusts to different screen sizes
* **Smooth Animations** - Beautiful transitions and interactions
* **Customizable Colors** - Use theme colors or custom palettes
* **Multiple Chart Types** - Line charts, bar charts, and more
## Properties
* `data` - Array of data objects
* `xField` - Field name for x-axis values
* `yField` - Field name for y-axis values
* `title` - Chart title (optional)
* `subtitle` - Chart subtitle (optional)
* `primaryColor` - Custom color override (optional)
## Data Format
Charts expect data in a simple array format:
```dart theme={null}
final chartData = [
{'date': '2024-01', 'revenue': 15000, 'users': 120},
{'date': '2024-02', 'revenue': 18000, 'users': 150},
{'date': '2024-03', 'revenue': 22000, 'users': 180},
];
```
HuxChart is powered by the [cristalyse](https://pub.dev/packages/cristalyse) package. Complete chart documentation is coming soon.
## Examples
See charts in action with real data
Build dashboards with multiple charts
# Checkbox
Source: https://docs.thehuxdesign.com/components/checkbox
Interactive checkbox component with smooth animations and consistent styling
## Overview
`HuxCheckbox` is an interactive checkbox component with smooth animations, consistent styling, and proper accessibility support. It automatically adapts to light and dark themes while providing a clean, professional appearance.
## Basic Usage
### Simple Checkbox
```dart theme={null}
HuxCheckbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value ?? false;
});
},
)
```
### Checkbox with Label
```dart theme={null}
HuxCheckbox(
value: isAgreed,
onChanged: (value) {
setState(() {
isAgreed = value ?? false;
});
},
label: 'I agree to the terms and conditions',
)
```
## Properties
### Core Properties
* `value` - Current checked state (true/false)
* `onChanged` - Callback triggered when state changes (null for disabled)
* `isDisabled` - Whether the checkbox is disabled (default: false)
### Label Properties
* `label` - Optional text label displayed next to the checkbox
### Styling Properties
* `size` - Checkbox size variant (small, medium, large)
## Size Variants
### Small Checkbox
* **Checkbox Size**: 16px × 16px
* **Icon Size**: 12px
* **Font Size**: 14px
* **Label Spacing**: 8px
### Medium Checkbox ⭐ **Default**
* **Checkbox Size**: 20px × 20px
* **Icon Size**: 14px
* **Font Size**: 16px
* **Label Spacing**: 12px
### Large Checkbox
* **Checkbox Size**: 24px × 24px
* **Icon Size**: 16px
* **Font Size**: 18px
* **Label Spacing**: 16px
## Styling & Colors
### Checkbox Colors
* **Background (Unchecked)**: `HuxTokens.surfacePrimary(context)`
* **Background (Checked)**: `HuxTokens.primary(context)`
* **Border (Unchecked)**: `HuxTokens.borderPrimary(context)`
* **Border (Checked)**: `HuxTokens.primary(context)`
* **Border (Disabled)**: `HuxTokens.borderSecondary(context)`
### Check Icon Colors
* **Check Color**: Automatically calculated for optimal contrast
* **Disabled State**: Transparent
### Text Colors
* **Label Text**: `HuxTokens.textPrimary(context)`
* **Disabled Label**: `HuxTokens.textDisabled(context)`
## States
### Unchecked State
* Empty checkbox with border
* Ready for user interaction
### Checked State
* Filled checkbox with check icon
* Visual confirmation of selection
### Disabled State
```dart theme={null}
HuxCheckbox(
value: isChecked,
onChanged: null, // Disables the checkbox
label: 'This option is disabled',
isDisabled: true,
)
```
* Reduced opacity and non-interactive
* Maintains visual consistency
## Accessibility
### Screen Reader Support
* Proper semantic labeling
* State announcements
* Focus management
### Keyboard Navigation
* Tab key support
* Space/Enter key activation
* Focus indicators
## Examples
See HuxCheckbox in action within forms
Try different checkbox configurations
## Related Components
* [HuxInput](/components/input) - Text input component
* [HuxSwitch](/components/switch) - Toggle switch component
* [HuxDateInput](/components/date-input) - Date input component
# Command
Source: https://docs.thehuxdesign.com/components/command
A powerful command palette component for quick access to actions and navigation
The Command component provides a searchable command palette that allows users to quickly find and execute actions using keyboard shortcuts or mouse interaction.
## Overview
* **Keyboard Shortcuts**: Open with `CMD+K` (Mac) or `Ctrl+K` (Windows/Linux)
* **Search & Filter**: Real-time filtering as you type
* **Keyboard Navigation**: Arrow keys to navigate, Enter to execute
* **Customizable**: Add your own commands with icons, shortcuts, and categories
* **Accessible**: Full keyboard and screen reader support
## Basic Usage
```dart theme={null}
import 'package:hux/hux.dart';
// Define your commands
final commands = [
HuxCommandItem(
id: 'toggle-theme',
label: 'Toggle Theme',
description: 'Switch between light and dark mode',
shortcut: '⌘⇧T',
icon: LucideIcons.sun,
category: 'View',
onExecute: () => print('Theme toggled'),
),
HuxCommandItem(
id: 'settings',
label: 'Settings',
description: 'Open application settings',
shortcut: '⌘,',
icon: LucideIcons.settings,
category: 'Preferences',
onExecute: () => print('Settings opened'),
),
];
// Show the command palette
showHuxCommand(
context: context,
commands: commands,
placeholder: 'Type a command or search...',
onCommandSelected: (command) {
print('Selected: ${command.label}');
},
);
```
## Global Keyboard Shortcuts
For app-wide command palette access, wrap your app with `HuxCommandShortcuts.wrapper`:
```dart theme={null}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return HuxCommandShortcuts.wrapper(
commands: globalCommands,
child: MaterialApp(
home: MyHomePage(),
),
);
}
}
```
## Command Item Properties
| Property | Type | Description |
| ------------- | -------------- | -------------------------------------------- |
| `id` | `String` | Unique identifier for the command |
| `label` | `String` | Display name of the command |
| `description` | `String?` | Optional detailed description |
| `shortcut` | `String?` | Keyboard shortcut (e.g., '⌘K', '⌘⇧F') |
| `icon` | `IconData?` | Icon to display next to the command |
| `category` | `String?` | Category for grouping commands |
| `onExecute` | `VoidCallback` | Function to execute when command is selected |
## Shortcut Format
Use Apple symbols for shortcuts without '+' signs:
* **Command**: `⌘`
* **Shift**: `⇧`
* **Option**: `⌥`
* **Control**: `⌃`
Examples:
* `⌘K` - Command + K
* `⌘⇧F` - Command + Shift + F
* `⌘⌥T` - Command + Option + T
## Customization
### Custom Placeholder
```dart theme={null}
showHuxCommand(
context: context,
commands: commands,
placeholder: 'Search commands...',
);
```
### Custom Empty State
```dart theme={null}
showHuxCommand(
context: context,
commands: commands,
emptyText: 'No matching commands found',
);
```
### Command Categories
Organize commands by category for better user experience:
```dart theme={null}
final commands = [
// File operations
HuxCommandItem(
id: 'new-file',
label: 'New File',
category: 'File',
// ...
),
// Edit operations
HuxCommandItem(
id: 'find',
label: 'Find',
category: 'Edit',
// ...
),
// View operations
HuxCommandItem(
id: 'toggle-sidebar',
label: 'Toggle Sidebar',
category: 'View',
// ...
),
];
```
## Keyboard Navigation
* **`CMD+K` / `Ctrl+K`**: Open command palette
* **`↑` / `↓`**: Navigate through commands
* **`Enter`**: Execute selected command
* **`Escape`**: Close command palette
* **Type**: Filter commands by name
## Examples
### File Management Commands
```dart theme={null}
final fileCommands = [
HuxCommandItem(
id: 'new-file',
label: 'New File',
shortcut: '⌘N',
icon: LucideIcons.filePlus,
category: 'File',
onExecute: () => createNewFile(),
),
HuxCommandItem(
id: 'open-file',
label: 'Open File',
shortcut: '⌘O',
icon: LucideIcons.folder,
category: 'File',
onExecute: () => openFileDialog(),
),
HuxCommandItem(
id: 'save-file',
label: 'Save File',
shortcut: '⌘S',
icon: LucideIcons.save,
category: 'File',
onExecute: () => saveCurrentFile(),
),
];
```
### Navigation Commands
```dart theme={null}
final navigationCommands = [
HuxCommandItem(
id: 'go-to-dashboard',
label: 'Go to Dashboard',
shortcut: '⌘1',
icon: LucideIcons.home,
category: 'Navigation',
onExecute: () => navigateToDashboard(),
),
HuxCommandItem(
id: 'go-to-settings',
label: 'Go to Settings',
shortcut: '⌘,',
icon: LucideIcons.settings,
category: 'Navigation',
onExecute: () => navigateToSettings(),
),
];
```
## Best Practices
**Command Organization**: Group related commands by category and use consistent naming conventions.
**Shortcut Conflicts**: Ensure keyboard shortcuts don't conflict with system shortcuts or other app shortcuts.
**Accessibility**: Always provide meaningful labels and descriptions for screen readers.
## API Reference
### HuxCommand
The main command palette widget.
#### Constructor
```dart theme={null}
HuxCommand({
required List commands,
String placeholder = 'Type a command or search...',
String emptyText = 'No commands found',
ValueChanged? onCommandSelected,
VoidCallback? onClose,
})
```
### HuxCommandItem
Represents a single command in the palette.
#### Constructor
```dart theme={null}
HuxCommandItem({
required String id,
required String label,
required VoidCallback onExecute,
String? description,
String? shortcut,
IconData? icon,
String? category,
})
```
### HuxCommandShortcuts
Utility class for global keyboard shortcuts.
#### Methods
* `wrapper()` - Wraps your app to provide global shortcuts
* `handleKeyEvent()` - Returns a key event handler for custom integration
# Context Menu
Source: https://docs.thehuxdesign.com/components/context-menu
Right-click context menus with smart positioning and cross-platform support
## Overview
Hux UI provides a comprehensive context menu system with smart positioning and cross-platform support:
* **HuxContextMenu** - Main wrapper widget with smart positioning
* **HuxContextMenuItem** - Individual menu items with icons and states
* **HuxContextMenuDivider** - Visual separators for menu groups
## Component Variants
### Basic Context Menu
Simple context menu with basic actions:
```dart theme={null}
HuxContextMenu(
menuItems: [
HuxContextMenuItem(
text: 'Copy',
icon: FeatherIcons.copy,
onTap: () => print('Copy action'),
),
HuxContextMenuItem(
text: 'Paste',
icon: FeatherIcons.clipboard,
onTap: () => print('Paste action'),
),
],
child: Text('Right-click me!'),
)
```
### Context Menu with Dividers
Organized menu with visual separators:
```dart theme={null}
HuxContextMenu(
menuItems: [
HuxContextMenuItem(
text: 'Copy',
icon: FeatherIcons.copy,
onTap: () => print('Copy action'),
),
HuxContextMenuItem(
text: 'Paste',
icon: FeatherIcons.clipboard,
onTap: () => print('Paste action'),
),
const HuxContextMenuDivider(),
HuxContextMenuItem(
text: 'Delete',
icon: FeatherIcons.trash2,
onTap: () => print('Delete action'),
isDestructive: true,
),
],
child: Container(
padding: const EdgeInsets.all(20),
child: const Text('Right-click me!'),
),
)
```
### Context Menu with Disabled Items
Menu with disabled and destructive actions:
```dart theme={null}
HuxContextMenu(
menuItems: [
HuxContextMenuItem(
text: 'Edit',
icon: FeatherIcons.edit2,
onTap: () => print('Edit action'),
),
HuxContextMenuItem(
text: 'Duplicate',
icon: FeatherIcons.copy,
onTap: () => print('Duplicate action'),
isDisabled: true, // Disabled item
),
const HuxContextMenuDivider(),
HuxContextMenuItem(
text: 'Delete',
icon: FeatherIcons.trash2,
onTap: () => print('Delete action'),
isDestructive: true, // Destructive action
),
],
child: Icon(Icons.more_vert),
)
```
### File Context Menu
Context menu for file operations:
```dart theme={null}
HuxContextMenu(
menuItems: [
HuxContextMenuItem(
text: 'New File',
icon: FeatherIcons.filePlus,
onTap: () => _createNewFile(),
),
HuxContextMenuItem(
text: 'Open',
icon: FeatherIcons.folderOpen,
onTap: () => _openFile(),
),
const HuxContextMenuDivider(),
HuxContextMenuItem(
text: 'Rename',
icon: FeatherIcons.edit2,
onTap: () => _renameFile(),
),
HuxContextMenuItem(
text: 'Delete',
icon: FeatherIcons.trash2,
onTap: () => _deleteFile(),
isDestructive: true,
),
],
child: FileIcon(),
)
```
## Basic Usage
## Features
* **Smart Positioning** - Automatic menu positioning to prevent screen overflow
* **Cross-Platform** - Works on desktop, mobile, and web
* **Web Optimization** - Proper browser context menu prevention
* **Consistent Design** - Follows Hux UI design system
* **Theme Aware** - Adapts to light and dark themes
## Components
### HuxContextMenu
Main wrapper that handles context menu display and positioning.
**Properties:**
* `menuItems` - List of menu items and dividers
* `child` - Widget that triggers the context menu
### HuxContextMenuItem
Individual menu item with icon, text, and interaction handling.
**Properties:**
* `text` - Menu item label
* `icon` - Optional icon (FeatherIcons recommended)
* `onTap` - Action callback
* `isDisabled` - Whether the item is disabled
* `isDestructive` - Whether the item represents a destructive action
### HuxContextMenuDivider
Visual separator for organizing menu items into groups.
```dart theme={null}
const HuxContextMenuDivider()
```
## Advanced Example
```dart theme={null}
HuxContextMenu(
menuItems: [
// File operations
HuxContextMenuItem(
text: 'New File',
icon: FeatherIcons.filePlus,
onTap: () => _createNewFile(),
),
HuxContextMenuItem(
text: 'Open',
icon: FeatherIcons.folderOpen,
onTap: () => _openFile(),
),
const HuxContextMenuDivider(),
// Edit operations
HuxContextMenuItem(
text: 'Cut',
icon: FeatherIcons.scissors,
onTap: () => _cutSelection(),
isDisabled: !_hasSelection,
),
HuxContextMenuItem(
text: 'Copy',
icon: FeatherIcons.copy,
onTap: () => _copySelection(),
isDisabled: !_hasSelection,
),
HuxContextMenuItem(
text: 'Paste',
icon: FeatherIcons.clipboard,
onTap: () => _pasteClipboard(),
isDisabled: !_hasClipboardContent,
),
const HuxContextMenuDivider(),
// Destructive operations
HuxContextMenuItem(
text: 'Delete',
icon: FeatherIcons.trash2,
onTap: () => _deleteSelection(),
isDestructive: true,
isDisabled: !_hasSelection,
),
],
child: YourContentWidget(),
)
```
## Platform Support
* **Desktop** - Right-click support with proper positioning
* **Mobile** - Long-press gesture support
* **Web** - Proper browser context menu prevention
Context menus automatically prevent the browser's default context menu on web platforms using the universal\_html package.
## Examples
See context menus in a file management interface
Learn how to implement editor context menus
Right-click any component in the [example app](https://github.com/lofidesigner/hux/tree/main/example) to see context menus in action!
# Date Picker
Source: https://docs.thehuxdesign.com/components/date-picker
Modern date selection with overlay calendar and theme-aware styling
## Overview
`HuxDatePicker` provides a modern date selection experience with an overlay calendar, theme-aware styling, and flexible configuration options.
## Basic Usage
```dart theme={null}
HuxDatePicker(
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
onDateChanged: (date) {
print('Selected date: $date');
},
placeholder: 'Select Date',
)
```
## Variants
### With Text Label
Default behavior showing both icon and text.
```dart theme={null}
HuxDatePicker(
initialDate: _selectedDate,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
onDateChanged: (date) => setState(() => _selectedDate = date),
variant: HuxButtonVariant.outline,
icon: FeatherIcons.calendar,
placeholder: 'Choose Date',
)
```
### Icon Only
Compact icon-only version for tight spaces.
```dart theme={null}
HuxDatePicker(
initialDate: _selectedDate,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
onDateChanged: (date) => setState(() => _selectedDate = date),
showText: false, // Icon-only mode
variant: HuxButtonVariant.ghost,
icon: FeatherIcons.calendar,
)
```
## Properties
* `initialDate` - Initially selected date
* `firstDate` - Earliest selectable date
* `lastDate` - Latest selectable date
* `onDateChanged` - Callback when date is selected
* `placeholder` - Text shown when no date is selected
* `variant` - Button visual style (HuxButtonVariant)
* `size` - Button size (HuxButtonSize)
* `icon` - Calendar icon (defaults to Icons.calendar\_today)
* `primaryColor` - Custom primary color override
* `overlayColor` - Custom overlay background color
* `showText` - Whether to show text label (default: true)
## Date Range Validation
Set boundaries for selectable dates:
```dart theme={null}
HuxDatePicker(
initialDate: DateTime.now(),
firstDate: DateTime.now().subtract(Duration(days: 365)), // 1 year ago
lastDate: DateTime.now().add(Duration(days: 365)), // 1 year from now
onDateChanged: (date) => _selectedDate = date,
placeholder: 'Select Date',
)
```
## Custom Styling
### Custom Colors
```dart theme={null}
HuxDatePicker(
initialDate: _selectedDate,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
onDateChanged: (date) => _selectedDate = date,
primaryColor: Colors.deepPurple,
overlayColor: Colors.deepPurple.withOpacity(0.1),
placeholder: 'Select Date',
)
```
### Custom Icon
```dart theme={null}
HuxDatePicker(
initialDate: _selectedDate,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
onDateChanged: (date) => _selectedDate = date,
icon: FeatherIcons.calendar,
placeholder: 'Pick a Date',
)
```
## Integration with Forms
Use HuxDatePicker in forms with validation:
```dart theme={null}
Form(
key: _formKey,
child: Column(
children: [
HuxDatePicker(
initialDate: _birthDate,
firstDate: DateTime(1900),
lastDate: DateTime.now(),
onDateChanged: (date) => _birthDate = date,
placeholder: 'Select Birth Date',
variant: HuxButtonVariant.outline,
),
SizedBox(height: 16),
HuxButton(
onPressed: () {
if (_birthDate != null) {
// Proceed with form submission
}
},
child: Text('Submit'),
variant: HuxButtonVariant.primary,
),
],
),
)
```
## Features
* **Overlay Calendar** - Modern calendar interface that appears below the button
* **Smart Positioning** - Automatically adjusts position to prevent screen overflow
* **Theme Aware** - Seamlessly adapts to light and dark themes
* **Date Validation** - Enforces date range constraints
* **Keyboard Navigation** - Arrow keys and Enter/Space for calendar/header interactions
* **Tab Focus Cycling** - Tab navigation stays within picker regions (calendar/header) while open
* **Bounded Month/Year Navigation** - Month/year views and focus state are clamped to `firstDate..lastDate`
* **Flexible Styling** - Multiple button variants and size options
* **Icon Only Mode** - Compact display for space-constrained layouts
For more examples, see the [full example app](https://github.com/lofidesigner/hux/tree/main/example) and [Basic Usage](/examples/basic-usage) guide.
# Dialog
Source: https://docs.thehuxdesign.com/components/dialog
Modal dialogs with Hux styling and consistent theming
## Overview
HuxDialog is a customizable dialog component that provides a consistent modal experience with optional header, content, and action buttons. The dialog automatically adapts to light and dark themes and provides a clean, modern appearance with proper spacing and accessibility.
## Component Variants
### Basic Dialog
Simple dialog with title and content:
```dart theme={null}
HuxDialog(
title: 'Basic Dialog',
content: Text('This is a basic dialog with Hux styling.'),
actions: [
HuxButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Close'),
variant: HuxButtonVariant.secondary,
),
],
)
```
### Confirmation Dialog
Dialog for confirming important actions:
```dart theme={null}
HuxDialog(
title: 'Confirm Action',
subtitle: 'Are you sure you want to proceed?',
content: Text('This action cannot be undone. Please confirm that you want to continue.'),
actions: [
HuxButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('Cancel'),
variant: HuxButtonVariant.secondary,
),
HuxButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('Confirm'),
),
],
)
```
### Large Dialog
Dialog with extensive content:
```dart theme={null}
HuxDialog(
title: 'Large Dialog',
subtitle: 'This dialog demonstrates the large size variant',
size: HuxDialogSize.large,
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text('This is a large dialog with more content.'),
SizedBox(height: 16),
Text('You can include multiple paragraphs, forms, or other widgets here.'),
],
),
actions: [
HuxButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Close'),
variant: HuxButtonVariant.secondary,
),
HuxButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Save'),
),
],
)
```
## Size Variants
### Small Dialog
Compact dialog for simple confirmations:
```dart theme={null}
HuxDialog(
size: HuxDialogSize.small,
title: 'Quick Confirm',
content: Text('Are you sure?'),
actions: [
HuxButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('No'),
variant: HuxButtonVariant.secondary,
),
HuxButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('Yes'),
),
],
)
```
### Medium Dialog
Standard dialog size (default):
```dart theme={null}
HuxDialog(
size: HuxDialogSize.medium, // Default
title: 'Standard Dialog',
content: Text('This is the default medium size.'),
)
```
### Large Dialog
Spacious dialog for complex content:
```dart theme={null}
HuxDialog(
size: HuxDialogSize.large,
title: 'Complex Dialog',
content: Column(
children: [
Text('Multiple sections'),
SizedBox(height: 16),
Text('Forms and widgets'),
SizedBox(height: 16),
Text('Extended content'),
],
),
)
```
### Extra Large Dialog
Maximum size for extensive content:
```dart theme={null}
HuxDialog(
size: HuxDialogSize.extraLarge,
title: 'Full Screen Dialog',
content: Container(
height: 400,
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) => ListTile(
title: Text('Item ${index + 1}'),
),
),
),
)
```
## Using showHuxDialog
For convenience, Hux provides a `showHuxDialog` function that wraps the dialog in a `showDialog` call:
```dart theme={null}
final bool? result = await showHuxDialog(
context: context,
title: 'Confirm Action',
content: Text('Are you sure?'),
actions: [
HuxButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('Cancel'),
variant: HuxButtonVariant.secondary,
),
HuxButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('Confirm'),
),
],
);
if (result == true) {
// User confirmed
print('Action confirmed');
}
```
## Properties
### Core Properties
* `title` - Optional title text displayed in the dialog header
* `subtitle` - Optional subtitle text displayed below the title
* `content` - The main content widget to display in the dialog body
* `actions` - Optional list of action buttons displayed at the bottom
### Appearance Properties
* `variant` - Visual variant of the dialog (default, destructive, success, warning)
* `size` - Size variant of the dialog (small, medium, large, extraLarge)
* `showCloseButton` - Whether to show a close button in the header (default: true)
### Behavior Properties
* `barrierDismissible` - Whether the dialog can be dismissed by tapping outside
* `clipBehavior` - How to clip the dialog content
* `shape` - Custom shape for the dialog
* `insetPadding` - Padding around the dialog content
## Styling & Layout
### Dimensions
* **Small**: Max width 400px, min width 300px
* **Medium**: Max width 500px, min width 350px (default)
* **Large**: Max width 700px, min width 500px
* **Extra Large**: Max width 900px, min width 700px
### Color System
* **Background**: `HuxTokens.surfaceElevated(context)`
* **Text**: `HuxTokens.textPrimary(context)` and `HuxTokens.textSecondary(context)`
* **Borders**: `HuxTokens.borderPrimary(context)` and `HuxTokens.borderSecondary(context)`
* **Shadows**: `HuxTokens.shadowColor(context)` with proper opacity
### Typography
* **Title**: 18-24px with medium weight (based on size)
* **Subtitle**: 14px with secondary text color
* **Content**: Inherits from theme
## Accessibility
### Screen Reader Support
* Proper semantic labeling for dialog content
* Title and subtitle announcements
* Action button descriptions
### Keyboard Navigation
* Tab key support for action buttons
* Enter/Space key activation
* Escape key dismissal (when barrierDismissible is true)
### Focus Management
* Automatic focus on first action button
* Proper focus trapping within dialog
* Focus restoration on dialog close
## Best Practices
* Use **Small** for simple confirmations
* Use **Medium** for standard content (default)
* Use **Large** for forms or complex content
* Use **Extra Large** for extensive content or full-screen experiences
* Place primary actions on the right
* Use secondary variant for cancel/dismiss actions
* Limit to 2-3 action buttons for clarity
* Use clear, action-oriented button text
* Keep titles concise and descriptive
* Use subtitles for additional context
* Structure content with proper spacing
* Consider mobile screen sizes
* Provide meaningful titles and subtitles
* Use semantic button labels
* Ensure proper contrast ratios
* Test with screen readers
## Examples
Create dialogs with form inputs and validation
Build multi-step confirmation processes
Show rich content in modal dialogs
Customize dialog appearance and behavior
## Related Components
* [HuxButton](/components/buttons) - Action buttons for dialogs
* [HuxCard](/components/cards) - Content containers
* [HuxInput](/components/input) - Form inputs within dialogs
* [HuxAlert](/components/alert) - Non-modal feedback messages
# Dropdown
Source: https://docs.thehuxdesign.com/components/dropdown
A customizable dropdown/select component with various styles and variants
## Overview
`HuxDropdown` is a versatile dropdown/select component that provides multiple visual variants, sizes, and supports custom item rendering with icons. It adapts seamlessly to light and dark themes.
## Basic Usage
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
## Variants
HuxDropdown supports four visual variants through the `HuxButtonVariant` enum:
### Primary
The default variant with a filled background using the primary color.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
variant: HuxButtonVariant.primary,
)
```
### Secondary
A subtle variant with a light background and border.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
variant: HuxButtonVariant.secondary,
)
```
### Outline
A transparent dropdown with only a border outline.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
variant: HuxButtonVariant.outline,
)
```
### Ghost
A minimal transparent dropdown without borders.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
variant: HuxButtonVariant.ghost,
)
```
## States
### Default
Shows the placeholder text when no value is selected.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: null,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
### Expanded
Shows the dropdown panel with options.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
HuxDropdownItem(
value: 'item3',
child: Text('Item 3'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
### Selected
Shows the selected option.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: 'Item 1',
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
### Disabled
Prevents user interaction.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: null, // or enabled: false
placeholder: 'Select option',
enabled: false,
)
```
## Sizes
HuxDropdown supports three size variants through the `HuxButtonSize` enum:
### Small
Compact size for tight spaces (32px height).
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
size: HuxButtonSize.small,
)
```
### Medium
Default size for most use cases (40px height).
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
size: HuxButtonSize.medium, // Default
)
```
### Large
Prominent size for important selections (48px height).
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'item1',
child: Text('Item 1'),
),
HuxDropdownItem(
value: 'item2',
child: Text('Item 2'),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
size: HuxButtonSize.large,
)
```
## With Icons
Enhance dropdown items with icons.
```dart theme={null}
HuxDropdown(
items: [
HuxDropdownItem(
value: 'user',
child: Row(
children: [
Icon(FeatherIcons.user, size: 16),
SizedBox(width: 8),
Text('User'),
],
),
),
HuxDropdownItem(
value: 'settings',
child: Row(
children: [
Icon(FeatherIcons.settings, size: 16),
SizedBox(width: 8),
Text('Settings'),
],
),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
## Using Item Widget as Value
By default, HuxDropdown extracts and displays text from the selected item's widget. The `useItemWidgetAsValue` parameter allows you to display the complete item widget (including icons, badges, and complex layouts) as the selected value.
```dart theme={null}
HuxDropdown(
useItemWidgetAsValue: true, // Display full widget instead of just text
items: [
HuxDropdownItem(
value: 'user',
child: Row(
children: [
Icon(LucideIcons.user, size: 16),
SizedBox(width: 8),
Text('User'),
],
),
),
HuxDropdownItem(
value: 'settings',
child: Row(
children: [
Icon(LucideIcons.settings, size: 16),
SizedBox(width: 8),
Text('Settings'),
],
),
),
],
value: selectedValue,
onChanged: (value) => setState(() => selectedValue = value),
placeholder: 'Select option',
)
```
With this feature enabled, the selected value will show the complete widget with all its visual elements (icons, badges, custom layouts), providing a richer visual experience compared to text-only representation.
## Custom Colors
Override the primary color of the dropdown.
```dart theme={null}
HuxDropdown(
primaryColor: Colors.purple,
// ...
)
```
## API Reference
### HuxDropdown Properties
| Property | Type | Default | Description |
| ---------------------- | -------------------------- | ----------------- | ----------------------------------------------------------- |
| `items` | `List>` | **required** | List of dropdown items |
| `value` | `T?` | `null` | Currently selected value |
| `onChanged` | `ValueChanged?` | `null` | Called when selection changes |
| `placeholder` | `String` | `'Select option'` | Text shown when no value is selected |
| `variant` | `HuxButtonVariant` | `outline` | Visual style of the dropdown |
| `size` | `HuxButtonSize` | `medium` | Size of the dropdown |
| `primaryColor` | `Color?` | `null` | Optional primary color override |
| `enabled` | `bool` | `true` | Whether the dropdown is enabled |
| `maxHeight` | `double` | `200` | Maximum height of the dropdown panel |
| `useItemWidgetAsValue` | `bool` | `false` | Display the complete item widget instead of extracting text |
### HuxDropdownItem Properties
| Property | Type | Default | Description |
| -------- | -------- | ------------ | ----------------------------------- |
| `value` | `T` | **required** | The value associated with this item |
| `child` | `Widget` | **required** | The widget to display for this item |
## Accessibility
HuxDropdown includes several accessibility features:
### Automatic Contrast
Text color is automatically calculated to ensure WCAG AA compliance (4.5:1 contrast ratio) against any background color.
### Keyboard Navigation
* Arrow keys to navigate items
* Enter/Space to open/close and select
* Escape to close dropdown
### Focus States
Proper focus management and visible focus indicators.
### Semantic Labels
Clear labels and roles for screen readers.
## Best Practices
* Use **Large** for primary selection fields
* Use **Medium** for most standard forms
* Use **Small** for compact interfaces or filters
* Use descriptive placeholders
* Group related dropdowns logically
* Consider adding helper text for complex selections
* Keep items concise
* Use icons to enhance visual scanning
* Order items logically (e.g., alphabetically)
## Examples
See dropdowns in action within forms
Apply custom colors and themes
Ensure your dropdowns are accessible
Use dropdowns for data filtering
# Components
Source: https://docs.thehuxdesign.com/components/index
Explore all Hux UI components
# Components
Hux UI provides a comprehensive collection of beautiful, customizable components for Flutter. Browse all available components below.
**Try them live!** See all components in action at [ui.thehuxdesign.com](https://ui.thehuxdesign.com)
## Feedback & Status
Message boxes with dismissible functionality
Status indicators with semantic variants
Customizable loading indicators and overlays
Progress bars and indicators
Toast notifications and snackbars
Contextual information on hover
## Input & Forms
Multiple variants with loading states
Interactive checkbox with custom styling
Modern date picker with calendar overlay
Dropdown menus and select inputs
Enhanced text input with validation
Radio button groups
Range and value sliders
Toggle switch with smooth animations
Multi-line text input
Toggle buttons and button groups
## Layout & Navigation
User images with initials fallback
Navigation breadcrumb trails
Flexible card component with actions
Right-click context menus
Modal dialogs and popups
Page navigation controls
Collapsible sidebar navigation
Tab navigation and panels
## Data & Utilities
Beautiful data visualization
Command palette and search
One-time password input
# Input
Source: https://docs.thehuxdesign.com/components/input
Enhanced text input component with validation and consistent styling
## Overview
HuxInput is a customizable text input component with consistent styling and extensive customization options. It provides a clean, modern text input with support for labels, hints, validation, icons, and different sizes while automatically adapting to light and dark themes.
## Basic Usage
### Simple Text Input
```dart theme={null}
HuxInput(
label: 'Email',
hint: 'Enter your email address',
)
```
### Input with Managed Focus
```dart theme={null}
final inputFocusNode = FocusNode();
HuxInput(
focusNode: inputFocusNode,
label: 'Search',
hint: 'Start typing...',
)
```
### Input with Icon
```dart theme={null}
HuxInput(
hint: 'Search for products...',
prefixIcon: Icon(FeatherIcons.search),
)
```
### Input with Helper Text
```dart theme={null}
HuxInput(
label: 'Password',
hint: 'Enter your password',
prefixIcon: Icon(FeatherIcons.lock),
obscureText: true,
helperText: 'Password must be at least 6 characters',
)
```
### Input with Error State
```dart theme={null}
HuxInput(
label: 'Email',
hint: 'Enter your email address',
prefixIcon: Icon(FeatherIcons.mail),
errorText: 'Please enter a valid email address',
validator: (value) {
if (value == null || value.isEmpty) {
return 'Email is required';
}
if (!value.contains('@')) {
return 'Please enter a valid email address';
}
return null;
},
)
```
## Properties
### Core Properties
* `label` - Optional field label text displayed above the input
* `hint` - Placeholder text displayed inside the input when empty
* `controller` - TextEditingController for managing input state
* `focusNode` - FocusNode for managing input focus, useful with widgets such as `RawAutocomplete`
* `onChanged` - Callback triggered when the input value changes
* `onSubmitted` - Callback triggered when the user submits the input
### Validation Properties
* `validator` - Form validation function that returns error text or null
* `errorText` - Custom error message (overrides validator output)
* `helperText` - Helper text displayed below the input
### Icon Properties
* `prefixIcon` - Icon displayed at the beginning of the input
* `suffixIcon` - Icon displayed at the end of the input
* `iconSize` - Custom size for icons (default: 18px)
### Behavior Properties
* `obscureText` - Whether to hide the input text (for passwords)
* `enabled` - Whether the input is interactive
* `maxLines` - Maximum number of text lines (default: 1)
* `keyboardType` - Type of keyboard to display
* `textInputAction` - Action button for the keyboard
### Layout Properties
* `width` - Custom width (default: full width)
## Styling & Dimensions
### Fixed Dimensions
* **Height**: 40px (consistent across all inputs)
* **Border Radius**: 8px (rounded corners)
* **Font Size**: 14px with 1.4 line height
### Padding & Spacing
* **Horizontal Padding**: 18px (left and right inside input)
* **Vertical Padding**: 12px (top and bottom inside input)
* **Label Gap**: 6px (space between label and input)
### Icon Spacing
* **Icon Size**: 18px (default, customizable)
* **Icon Outer Padding**: 14px (space from edge to icon)
* **Icon Inner Padding**: 4px (space between icon and text)
## Color System
### Border Colors
* **Default**: `HuxTokens.borderPrimary(context)`
* **Focused**: `HuxTokens.primary(context)` with 50% opacity
* **Error**: `HuxTokens.borderDestructive(context)`
* **Focused Error**: `HuxTokens.textDestructive(context)` with 2px width
* **Disabled**: `HuxTokens.borderSecondary(context)`
### Background Colors
* **Enabled**: `HuxTokens.surfacePrimary(context)`
* **Disabled**: `HuxTokens.surfaceSecondary(context)`
### Text Colors
* **Input Text**: Inherits from theme with 14px font size
* **Label Text**: `HuxTokens.textSecondary(context)` with medium weight
* **Icon Color**: `HuxTokens.iconSecondary(context)`
## States
### Enabled State
* Fully interactive with normal styling
* Responds to user input and focus
### Focused State
* Enhanced border with primary color
* Visual focus indicator for accessibility
### Disabled State
* Reduced opacity and non-interactive
* Maintains visual consistency
## Examples
See HuxInput in action within forms
Learn form validation best practices
## Related Components
* [HuxDateInput](/components/date-input) - Specialized date input component
* [HuxCheckbox](/components/checkbox) - Interactive checkbox component
* [HuxSwitch](/components/switch) - Toggle switch component
# KBD
Source: https://docs.thehuxdesign.com/components/kbd
Beautiful keyboard key component for shortcuts and UI indicators
## Overview
`HuxKBD` is a small, styled box component that resembles a physical keyboard key. It is primarily used to display keyboard shortcuts (e.g., "⌘K") or specific keys (e.g., "Enter", "Esc") in a visually distinct way. It is fully theme-aware and adapts seamlessly to light and dark modes.
## Basic Usage
```dart theme={null}
HuxKBD(shortcut: '⌘K')
```
## Examples
### Single Keys
Display individual modifier or action keys.
```dart theme={null}
Row(
children: [
HuxKBD(shortcut: '⌘'),
HuxKBD(shortcut: '⇧'),
HuxKBD(shortcut: 'Enter'),
],
)
```
### Combinations
Display keyboard shortcut combinations.
```dart theme={null}
HuxKBD(shortcut: '⌘⇧P')
```
### Inline with Text
Use `HuxKBD` within text to provide clear action indicators.
```dart theme={null}
Row(
children: [
Text('Press'),
SizedBox(width: 4),
HuxKBD(shortcut: 'Enter'),
SizedBox(width: 4),
Text('to submit'),
],
)
```
## Integration with HuxCommand
`HuxKBD` is integrated into the `HuxCommand` palette by default to display shortcuts for each command item. This ensures a consistent look and feel throughout the library.
```dart theme={null}
HuxCommandItem(
id: 'save',
label: 'Save',
shortcut: '⌘S', // Uses HuxKBD internally
onExecute: () => print('Saved'),
)
```
## API Reference
### HuxKBD Properties
| Property | Type | Default | Description |
| ---------- | -------- | ------------ | -------------------------------------------------------- |
| `shortcut` | `String` | **required** | The text to display inside the key (e.g., "⌘K", "Enter") |
## Accessibility
`HuxKBD` uses a monospace font and consistent padding to ensure readability for the special symbols often used in shortcuts. It automatically uses `HuxTokens.surfaceSecondary` for its background and `HuxTokens.textTertiary` for its text, ensuring appropriate contrast in both light and dark themes.
# Loading
Source: https://docs.thehuxdesign.com/components/loading
Loading indicators and overlays for async operations
## Overview
Hux UI provides loading components for indicating async operations:
* **HuxLoading** - Customizable loading indicators
* **HuxLoadingOverlay** - Full-screen loading overlays
## Component Variants
### Small Loading Indicator
Compact loading indicator for tight spaces:
```dart theme={null}
HuxLoading(size: HuxLoadingSize.small)
```
### Medium Loading Indicator
Standard loading indicator (default size):
```dart theme={null}
HuxLoading(size: HuxLoadingSize.medium)
```
### Large Loading Indicator
Prominent loading indicator for important operations:
```dart theme={null}
HuxLoading(size: HuxLoadingSize.large)
```
### Extra Large Loading Indicator
Maximum size loading indicator:
```dart theme={null}
HuxLoading(size: HuxLoadingSize.extraLarge)
```
### Loading with Custom Colors
Loading indicator with theme-aware colors:
```dart theme={null}
HuxLoading(
size: HuxLoadingSize.medium,
color: HuxTokens.primary(context),
)
```
## HuxLoading
### Sizes
* `small` - Compact loading indicator
* `medium` - Standard loading indicator (default)
* `large` - Prominent loading indicator
## HuxLoadingOverlay
Full-screen overlay that blocks user interaction during loading operations. Perfect for API calls, file uploads, or any long-running processes.
```dart theme={null}
HuxLoadingOverlay(
isLoading: _isLoading,
message: 'Processing...',
child: YourContent(),
)
```
### Properties
* **`isLoading`** - Boolean flag to control overlay visibility
* **`message`** - Optional loading message displayed above the spinner
* **`child`** - The main content widget that will be covered by the overlay
* **`barrierColor`** - Optional custom barrier color (defaults to semi-transparent black)
* **`spinnerColor`** - Optional custom spinner color (defaults to theme primary color)
### Advanced Usage
```dart theme={null}
HuxLoadingOverlay(
isLoading: _isLoading,
message: 'Uploading files...',
barrierColor: Colors.black54,
spinnerColor: HuxTokens.primary(context),
child: Scaffold(
appBar: AppBar(title: Text('File Upload')),
body: FileUploadForm(),
),
)
```
## Usage Example
```dart theme={null}
class AsyncOperationExample extends StatefulWidget {
@override
_AsyncOperationExampleState createState() => _AsyncOperationExampleState();
}
class _AsyncOperationExampleState extends State {
bool _isLoading = false;
void _performAsyncOperation() async {
setState(() {
_isLoading = true;
});
// Simulate async work
await Future.delayed(Duration(seconds: 3));
setState(() {
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return HuxLoadingOverlay(
isLoading: _isLoading,
message: 'Loading data...',
child: Column(
children: [
HuxButton(
onPressed: _isLoading ? null : _performAsyncOperation,
isLoading: _isLoading,
child: Text('Start Operation'),
),
],
),
);
}
}
```
## Best Practices
1. **Use for blocking operations** - Perfect for API calls, file uploads, or data processing
2. **Provide clear messages** - Help users understand what's happening
3. **Consider duration** - For very short operations (\< 500ms), consider using inline loading instead
4. **Accessibility** - The overlay automatically handles screen reader announcements
5. **Theme integration** - Colors automatically adapt to light/dark themes
## Accessibility Features
* **Screen reader support** - Loading state is announced to assistive technologies
* **Focus management** - Prevents interaction with background content during loading
* **High contrast support** - Uses Hux UI's accessible color tokens
* **Keyboard navigation** - Properly blocks keyboard input during loading states
# Pagination
Source: https://docs.thehuxdesign.com/components/pagination
Navigate through pages with HuxPagination component
## Overview
The HuxPagination component provides an intuitive way to navigate through multiple pages of content. It displays page numbers with intelligent ellipsis handling for large page counts and includes previous/next arrow buttons.
## Basic Usage
```dart theme={null}
import 'package:hux/hux.dart';
HuxPagination(
currentPage: 5,
totalPages: 20,
onPageChanged: (page) {
print('Selected page: $page');
},
)
```
## Properties
| Property | Type | Required | Default | Description |
| ---------------- | ------------------- | -------- | ------- | ----------------------------------- |
| `currentPage` | `int` | Yes | - | The currently active page (1-based) |
| `totalPages` | `int` | Yes | - | The total number of pages |
| `onPageChanged` | `ValueChanged` | Yes | - | Callback when a page is selected |
| `maxPagesToShow` | `int` | No | `5` | Maximum page buttons to display |
## Examples
### Basic Pagination
```dart theme={null}
HuxPagination(
currentPage: 3,
totalPages: 10,
onPageChanged: (page) {
setState(() {
currentPage = page;
});
},
)
```
### Large Page Count
When you have many pages, the component automatically shows ellipsis:
```dart theme={null}
HuxPagination(
currentPage: 15,
totalPages: 100,
maxPagesToShow: 7,
onPageChanged: (page) {
// Handle page change
},
)
```
### Custom Page Range
```dart theme={null}
HuxPagination(
currentPage: 1,
totalPages: 3,
maxPagesToShow: 3,
onPageChanged: (page) {
// Handle page change
},
)
```
## Accessibility
The HuxPagination component is built with accessibility in mind:
* **WCAG AA Compliant**: Uses proper contrast ratios for all text and backgrounds
* **Keyboard Navigation**: All buttons are focusable and keyboard accessible
* **Screen Reader Support**: Proper semantic markup and ARIA labels
* **Touch Targets**: Meets minimum touch target size requirements
## Styling
The component uses Hux's design tokens for consistent theming:
* **Theme-aware colors**: Automatically adapts to light/dark themes
* **Consistent spacing**: Uses Hux spacing tokens
* **Typography**: Follows Hux text style patterns
* **Interactive states**: Proper hover and focus states
The pagination component automatically handles edge cases like single page scenarios and ensures the current page is always visible in the page range.
## Best Practices
1. **Always provide feedback**: Use the `onPageChanged` callback to update your content
2. **Handle edge cases**: The component handles single pages and large page counts automatically
3. **Consider mobile**: The compact design works well on mobile devices
4. **Accessibility**: Ensure your page content changes are announced to screen readers
# Progress
Source: https://docs.thehuxdesign.com/components/progress
Linear progress indicator for task completion and status tracking
## Overview
HuxProgress is a customizable linear progress indicator that displays the completion status of a task or process. It provides smooth animations, consistent styling, and automatic theme adaptation, making it perfect for showing upload progress, download status, or any task completion percentage.
## Basic Usage
### Basic Progress
```dart theme={null}
HuxProgress(
value: 0.5,
)
```
### Progress with Label
```dart theme={null}
HuxProgress(
value: 0.75,
label: 'Uploading',
)
```
### Progress with Value Display
```dart theme={null}
HuxProgress(
value: 0.6,
label: 'Storage Used',
showValue: true,
)
```
## Variants
HuxProgress supports three visual variants to indicate different states:
### Primary Variant
```dart theme={null}
HuxProgress(
value: 0.6,
label: 'Progress',
variant: HuxProgressVariant.primary,
showValue: true,
)
```
### Success Variant
```dart theme={null}
HuxProgress(
value: 0.8,
label: 'Upload Complete',
variant: HuxProgressVariant.success,
showValue: true,
)
```
### Destructive Variant
```dart theme={null}
HuxProgress(
value: 0.3,
label: 'Error',
variant: HuxProgressVariant.destructive,
showValue: true,
)
```
## Sizes
HuxProgress comes in three size variants:
### Small
```dart theme={null}
HuxProgress(
value: 0.5,
size: HuxProgressSize.small,
label: 'Small Progress',
)
```
### Medium (Default)
```dart theme={null}
HuxProgress(
value: 0.5,
size: HuxProgressSize.medium,
label: 'Medium Progress',
)
```
### Large
```dart theme={null}
HuxProgress(
value: 0.5,
size: HuxProgressSize.large,
label: 'Large Progress',
)
```
## Custom Values
By default, HuxProgress uses values between 0.0 and 1.0. You can customize the range:
```dart theme={null}
HuxProgress(
value: 75.0,
min: 0.0,
max: 100.0,
label: 'Storage Used',
showValue: true,
)
```
When using custom min/max values, the displayed value will show as a number instead of a percentage.
## Custom Colors
You can customize both the progress fill color and background color:
```dart theme={null}
HuxProgress(
value: 0.7,
label: 'Custom Progress',
color: Colors.blue,
backgroundColor: Colors.grey[200],
)
```
## Custom Border Radius
```dart theme={null}
HuxProgress(
value: 0.6,
label: 'Rounded Progress',
borderRadius: 8.0,
)
```
## Animated Progress
HuxProgress automatically animates when the value changes:
```dart theme={null}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
double _progress = 0.0;
void _startUpload() {
// Simulate upload progress
Timer.periodic(Duration(milliseconds: 100), (timer) {
setState(() {
_progress += 0.01;
if (_progress >= 1.0) {
_progress = 1.0;
timer.cancel();
}
});
});
}
@override
Widget build(BuildContext context) {
return HuxProgress(
value: _progress,
label: 'Uploading file...',
showValue: true,
variant: HuxProgressVariant.success,
);
}
}
```
## API Reference
### HuxProgress
| Property | Type | Default | Description |
| ----------------- | -------------------- | ---------------------------- | ----------------------------------------------------------- |
| `value` | `double` | **required** | The current progress value (between min and max) |
| `min` | `double` | `0.0` | Minimum value for the progress |
| `max` | `double` | `1.0` | Maximum value for the progress |
| `label` | `String?` | `null` | Optional label displayed above the progress bar |
| `showValue` | `bool` | `false` | Whether to show the current value as a percentage or number |
| `size` | `HuxProgressSize` | `HuxProgressSize.medium` | Size variant of the progress bar |
| `variant` | `HuxProgressVariant` | `HuxProgressVariant.primary` | Visual variant of the progress bar |
| `backgroundColor` | `Color?` | `null` | Custom background color for the progress track |
| `color` | `Color?` | `null` | Custom color for the progress fill |
| `borderRadius` | `double?` | `null` | Border radius for the progress bar |
### HuxProgressSize
* `small` - Small progress bar (4px height)
* `medium` - Medium progress bar (6px height)
* `large` - Large progress bar (8px height)
### HuxProgressVariant
* `primary` - Primary progress using theme primary color
* `success` - Success progress using green color
* `destructive` - Destructive progress using red color
## Best Practices
* Use progress indicators for operations that take more than a few seconds
* Show labels to provide context about what is loading
* Use the success variant for completed operations
* Use the destructive variant for errors or failed operations
* Consider using `showValue: true` when precise progress information is important
* For uploads/downloads, update the progress value frequently for smooth animation
# Radio
Source: https://docs.thehuxdesign.com/components/radio
Radio button controls for single selection from groups
# HuxRadio
Radio button controls for single selection from groups with consistent sizing and theme adaptation.
## Overview
The `HuxRadio` component provides radio button controls that allow users to select a single option from a group of related choices. It features consistent 18x18 pixel sizing for optimal UX and automatic light/dark theme adaptation.
## Properties
* `value` - The value represented by this radio button
* `groupValue` - The currently selected value for the group
* `onChanged` - Callback when the radio button is selected
* `label` - Optional text label for the radio button
* `size` - Size variant (small, medium, large)
* `isDisabled` - Whether the radio button is disabled
## States
### Unchecked State
```dart theme={null}
HuxRadio(
value: 'option1',
groupValue: null, // No selection yet
onChanged: (value) => setState(() => selectedValue = value),
label: 'Option 1',
)
```
* Empty radio button with border
* Ready for user interaction
* Part of a radio group
### Checked State
```dart theme={null}
HuxRadio(
value: 'option1',
groupValue: 'option1', // This option is selected
onChanged: (value) => setState(() => selectedValue = value),
label: 'Option 1',
)
```
* Filled radio button with dot
* Visual confirmation of selection
* Only one radio button can be selected per group
### Disabled State
```dart theme={null}
HuxRadio(
value: 'disabled',
groupValue: selectedValue,
onChanged: null, // This makes it disabled
label: 'Disabled Option',
isDisabled: true,
)
```
* Reduced opacity and non-interactive
* Maintains visual consistency
* Cannot be selected even if clicked
## Examples
### Basic Radio Group
```dart theme={null}
String selectedValue = 'option1';
Column(
children: [
HuxRadio(
value: 'option1',
groupValue: selectedValue,
onChanged: (value) => setState(() => selectedValue = value!),
label: 'Option 1',
),
HuxRadio(
value: 'option2',
groupValue: selectedValue,
onChanged: (value) => setState(() => selectedValue = value!),
label: 'Option 2',
),
],
)
```
## Related Components
* [HuxCheckbox](/components/checkbox) - For multiple selection
* [HuxSwitch](/components/switch) - For toggle states
* [HuxButton](/components/buttons) - For action buttons
# Sidebar
Source: https://docs.thehuxdesign.com/components/sidebar
Complete sidebar navigation component for app-wide navigation with selection state management
## Overview
HuxSidebar is a complete navigation component that provides a consistent sidebar layout with header, navigation items, and optional footer. It handles selection state management automatically and provides a clean API for sidebar navigation in your Flutter applications.
## Basic Usage
### Simple Sidebar
Basic sidebar with navigation items:
```dart theme={null}
HuxSidebar(
items: [
HuxSidebarItemData(
id: 'dashboard',
icon: LucideIcons.home,
label: 'Dashboard',
),
HuxSidebarItemData(
id: 'settings',
icon: LucideIcons.settings,
label: 'Settings',
),
],
selectedItemId: 'dashboard',
onItemSelected: (itemId) => print('Selected: $itemId'),
)
```
### Sidebar with Header
Sidebar with custom header content:
```dart theme={null}
HuxSidebar(
header: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'My App',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 4),
Text(
'Navigation',
style: TextStyle(fontSize: 14, color: Colors.grey),
),
],
),
),
items: navigationItems,
selectedItemId: selectedId,
onItemSelected: handleItemSelection,
)
```
### Sidebar with Footer
Include footer content like user profile or settings:
```dart theme={null}
HuxSidebar(
items: navigationItems,
selectedItemId: currentRoute,
onItemSelected: navigateToRoute,
footer: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
HuxAvatar(name: 'John Doe', size: HuxAvatarSize.small),
SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('John Doe', style: TextStyle(fontWeight: FontWeight.w500)),
Text('john@example.com', style: TextStyle(fontSize: 12)),
],
),
),
],
),
),
)
```
## Navigation Items
### HuxSidebarItemData
Define individual navigation items:
```dart theme={null}
HuxSidebarItemData(
id: 'unique-id', // Required: Unique identifier
label: 'Dashboard', // Required: Display label
icon: LucideIcons.home, // Optional: Leading icon
)
```
### Multiple Items
Create a list of navigation items:
```dart theme={null}
final items = [
HuxSidebarItemData(
id: 'dashboard',
icon: LucideIcons.home,
label: 'Dashboard',
),
HuxSidebarItemData(
id: 'analytics',
icon: LucideIcons.barChart,
label: 'Analytics',
),
HuxSidebarItemData(
id: 'settings',
icon: LucideIcons.settings,
label: 'Settings',
),
];
```
## Properties
### HuxSidebar Properties
| Property | Type | Default | Description |
| ---------------- | -------------------------- | -------------- | ------------------------------ |
| `items` | `List` | **required** | List of navigation items |
| `onItemSelected` | `Function(String)` | **required** | Callback when item is selected |
| `selectedItemId` | `String?` | `null` | Currently selected item ID |
| `header` | `Widget?` | `null` | Optional header widget |
| `footer` | `Widget?` | `null` | Optional footer widget |
| `width` | `double` | `250` | Width of the sidebar |
| `padding` | `EdgeInsets` | `vertical: 16` | Padding around items |
### HuxSidebarItemData Properties
| Property | Type | Default | Description |
| -------- | ----------- | ------------ | ------------------------------ |
| `id` | `String` | **required** | Unique identifier for the item |
| `label` | `String` | **required** | Display label for the item |
| `icon` | `IconData?` | `null` | Optional leading icon |
## Styling
### Custom Width
Adjust sidebar width for your layout:
```dart theme={null}
HuxSidebar(
width: 280, // Custom width
items: navigationItems,
onItemSelected: handleSelection,
)
```
### Custom Padding
Control spacing around navigation items:
```dart theme={null}
HuxSidebar(
padding: EdgeInsets.all(20),
items: navigationItems,
onItemSelected: handleSelection,
)
```
## States
### Selection State
Items automatically show selected state based on `selectedItemId`:
* **Selected**: Highlighted with primary color background
* **Unselected**: Default appearance with hover state
* **Hovered**: Subtle background change on mouse hover
## Integration Examples
### With Routing
Integrate with your app's routing system:
```dart theme={null}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
String _currentRoute = 'dashboard';
void _handleNavigation(String itemId) {
setState(() {
_currentRoute = itemId;
});
// Navigate to route
Navigator.pushNamed(context, '/$itemId');
}
@override
Widget build(BuildContext context) {
return Row(
children: [
HuxSidebar(
items: [
HuxSidebarItemData(id: 'dashboard', icon: LucideIcons.home, label: 'Dashboard'),
HuxSidebarItemData(id: 'users', icon: LucideIcons.users, label: 'Users'),
HuxSidebarItemData(id: 'settings', icon: LucideIcons.settings, label: 'Settings'),
],
selectedItemId: _currentRoute,
onItemSelected: _handleNavigation,
),
Expanded(
child: ContentArea(route: _currentRoute),
),
],
);
}
}
```
### With Responsive Layout
Make sidebar responsive to screen size:
```dart theme={null}
LayoutBuilder(
builder: (context, constraints) {
final bool isWideScreen = constraints.maxWidth > 800;
return Row(
children: [
if (isWideScreen)
HuxSidebar(
width: 250,
items: navigationItems,
selectedItemId: currentRoute,
onItemSelected: handleNavigation,
),
Expanded(child: ContentArea()),
],
);
},
)
```
## Best Practices
* Keep navigation items between 5-10 for optimal UX
* Group related items together
* Use clear, concise labels
* Include meaningful icons that represent the destination
* Always maintain a selected state
* Update selected item when route changes
* Provide visual feedback for current location
* Consider highlighting active section in multi-level navigation
* Hide sidebar on small screens and use drawer instead
* Adjust sidebar width based on screen size
* Consider collapsible sidebar for medium screens
* Ensure touch targets are at least 44x44 pixels
* Ensure keyboard navigation works smoothly
* Provide clear focus indicators
* Use semantic labels for screen readers
* Maintain sufficient color contrast (WCAG AA)
## Theme Integration
HuxSidebar automatically adapts to your app's theme:
* **Light Mode**: Clean white background with subtle borders
* **Dark Mode**: Dark background with appropriate contrast
* **Selected State**: Uses theme primary color
* **Hover State**: Subtle background change based on theme
## Related Components
* [HuxButton](/components/buttons) - Action buttons within sidebar
* [HuxAvatar](/components/avatar) - User avatars in sidebar footer
* [HuxBadge](/components/badge) - Notification badges on items
* [HuxTooltip](/components/tooltip) - Tooltips for collapsed sidebar
# Slider
Source: https://docs.thehuxdesign.com/components/slider
Customizable slider component with smooth animations and theme-aware styling
## Overview
HuxSlider is a customizable slider component with smooth animations, consistent styling, and automatic theme adaptation. It provides a clean, modern interface for selecting numeric values within a range while maintaining accessibility standards.
## Basic Usage
### Basic Slider
```dart theme={null}
double sliderValue = 50.0;
HuxSlider(
value: sliderValue,
onChanged: (value) {
setState(() {
sliderValue = value;
});
},
min: 0,
max: 100,
)
```
### Slider with Label
```dart theme={null}
double volume = 75.0;
HuxSlider(
value: volume,
onChanged: (value) {
setState(() {
volume = value;
});
},
min: 0,
max: 100,
label: 'Volume',
)
```
### Slider with Value Display
```dart theme={null}
double brightness = 60.0;
HuxSlider(
value: brightness,
onChanged: (value) {
setState(() {
brightness = value;
});
},
min: 0,
max: 100,
label: 'Brightness',
showValue: true,
)
```
### Slider with Divisions
```dart theme={null}
double rating = 3.0;
HuxSlider(
value: rating,
onChanged: (value) {
setState(() {
rating = value;
});
},
min: 1,
max: 5,
divisions: 4, // Creates 5 discrete values (1, 2, 3, 4, 5)
label: 'Rating',
showValue: true,
)
```
### Disabled Slider
```dart theme={null}
HuxSlider(
value: 50.0,
onChanged: null, // Disables the slider
min: 0,
max: 100,
label: 'Volume',
)
```
## Properties
### Core Properties
* `value` - Current slider value (double)
* `onChanged` - Callback triggered when value changes (null for disabled)
* `min` - Minimum value (default: 0.0)
* `max` - Maximum value (default: 100.0)
### Display Properties
* `label` - Optional label displayed above the slider
* `showValue` - Whether to display the current value next to the label
* `divisions` - Number of discrete divisions (null for continuous)
### Styling Properties
* `size` - Slider size variant (small, medium, large)
* `activeColor` - Custom active color (uses primary color by default)
* `isDisabled` - Whether the slider is disabled
## Size Variants
### Small Slider
* **Track Height**: 2px
* **Thumb Size**: 14px × 14px
* **Overlay Size**: 28px × 28px
* **Tick Size**: 2px
### Medium Slider ⭐ **Default**
* **Track Height**: 3px
* **Thumb Size**: 18px × 18px
* **Overlay Size**: 36px × 36px
* **Tick Size**: 3px
### Large Slider
* **Track Height**: 4px
* **Thumb Size**: 22px × 22px
* **Overlay Size**: 44px × 44px
* **Tick Size**: 4px
## Styling & Colors
### Slider Colors
* **Active Track**: `HuxTokens.primary(context)` (or custom `activeColor`)
* **Inactive Track**: `HuxTokens.surfaceSecondary(context)`
* **Thumb**: `HuxTokens.primary(context)` (or custom `activeColor`)
* **Overlay**: Primary color with 10% opacity
* **Tick Marks**: `HuxTokens.primary(context)` (when divisions are used)
### Disabled State Colors
* **Active Track (Disabled)**: `HuxTokens.borderSecondary(context)`
* **Inactive Track (Disabled)**: `HuxTokens.surfaceSecondary(context)` with 50% opacity
* **Thumb (Disabled)**: `HuxTokens.surfaceSecondary(context)`
* **Text (Disabled)**: `HuxTokens.textDisabled(context)`
## Custom Colors
You can customize the slider's active color:
```dart theme={null}
HuxSlider(
value: sliderValue,
onChanged: (value) => setState(() => sliderValue = value),
min: 0,
max: 100,
activeColor: Colors.blue,
label: 'Custom Color',
)
```
## Advanced Examples
### Volume Control
```dart theme={null}
double volume = 50.0;
HuxSlider(
value: volume,
onChanged: (value) {
setState(() {
volume = value;
});
// Update audio volume
audioPlayer.setVolume(value / 100);
},
min: 0,
max: 100,
label: 'Volume',
showValue: true,
divisions: 20, // 5% increments
)
```
### Rating Slider
```dart theme={null}
double rating = 3.0;
HuxSlider(
value: rating,
onChanged: (value) {
setState(() {
rating = value;
});
},
min: 1,
max: 5,
divisions: 4, // Creates 5 discrete values
label: 'Rating',
showValue: true,
)
```
### Price Range Filter
```dart theme={null}
double maxPrice = 500.0;
HuxSlider(
value: maxPrice,
onChanged: (value) {
setState(() {
maxPrice = value;
});
// Filter products
filterProducts(maxPrice: value);
},
min: 0,
max: 1000,
label: 'Max Price',
showValue: true,
)
```
### Form Integration
```dart theme={null}
final _formKey = GlobalKey();
double satisfaction = 5.0;
Form(
key: _formKey,
child: Column(
children: [
HuxSlider(
value: satisfaction,
onChanged: (value) {
setState(() {
satisfaction = value;
});
},
min: 1,
max: 10,
divisions: 9,
label: 'Satisfaction Level',
showValue: true,
),
const SizedBox(height: 20),
HuxButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
submitForm(satisfaction: satisfaction);
}
},
child: const Text('Submit'),
),
],
),
)
```
## Accessibility
HuxSlider follows Flutter's accessibility guidelines:
* Supports keyboard navigation
* Provides semantic labels for screen readers
* Maintains proper touch target sizes (minimum 44px × 44px)
* Uses theme-aware colors that meet WCAG contrast requirements
## Best Practices
1. **Use Labels**: Always provide a label to make the slider's purpose clear
2. **Show Values**: Use `showValue: true` when the exact value is important
3. **Use Divisions**: Set `divisions` when you need discrete values (e.g., ratings, steps)
4. **Provide Feedback**: Consider showing additional feedback when the value changes (e.g., updating a preview)
5. **Range Selection**: For range selection, use two sliders or consider a RangeSlider component
## API Reference
### HuxSlider Properties
| Property | Type | Default | Description |
| ------------- | ----------------------- | -------- | ------------------------------- |
| `value` | `double` | — | Current slider value (required) |
| `onChanged` | `ValueChanged?` | — | Callback when value changes |
| `min` | `double` | `0.0` | Minimum value |
| `max` | `double` | `100.0` | Maximum value |
| `divisions` | `int?` | `null` | Number of discrete divisions |
| `label` | `String?` | `null` | Label displayed above slider |
| `showValue` | `bool` | `false` | Whether to show current value |
| `isDisabled` | `bool` | `false` | Whether slider is disabled |
| `size` | `HuxSliderSize` | `medium` | Size variant |
| `activeColor` | `Color?` | `null` | Custom active color |
### HuxSliderSize Enum
* `HuxSliderSize.small` - Small slider for compact layouts
* `HuxSliderSize.medium` - Medium slider for standard use (default)
* `HuxSliderSize.large` - Large slider for emphasis
# Snackbar
Source: https://docs.thehuxdesign.com/components/snackbar
Temporary notification messages with semantic variants and dismissible functionality
## Overview
HuxSnackbar is a message box component that provides clear communication to users through semantic variants (info, success, error) and dismissible functionality. It features a modern glassmorphism design with backdrop blur effects that automatically adapts to light and dark themes while maintaining excellent readability and accessibility.
### Key Features
* **Glassmorphism Design**: Modern frosted glass effect with backdrop blur
* **Fixed Width**: Consistent 400px width positioned at bottom-left
* **Theme-Adaptive**: Different blur intensities for light (5px) and dark (10px) modes
* **Semantic Variants**: Info, success, error, and warning states
* **Auto-positioning**: Floating behavior with proper margins
* **Optional actions**: Add interactive buttons like “Undo”
* **Optional stacking**: Show multiple snackbars at once using the overlay controller
## Component Variants
### Info Snackbar
Informational messages with blue styling:
```dart theme={null}
HuxSnackbar(
message: 'Your changes have been saved successfully!',
variant: HuxSnackbarVariant.info,
onDismiss: () => print('Dismissed'),
)
```
### Success Snackbar
Positive confirmation messages with green styling:
```dart theme={null}
HuxSnackbar(
message: 'Profile updated successfully!',
variant: HuxSnackbarVariant.success,
onDismiss: () => print('Dismissed'),
)
```
### Error Snackbar
Error messages with red styling:
```dart theme={null}
HuxSnackbar(
message: 'Failed to save changes. Please try again.',
variant: HuxSnackbarVariant.error,
onDismiss: () => print('Dismissed'),
)
```
### Warning Snackbar
Warning messages with orange styling:
```dart theme={null}
HuxSnackbar(
message: 'You have unsaved changes. Save before leaving?',
variant: HuxSnackbarVariant.warning,
onDismiss: () => print('Dismissed'),
)
```
## Basic Usage
### Simple Snackbar (via extension)
Show a snackbar from any widget with a `BuildContext`:
```dart theme={null}
context.showHuxSnackbar(message: 'This is a simple snackbar message');
```
### Dismissible Snackbar
Snackbar that can be dismissed by the user:
```dart theme={null}
context.showHuxSnackbar(
message: 'Click the X to dismiss this message',
onDismiss: () => print('Snackbar dismissed'),
);
```
### Snackbar with Actions (Undo / Retry / View)
Add one or more action buttons (for example, “Undo”):
```dart theme={null}
context.showHuxSnackbar(
message: 'Item deleted',
variant: HuxSnackbarVariant.info,
actions: [
HuxSnackbarAction(
label: 'Undo',
onPressed: () {
// Restore the item
},
),
],
);
```
### Stacking multiple snackbars (overlay)
Flutter’s `ScaffoldMessenger` queues snackbars. To **stack** multiple snackbars (show them simultaneously), use the overlay controller:
```dart theme={null}
HuxSnackbarStackController.of(context).show(
const HuxSnackbar(
message: 'Saved',
duration: Duration(seconds: 4),
),
);
HuxSnackbarStackController.of(context).show(
const HuxSnackbar(
message: 'Synced',
duration: Duration(seconds: 4),
),
);
```
## Properties
### HuxSnackbar Properties
| Property | Type | Default | Description |
| ----------- | -------------------------- | ------------ | ----------------------------------------------- |
| `message` | `String` | **required** | The message text to display |
| `variant` | `HuxSnackbarVariant` | `info` | Visual variant of the snackbar |
| `title` | `String?` | `null` | Optional title displayed above the message |
| `onDismiss` | `VoidCallback?` | `null` | Callback when dismiss button is pressed |
| `duration` | `Duration` | `4 seconds` | Duration the snackbar is displayed |
| `showIcon` | `bool` | `true` | Whether to show an icon in the snackbar |
| `actions` | `List?` | `null` | Optional action buttons (Undo/Retry/Close/etc.) |
### HuxSnackbarAction Properties
| Property | Type | Default | Description |
| ----------- | -------------- | ------------ | ----------------------------- |
| `label` | `String` | **required** | Button label (e.g. `"Undo"`) |
| `onPressed` | `VoidCallback` | **required** | Callback when pressed |
| `textColor` | `Color?` | `null` | Optional label color override |
### HuxSnackbarVariant Enum
* `HuxSnackbarVariant.info` - Blue styling for informational messages
* `HuxSnackbarVariant.success` - Green styling for success confirmations
* `HuxSnackbarVariant.error` - Red styling for error messages
* `HuxSnackbarVariant.warning` - Orange styling for warning messages
## Styling
### Custom Colors
Override default colors for specific use cases:
```dart theme={null}
HuxSnackbar(
message: 'Custom styled snackbar',
variant: HuxSnackbarVariant.info,
backgroundColor: Colors.deepPurple,
textColor: Colors.white,
)
```
## Colors
### Theme-Aware Colors
Snackbar automatically adapts to light and dark themes:
* **Info**: Blue tones with appropriate contrast
* **Success**: Green tones with appropriate contrast
* **Error**: Red tones with appropriate contrast
* **Warning**: Orange tones with appropriate contrast
## States
### Default State
Normal snackbar appearance with all interactive elements enabled.
### Dismissed State
Snackbar is removed from the UI after user interaction or auto-dismiss.
### Loading State
For future enhancement - snackbar with loading indicator.
## Accessibility
HuxSnackbar includes several accessibility features:
### Screen Reader Support
* Message content is properly announced
* Dismiss button includes appropriate labels
### Keyboard Navigation
* Tab navigation to dismiss button
* Enter/Space key support for dismissal
* Escape key support for quick dismissal
### High Contrast Support
* Colors automatically adjust for high contrast themes
* Maintains WCAG AA compliance (4.5:1 contrast ratio)
## Best Practices
* Use **Info** for general information and updates
* Use **Success** for positive confirmations and achievements
* Use **Error** for actual errors that need user attention
* Use **Warning** for potential issues or important notices
* Keep messages concise (under 2 lines when possible)
* Use clear, action-oriented language
* Avoid technical jargon unless necessary
* Use auto-dismiss for informational messages (3-5 seconds)
* Keep error messages visible until user dismisses
* Consider user reading time for longer messages
* Position at the top or bottom of the screen
* Avoid covering important content
* Consider mobile keyboard visibility
## Examples
Show success/error messages after form submission
Display system updates and user alerts
Confirm successful operations and actions
Gracefully handle and display errors
## Related Components
* [HuxInput](/components/input) - Form input components
* [HuxButton](/components/buttons) - Action buttons for forms
* [HuxBadge](/components/badge) - Status indicators
* [HuxCard](/components/cards) - Content containers
# Switch
Source: https://docs.thehuxdesign.com/components/switch
Toggle switch component with smooth animations and theme-aware styling
## Overview
HuxSwitch is a toggle switch component with smooth animations, consistent styling, and automatic theme adaptation. It provides a clean, modern interface for binary choices while maintaining accessibility standards.
## Basic Usage
### Switch States
```dart theme={null}
HuxSwitch(
value: isEnabled,
onChanged: (value) {
setState(() {
isEnabled = value;
});
},
)
```
### Switch with Label
```dart theme={null}
Row(
children: [
Text('Enable notifications'),
const SizedBox(width: 12),
HuxSwitch(
value: notificationsEnabled,
onChanged: (value) {
setState(() {
notificationsEnabled = value;
});
},
),
],
)
```
### Disabled Switch
```dart theme={null}
HuxSwitch(
value: isEnabled,
onChanged: null, // Disables the switch
)
```
## Properties
### Core Properties
* `value` - Current switch state (true/false)
* `onChanged` - Callback triggered when state changes (null for disabled)
### Styling Properties
* `size` - Switch size variant (small, medium, large)
## Size Variants
### Small Switch
* **Switch Size**: 32px × 20px
* **Thumb Size**: 16px × 16px
* **Track Width**: 32px
* **Track Height**: 20px
### Medium Switch ⭐ **Default**
* **Switch Size**: 40px × 24px
* **Thumb Size**: 20px × 20px
* **Track Width**: 40px
* **Track Height**: 24px
### Large Switch
* **Switch Size**: 48px × 28px
* **Thumb Size**: 24px × 24px
* **Track Width**: 48px
* **Track Height**: 28px
## Styling & Colors
### Switch Colors
* **Track (Off)**: `HuxTokens.surfaceSecondary(context)`
* **Track (On)**: `HuxTokens.primary(context)`
* **Thumb (Off)**: `HuxTokens.surfacePrimary(context)`
* **Thumb (On)**: `HuxTokens.surfacePrimary(context)`
* **Border**: `HuxTokens.borderPrimary(context)`
### Disabled State Colors
* **Track (Disabled)**: `HuxTokens.surfaceSecondary(context)` with 50% opacity
* **Thumb (Disabled)**: `HuxTokens.surfacePrimary(context)` with 50% opacity
## Animation
### Transition Timing
* **Duration**: 200ms smooth animation
* **Curve**: Natural easing for professional feel
* **Properties**: Position, color, and opacity transitions
### Interactive Feedback
* Smooth thumb movement
* Color transitions
* Hover state effects
## Accessibility
### Screen Reader Support
* Proper semantic labeling
* State announcements
* Focus management
### Keyboard Navigation
* Tab key support
* Space/Enter key activation
* Focus indicators
### Touch Targets
* Minimum 44px touch area
* Proper spacing for mobile use
* Clear visual feedback
## Examples
See HuxSwitch in action within forms
Try different switch configurations
## Related Components
* [HuxInput](/components/input) - Text input component
* [HuxCheckbox](/components/checkbox) - Checkbox component
* [HuxDateInput](/components/date-input) - Date input component
# Tabs
Source: https://docs.thehuxdesign.com/components/tabs
Organize content into multiple panels with tab navigation
# HuxTabs
The HuxTabs component provides a clean and modern way to organize content into multiple panels with tab navigation. It supports multiple variants, sizes, and includes built-in theme awareness.
## Basic Usage
```dart theme={null}
import 'package:hux/hux.dart';
HuxTabs(
tabs: [
HuxTabItem(
label: 'Overview',
content: Text('Overview content goes here'),
),
HuxTabItem(
label: 'Settings',
content: Text('Settings content goes here'),
),
HuxTabItem(
label: 'Profile',
content: Text('Profile content goes here'),
),
],
onTabChanged: (index) => print('Tab changed to $index'),
)
```
## Variants
### Default
The default variant displays tabs with an underline indicator.
```dart theme={null}
HuxTabs(
variant: HuxTabVariant.default_,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
### Pill
The pill variant displays tabs with a background indicator that highlights the active tab.
```dart theme={null}
HuxTabs(
variant: HuxTabVariant.pill,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
### Minimal
The minimal variant displays tabs without any indicator, relying on text color changes.
```dart theme={null}
HuxTabs(
variant: HuxTabVariant.minimal,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
## Sizes
### Small
```dart theme={null}
HuxTabs(
size: HuxTabSize.small,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
### Medium (Default)
```dart theme={null}
HuxTabs(
size: HuxTabSize.medium,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
### Large
```dart theme={null}
HuxTabs(
size: HuxTabSize.large,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
## With Icons
Add icons to your tabs for better visual hierarchy.
```dart theme={null}
HuxTabs(
tabs: [
HuxTabItem(
label: 'Dashboard',
icon: Icons.dashboard,
content: Text('Dashboard content'),
),
HuxTabItem(
label: 'Settings',
icon: Icons.settings,
content: Text('Settings content'),
),
HuxTabItem(
label: 'Profile',
icon: Icons.person,
content: Text('Profile content'),
),
],
)
```
## With Badges
Add badges to indicate notifications or counts.
```dart theme={null}
HuxTabs(
tabs: [
HuxTabItem(
label: 'Messages',
icon: Icons.message,
badge: HuxBadge(
text: '3',
variant: HuxBadgeVariant.destructive,
),
content: Text('Messages content'),
),
HuxTabItem(
label: 'Notifications',
icon: Icons.notifications,
badge: HuxBadge(
text: '12',
variant: HuxBadgeVariant.primary,
),
content: Text('Notifications content'),
),
],
)
```
## Scrollable Tabs
Enable horizontal scrolling for tabs that don't fit in the available space.
```dart theme={null}
HuxTabs(
isScrollable: true,
tabs: List.generate(10, (index) => HuxTabItem(
label: 'Tab ${index + 1}',
content: Text('Content ${index + 1}'),
)),
)
```
## Tab Alignment
Control how tabs are aligned within the available space.
```dart theme={null}
HuxTabs(
alignment: TabAlignment.center,
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
)
```
## Disabled Tabs
Mark individual tabs as disabled to prevent interaction.
```dart theme={null}
HuxTabs(
tabs: [
HuxTabItem(
label: 'Available Tab',
content: Text('This tab is available'),
),
HuxTabItem(
label: 'Disabled Tab',
content: Text('This tab is disabled'),
isDisabled: true,
),
],
)
```
## Expanding Content
By default, tab content takes only the space it needs. Use `expandContent` to fill available vertical space.
```dart theme={null}
// Content fills available height
HuxTabs(
expandContent: true,
tabs: [
HuxTabItem(
label: 'Overview',
content: Container(
color: Colors.blue.shade100,
child: Center(child: Text('Fills available space')),
),
),
HuxTabItem(
label: 'Settings',
content: Container(
color: Colors.green.shade100,
child: Center(child: Text('Also fills available space')),
),
),
],
)
```
Set `expandContent: true` when tabs are in a bounded container (like an Expanded widget) and you want the content to fill available space. Leave it `false` (default) for better compatibility with unbounded layouts.
## Controlled Tabs
Control the active tab programmatically.
```dart theme={null}
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
int _activeTab = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
HuxButton(
onPressed: () => setState(() => _activeTab = 0),
child: Text('Go to Tab 1'),
),
SizedBox(width: 8),
HuxButton(
onPressed: () => setState(() => _activeTab = 1),
child: Text('Go to Tab 2'),
),
],
),
SizedBox(height: 16),
HuxTabs(
initialIndex: _activeTab,
onTabChanged: (index) => setState(() => _activeTab = index),
tabs: [
HuxTabItem(label: 'Tab 1', content: Text('Content 1')),
HuxTabItem(label: 'Tab 2', content: Text('Content 2')),
],
),
],
);
}
}
```
## API Reference
### HuxTabs
| Property | Type | Default | Description |
| --------------- | -------------------- | ------------------------ | -------------------------------------------------------------- |
| `tabs` | `List` | **required** | List of tab items to display |
| `initialIndex` | `int` | `0` | Initial active tab index |
| `variant` | `HuxTabVariant` | `HuxTabVariant.default_` | Visual variant of the tabs |
| `size` | `HuxTabSize` | `HuxTabSize.medium` | Size variant of the tabs |
| `onTabChanged` | `ValueChanged?` | `null` | Callback when the active tab changes |
| `isScrollable` | `bool` | `false` | Whether tabs should be scrollable horizontally |
| `alignment` | `TabAlignment` | `TabAlignment.start` | Alignment of tabs within the available space |
| `expandContent` | `bool` | `false` | Whether content should expand to fill available vertical space |
### HuxTabItem
| Property | Type | Default | Description |
| ------------ | ----------- | ------------ | ---------------------------------------------------- |
| `label` | `String` | **required** | The text label displayed on the tab |
| `content` | `Widget` | **required** | The content widget displayed when this tab is active |
| `icon` | `IconData?` | `null` | Optional icon displayed before the label |
| `badge` | `Widget?` | `null` | Optional badge widget displayed after the label |
| `isDisabled` | `bool` | `false` | Whether this tab is disabled |
### HuxTabVariant
* `HuxTabVariant.default_` - Default tabs with underline indicator
* `HuxTabVariant.pill` - Pill-style tabs with background indicator
* `HuxTabVariant.minimal` - Minimal tabs with no indicator
### HuxTabSize
* `HuxTabSize.small` - Small tabs for compact layouts
* `HuxTabSize.medium` - Medium tabs for standard layouts (default)
* `HuxTabSize.large` - Large tabs for prominent navigation
## Theming
HuxTabs automatically adapts to light and dark themes using HuxTokens. The component uses the following design tokens:
* `HuxTokens.tabActiveBackground` - Background color for active tab
* `HuxTokens.tabActiveText` - Text color for active tab
* `HuxTokens.tabInactiveBackground` - Background color for inactive tab
* `HuxTokens.tabInactiveText` - Text color for inactive tab
* `HuxTokens.tabHoverBackground` - Hover background color for tabs
* `HuxTokens.tabBorder` - Border color for tab container
* `HuxTokens.tabIndicator` - Indicator color for active tab
The tabs component follows Hux UI design principles with consistent spacing, typography, and color usage. All variants automatically adapt to your theme configuration.
# Textarea
Source: https://docs.thehuxdesign.com/components/textarea
Multi-line text input component optimized for longer content
## Overview
HuxTextarea is a customizable multi-line text input component with consistent styling and extensive customization options. It provides a clean, modern textarea with support for labels, hints, validation, and character counting while automatically adapting to light and dark themes. Optimized for longer text input with proper height handling.
## Basic Usage
### Simple Textarea
```dart theme={null}
HuxTextarea(
label: 'Description',
hint: 'Enter a description...',
minLines: 3,
maxLines: 6,
)
```
### Textarea with Character Count
```dart theme={null}
HuxTextarea(
label: 'Comments',
hint: 'Enter your comments...',
minLines: 4,
maxLines: 8,
maxLength: 500,
showCharacterCount: true,
)
```
### Textarea with Validation
```dart theme={null}
HuxTextarea(
label: 'Description',
hint: 'Enter a description...',
minLines: 3,
maxLines: 6,
helperText: 'Provide a detailed description',
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a description';
}
if (value.length < 10) {
return 'Description must be at least 10 characters';
}
return null;
},
)
```
### Textarea with Error State
```dart theme={null}
HuxTextarea(
label: 'Description',
hint: 'Enter a description...',
minLines: 3,
maxLines: 6,
errorText: 'Description is required',
)
```
## Properties
### Core Properties
* `label` - Optional field label text displayed above the textarea
* `hint` - Placeholder text displayed inside the textarea when empty
* `controller` - TextEditingController for managing input state
* `onChanged` - Callback triggered when the textarea value changes
* `onSubmitted` - Callback triggered when the user submits the textarea
### Validation Properties
* `validator` - Form validation function that returns error text or null
* `errorText` - Custom error message (overrides validator output)
* `helperText` - Helper text displayed below the textarea
### Behavior Properties
* `enabled` - Whether the textarea is interactive (default: true)
* `minLines` - Minimum number of text lines (default: 3)
* `maxLines` - Maximum number of text lines (default: 6)
* `maxLength` - Maximum character length
* `showCharacterCount` - Whether to show character count when maxLength is set (default: false)
* `keyboardType` - Type of keyboard to display
* `textInputAction` - Action button for the keyboard
### Layout Properties
* `width` - Custom width (default: full width)
## Styling & Dimensions
### Dimensions
* **Border Radius**: 8px (rounded corners)
* **Font Size**: 14px with 1.4 line height
* **Horizontal Padding**: 12px (compact padding for better text density)
* **Vertical Padding**: 12px
### Theme Support
* Automatically adapts to light and dark themes
* Uses HuxTokens for consistent theming
* Label uses FontWeight.w400 for lighter appearance
## Character Count
When `maxLength` is set and `showCharacterCount` is true, the textarea displays a character counter in the format "X / Y" at the bottom right. The counter updates dynamically as you type.
```dart theme={null}
HuxTextarea(
label: 'Message',
maxLength: 500,
showCharacterCount: true,
)
```
## Examples
### Basic Form with Textarea
```dart theme={null}
Form(
key: _formKey,
child: Column(
children: [
HuxInput(
label: 'Name',
hint: 'Enter your name',
),
const SizedBox(height: 16),
HuxTextarea(
label: 'Message',
hint: 'Enter your message...',
minLines: 4,
maxLines: 8,
maxLength: 1000,
showCharacterCount: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Message is required';
}
return null;
},
),
],
),
)
```
### Disabled Textarea
```dart theme={null}
HuxTextarea(
label: 'Notes',
hint: 'This field is disabled',
enabled: false,
minLines: 3,
maxLines: 6,
)
```
## Best Practices
* Use `minLines` to set the initial visible height
* Set `maxLines` to prevent the textarea from growing too large
* Use `showCharacterCount` when you have a `maxLength` to help users stay within limits
* Provide helpful `helperText` to guide users on what to enter
* Use validation to ensure data quality
# Toggle
Source: https://docs.thehuxdesign.com/components/toggle
Two-state toggle button for formatting controls and feature toggles
## Overview
`HuxToggle` is a two-state button component commonly used for formatting controls (like bold, italic) or feature toggles. It supports both icon-only and icon-with-text configurations, with multiple variants and sizes.
## Basic Usage
```dart theme={null}
HuxToggle(
value: isBold,
onChanged: (value) => setState(() => isBold = value),
icon: FeatherIcons.bold,
label: 'Bold', // Optional visual label
semanticLabel: 'Bold', // Optional when label is provided
)
```
## Icon-Only Toggle
```dart theme={null}
HuxToggle(
value: isEditing,
onChanged: (value) => setState(() => isEditing = value),
icon: FeatherIcons.edit2,
semanticLabel: 'Edit', // Required when label is null
)
```
## Variants
HuxToggle supports four visual variants through the `HuxButtonVariant` enum:
### Primary Toggle
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
variant: HuxButtonVariant.primary, // Default
)
```
### Secondary Toggle
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
variant: HuxButtonVariant.secondary,
)
```
### Outline Toggle
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
variant: HuxButtonVariant.outline,
)
```
### Ghost Toggle
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
variant: HuxButtonVariant.ghost,
)
```
## Sizes
Control toggle dimensions with three size options:
### Small Toggle
Compact size for tight spaces (32px height).
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
size: HuxToggleSize.small,
)
```
### Medium Toggle (Default)
Default size for most use cases (40px height).
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
size: HuxToggleSize.medium, // Default
)
```
### Large Toggle
Prominent size for important actions (48px height).
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
size: HuxToggleSize.large,
)
```
## States
### Disabled State
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: null, // Disable the toggle
icon: FeatherIcons.edit2,
isDisabled: true,
)
```
### Custom Primary Color
```dart theme={null}
HuxToggle(
value: isActive,
onChanged: (value) => setState(() => isActive = value),
icon: FeatherIcons.edit2,
primaryColor: Colors.deepPurple,
)
```
## API Reference
### HuxToggle Properties
| Property | Type | Default | Description |
| --------------- | --------------------- | ------------ | ----------------------------------------------------- |
| `value` | `bool` | **required** | The current toggle state (on/off) |
| `onChanged` | `ValueChanged?` | `null` | Callback triggered when toggle state changes |
| `icon` | `IconData` | **required** | The icon to display in the toggle |
| `label` | `String?` | `null` | Optional text label to display next to the icon |
| `semanticLabel` | `String?` | `null` | Accessibility label used when `label` is not provided |
| `size` | `HuxToggleSize` | `medium` | Size variant of the toggle |
| `variant` | `HuxButtonVariant` | `primary` | Visual variant of the toggle |
| `isDisabled` | `bool` | `false` | Whether the toggle is disabled |
| `primaryColor` | `Color?` | `null` | Optional custom primary color |
> If `label` is omitted (icon-only toggle), provide `semanticLabel` for accessibility.
### HuxToggleSize Enum
* `HuxToggleSize.small` - 32px height, compact padding
* `HuxToggleSize.medium` - 40px height, standard padding
* `HuxToggleSize.large` - 48px height, generous padding
## Accessibility
HuxToggle includes several accessibility features:
### Automatic Contrast
Text and icon colors are automatically calculated to ensure WCAG AA compliance (4.5:1 contrast ratio) against any background color.
### Semantic Roles
Toggles include proper semantic roles for screen readers and announce `label` or `semanticLabel`.
### Focus States
Keyboard navigation support with visible focus indicators.
### Disabled States
Proper disabled state handling for assistive technologies.
## Best Practices
* Use **Primary** for important toggles that need emphasis
* Use **Secondary** for standard toggles in content areas
* Use **Outline** for toggles that need visual separation
* Use **Ghost** for subtle toggles in toolbars
* Use **Large** for important feature toggles
* Use **Medium** for most standard interactions
* Use **Small** for compact toolbars or formatting controls
* Choose clear, meaningful icons that represent the action
* Use standard icons (bold, italic) for formatting controls
* Add labels for actions that aren't immediately clear
* For icon-only toggles, always provide `semanticLabel`
* Let toggles adapt to your app's theme
* Use `primaryColor` only for specific emphasis
* Maintain consistent styling within toggle groups
## Examples
See toggles in action within forms
Learn how to build a formatting toolbar
Apply custom colors and themes
Ensure your toggles are accessible
# Tooltip
Source: https://docs.thehuxdesign.com/components/tooltip
Display helpful information when hovering over or long-pressing on widgets
# Overview
`HuxTooltip` component provides additional context when hovering over or long-pressing on widgets. It automatically adapts to light and dark themes and provides various positioning and styling options.
## Basic Usage
The simplest way to use a tooltip is to wrap any widget with `HuxTooltip`:
```dart theme={null}
HuxTooltip(
message: 'This is a helpful tooltip',
child: Icon(Icons.info),
)
```
## Variants
### Standard Tooltip
The basic tooltip with customizable styling:
```dart theme={null}
HuxTooltip(
message: 'This is a tooltip message',
child: HuxButton(
onPressed: () {},
child: Text('Save'),
),
)
```
### Tooltip with Icon
For enhanced visual context, add an icon parameter to `HuxTooltip`.
```dart theme={null}
HuxTooltip(
message: 'New feature',
icon: Icons.info_outline, // Icon appears inside the tooltip
child: HuxButton(
onPressed: () {},
child: Text('Help'),
),
)
// Or with Lucide/Feather icons
HuxTooltip(
message: 'Help information',
icon: FeatherIcons.info, // Lucide/Feather icons
child: Icon(FeatherIcons.help),
)
```
## Customization
### Colors
Customize the tooltip appearance with your own colors:
```dart theme={null}
HuxTooltip(
message: 'Custom styled tooltip',
backgroundColor: Colors.deepPurple,
textColor: Colors.white,
child: Text('Hover me'),
)
```
### Positioning
Control where the tooltip appears relative to the child:
```dart theme={null}
HuxTooltip(
message: 'Tooltip above the element',
preferBelow: false, // Show above instead of below
verticalOffset: 20.0, // Increase distance from child
child: Icon(Icons.info),
)
```
### Timing
Adjust when and how long the tooltip appears:
```dart theme={null}
HuxTooltip(
message: 'Quick tooltip',
waitDuration: Duration(milliseconds: 200), // Show faster
showDuration: Duration(seconds: 5), // Show longer
child: Icon(Icons.info),
)
```
### Advanced Styling
For complete control over the tooltip appearance:
```dart theme={null}
HuxTooltip(
message: 'Custom styled tooltip',
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white, width: 2),
),
textStyle: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
padding: EdgeInsets.all(16),
child: Icon(Icons.info),
)
```
## Props
### HuxTooltip
| Prop | Type | Default | Description |
| ---------------------- | --------------------- | ------------- | ----------------------------------------- |
| `message` | `String` | **required** | The text to display in the tooltip |
| `child` | `Widget` | **required** | The widget below this tooltip |
| `backgroundColor` | `Color?` | Theme surface | Background color of the tooltip |
| `textColor` | `Color?` | Theme text | Text color of the tooltip |
| `preferBelow` | `bool` | `true` | Whether to prefer showing below the child |
| `excludeFromSemantics` | `bool` | `false` | Whether to exclude from semantics tree |
| `verticalOffset` | `double` | `10.0` | Vertical offset from the child |
| `waitDuration` | `Duration` | `500ms` | How long to wait before showing |
| `showDuration` | `Duration` | `3000ms` | How long to show the tooltip |
| `decoration` | `Decoration?` | Default theme | Custom decoration for the tooltip |
| `textStyle` | `TextStyle?` | Default theme | Custom text style |
| `height` | `double?` | Auto | Height of the tooltip |
| `padding` | `EdgeInsetsGeometry?` | `12x8` | Padding inside the tooltip |
| `margin` | `EdgeInsetsGeometry?` | `8` | Margin around the tooltip |
| `richMessage` | `InlineSpan?` | `null` | Rich text message (overrides message) |
### HuxTooltip Icon Parameters
| Prop | Type | Default | Description |
| ----------- | ----------- | ---------------- | ---------------------------------------------------------------------- |
| `icon` | `IconData?` | `null` | The icon to display alongside the message (rendered as an Icon widget) |
| `iconColor` | `Color?` | Theme text color | Color of the icon |
| `iconSize` | `double` | `16.0` | Size of the icon |
## Examples
Provide context for form inputs:
```dart theme={null}
Row(
children: [
Expanded(
child: HuxInput(
label: 'Email Address',
hintText: 'Enter your email',
),
),
HuxTooltip(
message: 'We\'ll use this to send you important updates',
child: Icon(Icons.help_outline, color: Colors.grey),
),
],
)
```
### Button Explanations
Explain button actions:
```dart theme={null}
HuxTooltip(
message: 'This will permanently delete your account',
icon: Icons.warning,
child: HuxButton(
onPressed: () {},
variant: HuxButtonVariant.destructive,
child: Text('Delete Account'),
),
)
```
### Navigation Hints
Guide users through complex interfaces:
```dart theme={null}
HuxTooltip(
message: 'Click to expand this section and see more options',
child: HuxButton(
onPressed: () {},
variant: HuxButtonVariant.ghost,
child: Icon(Icons.expand_more),
),
)
```
## Best Practices
### Content Guidelines
* **Keep messages concise**: Tooltips should be brief and to the point
* **Use clear language**: Avoid technical jargon unless necessary
* **Provide value**: Only show tooltips when they add meaningful context
### Accessibility
* **Semantic content**: Tooltips are automatically included in the accessibility tree
* **Keyboard navigation**: Tooltips work with keyboard navigation
* **Screen readers**: Content is properly announced to assistive technologies
### Performance
* **Lazy loading**: Tooltips only render when needed
* **Efficient positioning**: Smart positioning algorithms minimize layout calculations
* **Memory management**: Proper cleanup when tooltips are dismissed
### Theme Integration
* **Automatic adaptation**: Tooltips automatically adapt to light/dark themes
* **Consistent styling**: Uses Hux design tokens for consistent appearance
* **Customizable**: Override theme colors when needed for specific use cases
## Related Components
* **[Button](/components/buttons)** - Add tooltips to buttons for better UX
* **[Input](/components/inputs)** - Provide help text for form fields
* **[Card](/components/cards)** - Add context to card content
* **[Badge](/components/badge)** - Explain badge meanings with tooltips
# Basic Usage Examples
Source: https://docs.thehuxdesign.com/examples/basic-usage
Common patterns and implementations using Hux UI components
## Overview
This page showcases common usage patterns and implementations using Hux UI components. These examples are taken from real-world scenarios and demonstrate best practices.
## Complete App Example
Here's a minimal but complete Flutter app using Hux UI:
```dart theme={null}
import 'package:flutter/material.dart';
import 'package:hux/hux.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hux UI Example',
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hux UI Demo')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HuxCard(
title: 'Welcome',
subtitle: 'Getting started with Hux UI',
child: Text('This is a simple example app.'),
),
SizedBox(height: 20),
HuxButton(
onPressed: () => print('Primary action'),
child: Text('Primary Button'),
variant: HuxButtonVariant.primary,
),
SizedBox(height: 12),
HuxButton(
onPressed: () => print('Secondary action'),
child: Text('Secondary Button'),
variant: HuxButtonVariant.secondary,
),
],
),
),
);
}
}
```
## Form Example
```dart theme={null}
class LoginForm extends StatefulWidget {
@override
_LoginFormState createState() => _LoginFormState();
}
class _LoginFormState extends State {
final _formKey = GlobalKey();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _isLoading = false;
void _handleLogin() async {
if (_formKey.currentState!.validate()) {
setState(() {
_isLoading = true;
});
// Simulate login
await Future.delayed(Duration(seconds: 2));
setState(() {
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return HuxCard(
title: 'Login',
child: Form(
key: _formKey,
child: Column(
children: [
HuxInput(
label: 'Email',
hint: 'Enter your email',
controller: _emailController,
prefixIcon: Icon(FeatherIcons.mail),
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Email is required';
}
return null;
},
),
SizedBox(height: 16),
HuxInput(
label: 'Password',
hint: 'Enter your password',
controller: _passwordController,
prefixIcon: Icon(FeatherIcons.lock),
obscureText: true,
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Password is required';
}
return null;
},
),
SizedBox(height: 24),
HuxButton(
onPressed: _isLoading ? null : _handleLogin,
isLoading: _isLoading,
child: Text('Login'),
variant: HuxButtonVariant.primary,
),
],
),
),
);
}
}
```
## Settings Page Example
```dart theme={null}
class SettingsPage extends StatefulWidget {
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State {
bool _notifications = true;
bool _darkMode = false;
bool _analytics = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Settings')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HuxCard(
title: 'Preferences',
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Push Notifications'),
HuxSwitch(
value: _notifications,
onChanged: (value) {
setState(() {
_notifications = value;
});
},
),
],
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Dark Mode'),
HuxSwitch(
value: _darkMode,
onChanged: (value) {
setState(() {
_darkMode = value;
});
},
),
],
),
SizedBox(height: 16),
HuxCheckbox(
value: _analytics,
onChanged: (value) {
setState(() {
_analytics = value ?? false;
});
},
label: 'Share analytics data to help improve the app',
),
],
),
),
SizedBox(height: 20),
HuxCard(
title: 'Account',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HuxButton(
onPressed: () {},
child: Text('Change Password'),
variant: HuxButtonVariant.outline,
),
SizedBox(height: 12),
HuxButton(
onPressed: () {},
child: Text('Export Data'),
variant: HuxButtonVariant.outline,
),
SizedBox(height: 12),
HuxButton(
onPressed: () {},
child: Text('Delete Account'),
variant: HuxButtonVariant.outline,
primaryColor: HuxColors.red,
),
],
),
),
],
),
),
);
}
}
```
## Profile Page Example
```dart theme={null}
class ProfilePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Profile')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
HuxCard(
child: Row(
children: [
HuxAvatar(
name: 'John Doe',
size: HuxAvatarSize.large,
),
SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'John Doe',
style: Theme.of(context).textTheme.titleLarge,
),
Text(
'john.doe@example.com',
style: TextStyle(
color: HuxTokens.textSecondary(context),
),
),
SizedBox(height: 8),
Row(
children: [
HuxBadge(
label: 'Pro',
variant: HuxBadgeVariant.primary,
),
SizedBox(width: 8),
HuxBadge(
label: 'Verified',
variant: HuxBadgeVariant.success,
),
],
),
],
),
),
],
),
),
SizedBox(height: 20),
HuxCard(
title: 'Team Members',
child: HuxAvatarGroup(
avatars: [
HuxAvatar(name: 'Alice Smith'),
HuxAvatar(name: 'Bob Johnson'),
HuxAvatar(
useGradient: true,
gradientVariant: HuxAvatarGradient.bluePurple,
),
HuxAvatar(name: 'Carol Williams'),
HuxAvatar(name: 'David Brown'),
],
overlap: true,
maxVisible: 4,
),
),
],
),
),
);
}
}
```
These examples demonstrate common patterns you'll use when building apps with Hux UI. For more complex examples, check out the [full example app](https://github.com/lofidesigner/hux/tree/main/example).
## Date Input Example
```dart theme={null}
class DateSelectionForm extends StatefulWidget {
@override
_DateSelectionFormState createState() => _DateSelectionFormState();
}
class _DateSelectionFormState extends State {
DateTime? _selectedDate;
@override
Widget build(BuildContext context) {
return HuxCard(
title: 'Event Details',
child: Column(
children: [
HuxInput(
label: 'Event Name',
hint: 'Enter event name',
prefixIcon: Icon(FeatherIcons.calendar),
),
SizedBox(height: 16),
HuxDateInput(
label: 'Event Date',
hint: 'MM/DD/YYYY',
onDateChanged: (date) {
setState(() {
_selectedDate = date;
});
},
validator: (date) {
if (date == null) return 'Please select a date';
if (date.isBefore(DateTime.now())) {
return 'Date cannot be in the past';
}
return null;
},
),
SizedBox(height: 16),
HuxButton(
onPressed: _selectedDate != null ? () {
print('Event scheduled for: $_selectedDate');
} : null,
child: Text('Schedule Event'),
variant: HuxButtonVariant.primary,
),
],
),
);
}
}
```
## Next Steps
Learn advanced form patterns and validation
Implement dynamic theme switching
# Data Visualization
Source: https://docs.thehuxdesign.com/examples/data-visualization
Creating beautiful charts and data displays with HuxChart
## Overview
Learn how to create stunning data visualizations using HuxChart components with real-world data examples.
Data visualization examples are coming soon. For basic chart usage, see the [Charts component documentation](/components/charts).
# Form Building
Source: https://docs.thehuxdesign.com/examples/form-building
Advanced form patterns and validation with Hux UI components
## Overview
Learn how to build robust forms using Hux UI components with proper validation, error handling, and user experience patterns.
## Form Components
Hux UI provides several components for building forms:
* **HuxInput** - Text input with validation and consistent styling
* **HuxDateInput** - Date input with automatic formatting and calendar picker
* **HuxCheckbox** - Interactive checkbox for boolean inputs
* **HuxSwitch** - Toggle switch for binary choices
* **HuxButton** - Form submission and action buttons
## Basic Form Example
```dart theme={null}
Form(
key: _formKey,
child: Column(
children: [
HuxInput(
label: 'Full Name',
hint: 'Enter your full name',
validator: (value) {
if (value?.isEmpty ?? true) return 'Name is required';
return null;
},
),
SizedBox(height: 16),
HuxDateInput(
label: 'Birth Date',
onDateChanged: (date) => _birthDate = date,
validator: (date) {
if (date == null) return 'Birth date is required';
return null;
},
),
SizedBox(height: 16),
HuxButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Form is valid, proceed
}
},
child: Text('Submit'),
variant: HuxButtonVariant.primary,
),
],
),
)
```
For more detailed examples, see the [Basic Usage](/examples/basic-usage) page and the [full example app](https://github.com/lofidesigner/hux/tree/main/example).
# Theme Switching
Source: https://docs.thehuxdesign.com/examples/theme-switching
Implementing dynamic theme switching and custom brand colors
## Overview
Learn how to implement dynamic theme switching, save user preferences, and apply custom brand colors in your Hux UI applications.
Theme switching examples are coming soon. For basic theming concepts, see the [Theming guide](/theming).
# Hux UI
Source: https://docs.thehuxdesign.com/index
An open-source state of the art UI library for Flutter 💙
## What is Hux UI?
Hux UI is an open-source state-of-the-art UI library for Flutter, created by [Zoe Gilbert](https://github.com/lofidesigner). It provides a comprehensive set of beautiful, customizable components designed for clean and consistent user interfaces.
**Try it live!** Explore all Hux UI components interactively at [ui.thehuxdesign.com](https://ui.thehuxdesign.com) 🚀
**Designers**: Access the complete Hux UI design system in [Figma](https://www.figma.com/community/file/1541197128732135637/the-hux-ui) with all components, colors, and design tokens ready for your design workflow.
Try all Hux UI components interactively in your browser
Install Hux UI and set up your first Flutter app in minutes
Explore our comprehensive collection of UI components
See Hux UI in action with practical examples
Learn how to customize themes and design tokens
Access the complete design system for your design workflow
## Key Features
Clean, minimal design language with beautiful animations and smooth interactions.
Built-in light and dark theme support with automatic adaptation and design tokens.
Beautiful animated charts for data presentation with line and bar chart support.
Components adapt to different screen sizes and provide excellent cross-platform support.
Extensive customization options with design tokens and theme system.
WCAG AA compliant with proper contrast ratios and accessibility features.
## Available Components
Hux UI includes 25+ carefully crafted components organized into logical categories:
### Input & Forms
* **HuxButton** - Multiple variants (primary, secondary, outline, ghost) with loading states and icon-only support
* **HuxInput** - Enhanced text input with validation and consistent styling
* **HuxTextarea** - Multi-line text input optimized for longer content with character count support
* **HuxDateInput** - Date input with automatic formatting and calendar picker
* **HuxCheckbox** - Interactive checkbox with custom styling and labels
* **HuxSwitch** - Toggle switch with smooth animations
### Date & Time Selection
* **HuxDatePicker** - Modern date picker with overlay calendar and icon-only mode
* **HuxDateInput** - Integrated date input with automatic formatting
### Layout & Display
* **HuxCard** - Flexible card component with headers, actions, and tap handling
* **HuxTabs** - Organize content into multiple panels with tab navigation
* **HuxAvatar** - Circular user images with initials fallback and gradient variants
* **HuxAvatarGroup** - Display multiple avatars with overlapping layouts
### Feedback & Status
* **HuxBadge** - Status indicators with semantic variants
* **HuxAlert** - Message boxes with dismissible functionality
* **HuxLoading** - Customizable loading indicators and overlays
### Advanced Components
* **HuxChart** - Beautiful data visualization with cristalyse integration
* **HuxContextMenu** - Right-click context menus with smart positioning
### Theme System
* **HuxTheme** - Pre-configured light and dark themes
* **HuxColors** - Comprehensive color palette
* **HuxTokens** - Design token system for consistent theming
## Quick Example
```dart theme={null}
import 'package:flutter/material.dart';
import 'package:hux/hux.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hux UI Demo',
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
home: Scaffold(
body: Column(
children: [
HuxButton(
onPressed: () => print('Hello Hux!'),
child: Text('Get Started'),
variant: HuxButtonVariant.primary,
),
HuxInput(
label: 'Your Name',
hint: 'Enter your name',
),
HuxDateInput(
label: 'Birth Date',
onDateChanged: (date) => print('Selected: $date'),
),
HuxCard(
title: 'Welcome to Hux UI',
subtitle: 'Build beautiful Flutter apps',
child: Text('Start creating amazing user interfaces'),
),
],
),
),
);
}
}
```
## Support Hux UI
If you find Hux UI helpful and would like to support its continued development, consider becoming a GitHub Sponsor! 🌟
Your support helps us:
* 🚀 Maintain and improve Hux UI components
* 📚 Create better documentation and examples
* 🐛 Fix bugs and add new features faster
* 💡 Invest in new component development
[**Become a GitHub Sponsor**](https://github.com/sponsors/lofidesigner) - Every contribution makes a difference!
***
## Links
* **Live Demo**: [ui.thehuxdesign.com](https://ui.thehuxdesign.com) - Interactive component playground
* **Package**: [pub.dev/packages/hux](https://pub.dev/packages/hux)
* **Source Code**: [github.com/lofidesigner/hux](https://github.com/lofidesigner/hux)
* **Issues**: [GitHub Issues](https://github.com/lofidesigner/hux/issues)
* **Documentation**: [docs.thehuxdesign.com](https://docs.thehuxdesign.com)
* **Figma Library**: [Figma Community](https://www.figma.com/community/file/1541197128732135637/the-hux-ui)
* **Changelog**: [GitHub Releases](https://github.com/lofidesigner/hux/releases)
# Installation
Source: https://docs.thehuxdesign.com/installation
Get started with Hux UI in your Flutter project
## Requirements
Before installing Hux UI, ensure your development environment meets these requirements:
Flutter **3.22.0** or higher
Dart **3.4.0** or higher (included with Flutter)
* **Android** (API level 21+)
* **iOS** (iOS 12.0+)
* **Web** (JS and WASM)
* **Windows** (Windows 10+)
* **macOS** (macOS 10.15+)
* **Linux** (Ubuntu 18.04+)
## Installation
### Method 1: Using Flutter Command Line
Add Hux UI to your Flutter project using the command line:
```bash theme={null}
flutter pub add hux
```
This will automatically add the latest version of Hux UI to your `pubspec.yaml` file and run `flutter pub get`.
### Method 2: Manual Installation
Alternatively, you can manually add Hux UI to your `pubspec.yaml` file:
```yaml pubspec.yaml theme={null}
dependencies:
flutter:
sdk: flutter
hux: ^1.2.1 # Use the latest version
```
Then run:
```bash theme={null}
flutter pub get
```
## Import and Setup
### 1. Import Hux UI
Import Hux UI in your Dart files where you want to use the components:
```dart theme={null}
import 'package:hux/hux.dart';
```
This single import gives you access to all Hux UI components and utilities.
### 2. Configure Themes
Wrap your `MaterialApp` with Hux UI themes for the best experience:
```dart main.dart theme={null}
import 'package:flutter/material.dart';
import 'package:hux/hux.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Hux UI App',
// Configure light theme
theme: HuxTheme.lightTheme,
// Configure dark theme
darkTheme: HuxTheme.darkTheme,
// Optional: Set theme mode
themeMode: ThemeMode.system, // Follows system theme
home: MyHomePage(),
);
}
}
```
### 3. Start Using Components
You're now ready to use Hux UI components in your app:
```dart theme={null}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hux UI Demo')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
HuxButton(
onPressed: () => print('Button pressed!'),
child: Text('Primary Button'),
variant: HuxButtonVariant.primary,
),
SizedBox(height: 16),
HuxCard(
title: 'Welcome to Hux UI',
child: Text('This is a Hux UI card component.'),
),
],
),
),
);
}
}
```
## Verification
To verify that Hux UI is properly installed and working:
### 1. Check Dependencies
Ensure these dependencies are listed in your `pubspec.yaml`:
```yaml theme={null}
dependencies:
hux: ^1.2.1
flutter:
sdk: flutter
```
### 2. Test Import
Create a simple test to verify the import:
```dart test.dart theme={null}
import 'package:hux/hux.dart';
void main() {
// If this compiles without errors, Hux UI is properly installed
final button = HuxButton(
onPressed: () {},
child: Text('Test'),
);
print('Hux UI installed successfully!');
}
```
### 3. Run Your App
Start your Flutter app:
```bash theme={null}
flutter run
```
If you see Hux UI components rendering correctly, the installation is complete!
## Troubleshooting
If you encounter dependency conflicts, try:
```bash theme={null}
flutter pub deps
flutter clean
flutter pub get
```
Check for version conflicts with other packages in your `pubspec.yaml`.
If you get import errors:
1. Ensure you're using the correct import: `import 'package:hux/hux.dart';`
2. Check that the package is listed in your `pubspec.yaml`
3. Run `flutter pub get` to fetch dependencies
4. Restart your IDE/editor
If themes aren't working correctly:
1. Ensure you're using `HuxTheme.lightTheme` and `HuxTheme.darkTheme`
2. Check that `MaterialApp` is properly configured
3. Verify theme mode settings
4. Make sure components are wrapped in a `MaterialApp` context
For web applications, ensure you have the latest Flutter web support:
```bash theme={null}
flutter config --enable-web
flutter create . --platforms web
```
For desktop platforms:
```bash theme={null}
flutter config --enable-windows-desktop --enable-macos-desktop --enable-linux-desktop
```
## Next Steps
Now that Hux UI is installed, you can:
Learn the basics with our quickstart guide
Discover all available UI components
Customize themes and design tokens
See practical implementation examples
## Package Information
* **Latest Version**: 0.2.1
* **Package URL**: [pub.dev/packages/hux](https://pub.dev/packages/hux)
* **Repository**: [github.com/lofidesigner/hux](https://github.com/lofidesigner/hux)
* **License**: MIT
* **Author**: [Zoe Gilbert](https://github.com/lofidesigner)
# Quickstart
Source: https://docs.thehuxdesign.com/quickstart
Build your first Hux UI app in 5 minutes
## Quick Setup
Get up and running with Hux UI in just a few minutes. This guide will help you create a simple Flutter app using Hux UI components.
**For Designers**: Check out the [Figma library](https://www.figma.com/community/file/1541197128732135637/the-hux-ui) to explore all Hux UI components visually and use them in your design workflow.
Add Hux UI to your Flutter project:
```bash theme={null}
flutter pub add hux
```
Set up Hux UI themes in your `main.dart`:
```dart main.dart theme={null}
import 'package:flutter/material.dart';
import 'package:hux/hux.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hux UI Quickstart',
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
home: QuickstartPage(),
);
}
}
```
Create a simple page with Hux UI components:
```dart theme={null}
class QuickstartPage extends StatefulWidget {
@override
_QuickstartPageState createState() => _QuickstartPageState();
}
class _QuickstartPageState extends State {
bool _isLoading = false;
final _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hux UI Quickstart')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HuxCard(
title: 'Welcome to Hux UI',
subtitle: 'Modern Flutter components',
child: Text('This is your first Hux UI app!'),
),
SizedBox(height: 20),
HuxInput(
label: 'Enter your name',
hint: 'Type here...',
controller: _textController,
prefixIcon: Icon(FeatherIcons.user),
),
SizedBox(height: 20),
HuxButton(
onPressed: _isLoading ? null : () {
setState(() { _isLoading = true; });
Future.delayed(Duration(seconds: 2), () {
setState(() { _isLoading = false; });
});
},
isLoading: _isLoading,
child: Text('Get Started'),
variant: HuxButtonVariant.primary,
),
SizedBox(height: 20),
Row(
children: [
Expanded(
child: HuxButton(
onPressed: () {},
child: Text('Secondary'),
variant: HuxButtonVariant.secondary,
),
),
SizedBox(width: 12),
Expanded(
child: HuxButton(
onPressed: () {},
child: Text('Outline'),
variant: HuxButtonVariant.outline,
),
),
],
),
],
),
),
);
}
}
```
Start your Flutter app to see Hux UI in action:
```bash theme={null}
flutter run
```
## What You Built
Congratulations! You just created a Flutter app with:
* **HuxCard** - A beautiful card container with title and subtitle
* **HuxInput** - An enhanced text input with icon and validation support
* **HuxDateInput** - Date input with automatic formatting and calendar picker
* **HuxButton** - Multiple button variants with loading states
* **Automatic theming** - Light and dark mode support
## Common Patterns
Here are some common patterns you'll use with Hux UI:
Combine text fields, buttons, and validation:
```dart theme={null}
Form(
key: _formKey,
child: Column(
children: [
HuxInput(
label: 'Email',
hint: 'Enter your email',
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Email is required';
}
return null;
},
),
SizedBox(height: 16),
HuxButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Form is valid
}
},
child: Text('Submit'),
),
],
),
)
```
Show loading indicators and overlays:
```dart theme={null}
HuxLoadingOverlay(
isLoading: _isLoading,
message: 'Processing...',
child: Column(
children: [
HuxButton(
onPressed: _isLoading ? null : _handleSubmit,
isLoading: _isLoading,
child: Text('Submit'),
),
// Or standalone loading
if (_isLoading) HuxLoading(size: HuxLoadingSize.medium),
],
),
)
```
Customize colors and apply themes:
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Custom Color'),
variant: HuxButtonVariant.primary,
primaryColor: Colors.purple, // Custom primary color
)
// Or use design tokens
Container(
color: HuxTokens.surfaceElevated(context),
child: Text(
'Themed content',
style: TextStyle(color: HuxTokens.textPrimary(context)),
),
)
```
Show data with charts and badges:
```dart theme={null}
Column(
children: [
HuxChart.line(
data: [
{'x': 1, 'y': 10},
{'x': 2, 'y': 20},
{'x': 3, 'y': 15},
],
xField: 'x',
yField: 'y',
title: 'Sales Data',
),
SizedBox(height: 20),
Row(
children: [
HuxBadge(
label: 'New',
variant: HuxBadgeVariant.primary,
),
SizedBox(width: 8),
HuxBadge(
label: 'Success',
variant: HuxBadgeVariant.success,
),
],
),
],
)
```
## Next Steps
Now that you've built your first Hux UI app, explore more features:
Explore all available components and their APIs
Learn how to customize themes and design tokens
See complex implementations and best practices
Make your apps accessible with Hux UI
## Get Help
If you need assistance:
* **Issues**: [GitHub Issues](https://github.com/lofidesigner/hux/issues)
* **Source Code**: [github.com/lofidesigner/hux](https://github.com/lofidesigner/hux)
* **Package**: [pub.dev/packages/hux](https://pub.dev/packages/hux)
* **Figma Library**: [Figma Community](https://www.figma.com/community/file/1541197128732135637/the-hux-ui)
The complete source code for this quickstart example is available in the [Hux UI repository examples](https://github.com/lofidesigner/hux/tree/main/example).
# Theming
Source: https://docs.thehuxdesign.com/theming
Customize Hux UI themes and design tokens to match your brand
## Overview
Hux UI provides a comprehensive theming system based on design tokens that automatically adapt to light and dark modes. The theming system separates primitive colors from semantic tokens, following modern design system best practices.
**Design System Reference**: Explore the complete design system, including all colors, tokens, and component specifications in our [Figma library](https://www.figma.com/community/file/1541197128732135637/the-hux-ui).
## Theme Configuration
### Basic Setup
Configure light and dark themes in your app:
```dart main.dart theme={null}
import 'package:flutter/material.dart';
import 'package:hux/hux.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
// Use Hux UI themes
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
// Control theme mode
themeMode: ThemeMode.system, // Follow system setting
// themeMode: ThemeMode.light, // Force light mode
// themeMode: ThemeMode.dark, // Force dark mode
home: MyHomePage(),
);
}
}
```
### Dynamic Theme Switching
Implement theme switching in your app:
```dart theme={null}
class ThemeProvider extends StatefulWidget {
@override
_ThemeProviderState createState() => _ThemeProviderState();
}
class _ThemeProviderState extends State {
ThemeMode _themeMode = ThemeMode.system;
void toggleTheme() {
setState(() {
_themeMode = _themeMode == ThemeMode.light
? ThemeMode.dark
: ThemeMode.light;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
themeMode: _themeMode,
home: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(_themeMode == ThemeMode.light
? FeatherIcons.moon
: FeatherIcons.sun),
onPressed: toggleTheme,
),
],
),
body: YourContent(),
),
);
}
}
```
## Design Tokens
Hux UI uses semantic design tokens through the `HuxTokens` class. These tokens automatically adapt to the current theme.
### Text Tokens
```dart theme={null}
// Primary text (black in light, white in dark)
Text(
'Primary Text',
style: TextStyle(color: HuxTokens.textPrimary(context)),
)
// Secondary text (70% opacity)
Text(
'Secondary Text',
style: TextStyle(color: HuxTokens.textSecondary(context)),
)
// Tertiary text (50% opacity)
Text(
'Tertiary Text',
style: TextStyle(color: HuxTokens.textTertiary(context)),
)
// Disabled text (30% opacity)
Text(
'Disabled Text',
style: TextStyle(color: HuxTokens.textDisabled(context)),
)
```
### Surface Tokens
```dart theme={null}
// Primary surface (main background)
Container(
color: HuxTokens.surfacePrimary(context),
child: YourContent(),
)
// Secondary surface (subtle background)
Container(
color: HuxTokens.surfaceSecondary(context),
child: YourContent(),
)
// Elevated surface (cards, modals)
Container(
color: HuxTokens.surfaceElevated(context),
child: YourContent(),
)
// Hover surface
Container(
color: HuxTokens.surfaceHover(context),
child: YourContent(),
)
```
### Border Tokens
```dart theme={null}
// Primary borders
Container(
decoration: BoxDecoration(
border: Border.all(color: HuxTokens.borderPrimary(context)),
),
child: YourContent(),
)
// Secondary borders (more subtle)
Container(
decoration: BoxDecoration(
border: Border.all(color: HuxTokens.borderSecondary(context)),
),
child: YourContent(),
)
```
### Status Tokens
```dart theme={null}
// Success colors
HuxAlert(
variant: HuxAlertVariant.success,
title: 'Success!',
message: 'Operation completed successfully.',
)
// Destructive colors
HuxAlert(
variant: HuxAlertVariant.destructive,
title: 'Error',
message: 'Something went wrong.',
)
```
## Custom Colors
### Using Preset Colors
Hux UI provides several preset colors for customization:
```dart theme={null}
// Available preset colors
final presets = HuxColors.availablePresetColors;
// ['default', 'indigo', 'green', 'pink']
// Use preset colors in buttons
HuxButton(
onPressed: () {},
child: Text('Indigo Button'),
primaryColor: HuxColors.getPresetColor('indigo'), // #665CFF
)
HuxButton(
onPressed: () {},
child: Text('Green Button'),
primaryColor: HuxColors.getPresetColor('green'), // #2E7252
)
HuxButton(
onPressed: () {},
child: Text('Pink Button'),
primaryColor: HuxColors.getPresetColor('pink'), // #DF1D54
)
```
### Custom Colors
Use any custom color with Hux UI components:
```dart theme={null}
HuxButton(
onPressed: () {},
child: Text('Custom Purple'),
primaryColor: Color(0xFF6366F1),
)
HuxButton(
onPressed: () {},
child: Text('Custom Orange'),
primaryColor: Colors.deepOrange,
)
```
### Color Accessibility
Hux UI automatically ensures WCAG AA contrast compliance:
```dart theme={null}
// Button text color is automatically calculated for optimal contrast
HuxButton(
onPressed: () {},
child: Text('Auto Contrast'), // Text color adapts to background
primaryColor: Colors.purple, // Any background color
)
```
## Advanced Theming
### Custom Theme Extensions
Extend Hux themes with your own customizations:
```dart theme={null}
final customLightTheme = HuxTheme.lightTheme.copyWith(
// Override specific properties
appBarTheme: HuxTheme.lightTheme.appBarTheme.copyWith(
backgroundColor: Colors.blue.shade50,
),
// Add custom color scheme
colorScheme: HuxTheme.lightTheme.colorScheme.copyWith(
secondary: Colors.blue,
),
);
final customDarkTheme = HuxTheme.darkTheme.copyWith(
appBarTheme: HuxTheme.darkTheme.appBarTheme.copyWith(
backgroundColor: Colors.blue.shade900,
),
colorScheme: HuxTheme.darkTheme.colorScheme.copyWith(
secondary: Colors.blue.shade300,
),
);
```
### Theme-Aware Widgets
Create widgets that respond to theme changes:
```dart theme={null}
class ThemeAwareWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: HuxTokens.surfaceElevated(context),
border: Border.all(color: HuxTokens.borderPrimary(context)),
borderRadius: BorderRadius.circular(12),
),
child: Column(
children: [
Icon(
FeatherIcons.star,
color: HuxTokens.iconPrimary(context),
),
Text(
'Theme Aware Content',
style: TextStyle(color: HuxTokens.textPrimary(context)),
),
Text(
'Adapts to ${isDark ? 'dark' : 'light'} mode',
style: TextStyle(color: HuxTokens.textSecondary(context)),
),
],
),
);
}
}
```
## Best Practices
Always use `HuxTokens` instead of hardcoded colors:
```dart theme={null}
// ✅ Good - semantic tokens
Text(
'Hello',
style: TextStyle(color: HuxTokens.textPrimary(context)),
)
// ❌ Bad - hardcoded colors
Text(
'Hello',
style: TextStyle(color: Colors.black),
)
```
Always test your UI in both light and dark modes:
```dart theme={null}
// Force different themes for testing
MaterialApp(
theme: HuxTheme.lightTheme,
darkTheme: HuxTheme.darkTheme,
themeMode: ThemeMode.light, // Test light mode
// themeMode: ThemeMode.dark, // Test dark mode
)
```
Use consistent spacing that works with the theme:
```dart theme={null}
// Use multiples of 4 or 8 for consistent spacing
EdgeInsets.all(16), // ✅ Good
EdgeInsets.symmetric(horizontal: 20, vertical: 12), // ✅ Good
EdgeInsets.all(13), // ❌ Inconsistent
```
Leverage automatic contrast calculation:
```dart theme={null}
// Hux UI automatically ensures proper contrast
HuxButton(
primaryColor: Colors.purple, // Any color
child: Text('Button'), // Text color automatically calculated
)
```
## Color Reference
### Preset Colors
| Name | Light Mode | Dark Mode | Hex Code |
| ------- | ---------- | --------- | --------- |
| Default | Black | White | Dynamic |
| Indigo | Indigo | Indigo | `#665CFF` |
| Green | Green | Green | `#2E7252` |
| Pink | Pink | Pink | `#DF1D54` |
### Status Colors
| Status | Purpose | Light Mode | Dark Mode |
| ----------- | ---------------- | ---------- | ----------- |
| Success | Positive actions | Dark Green | Light Green |
| Destructive | Errors, warnings | Dark Red | Light Red |
### Token Categories
* **Text**: Primary, Secondary, Tertiary, Disabled, Inverted
* **Surface**: Primary, Secondary, Elevated, Hover
* **Border**: Primary, Secondary, Destructive, Success
* **Button**: Secondary Background, Secondary Text, Secondary Border
* **Icon**: Primary, Secondary
* **Chart**: Grid, Axis, Axis Text
## Examples
See how to implement dynamic theme switching
Learn how to apply custom brand colors
Explore the complete design system in Figma
Ensure your themes meet accessibility standards
Deep dive into advanced theming techniques