ColorScheme.fromSwatch constructor

ColorScheme.fromSwatch(
  1. {MaterialColor primarySwatch = Colors.blue,
  2. Color? accentColor,
  3. Color? cardColor,
  4. Color? backgroundColor,
  5. Color? errorColor,
  6. Brightness brightness = Brightness.light}
)

Creates a color scheme from a MaterialColor swatch.

In Material 3, this constructor is ignored by ThemeData when creating its default color scheme. Instead, ThemeData uses ColorScheme.fromSeed to create its default color scheme. This constructor shouldn't be used to update the Material 3 color scheme. It will be phased out gradually; see https://github.com/flutter/flutter/issues/120064 for more details.

If ThemeData.useMaterial3 is false, then this constructor is used by ThemeData to create its default color scheme.

Implementation

factory ColorScheme.fromSwatch({
  MaterialColor primarySwatch = Colors.blue,
  Color? accentColor,
  Color? cardColor,
  Color? backgroundColor,
  Color? errorColor,
  Brightness brightness = Brightness.light,
}) {
  final bool isDark = brightness == Brightness.dark;
  final bool primaryIsDark = _brightnessFor(primarySwatch) == Brightness.dark;
  final Color secondary = accentColor ?? (isDark ? Colors.tealAccent[200]! : primarySwatch);
  final bool secondaryIsDark = _brightnessFor(secondary) == Brightness.dark;

  return ColorScheme(
    primary: primarySwatch,
    secondary: secondary,
    surface: cardColor ?? (isDark ? Colors.grey[800]! : Colors.white),
    background: backgroundColor ?? (isDark ? Colors.grey[700]! : primarySwatch[200]!),
    error: errorColor ?? Colors.red[700]!,
    onPrimary: primaryIsDark ? Colors.white : Colors.black,
    onSecondary: secondaryIsDark ? Colors.white : Colors.black,
    onSurface: isDark ? Colors.white : Colors.black,
    onBackground: primaryIsDark ? Colors.white : Colors.black,
    onError: isDark ? Colors.black : Colors.white,
    brightness: brightness,
  );
}