Flutter 中ThemeData 介绍

ThemeData的定义

// GENERAL CONFIGURATION
    bool? applyElevationOverlayColor,
    NoDefaultCupertinoThemeData? cupertinoOverrideTheme,
    Iterable<ThemeExtension<dynamic>>? extensions,
    InputDecorationTheme? inputDecorationTheme,
    MaterialTapTargetSize? materialTapTargetSize,
    PageTransitionsTheme? pageTransitionsTheme,
    TargetPlatform? platform,
    ScrollbarThemeData? scrollbarTheme,
    InteractiveInkFeatureFactory? splashFactory,
    VisualDensity? visualDensity,
    bool? useMaterial3,
    ColorScheme? colorScheme,
    Color? colorSchemeSeed,
    Brightness? brightness,
    MaterialColor? primarySwatch,
    Color? primaryColor,
    Color? primaryColorLight,
    Color? primaryColorDark,
    Color? focusColor,
    Color? hoverColor,
    Color? shadowColor,
    Color? canvasColor,
    Color? scaffoldBackgroundColor,
    Color? bottomAppBarColor,
    Color? cardColor,
    Color? dividerColor,
    Color? highlightColor,
    Color? splashColor,
    Color? selectedRowColor,
    Color? unselectedWidgetColor,
    Color? disabledColor,
    Color? secondaryHeaderColor,
    Color? backgroundColor,
    Color? dialogBackgroundColor,
    Color? indicatorColor,
    Color? hintColor,
    Color? errorColor,
    Color? toggleableActiveColor,
    // TYPOGRAPHY & ICONOGRAPHY
    String? fontFamily,
    Typography? typography,
    TextTheme? textTheme,
    TextTheme? primaryTextTheme,
    IconThemeData? iconTheme,
    IconThemeData? primaryIconTheme,
    // COMPONENT THEMES
    AppBarTheme? appBarTheme,
    MaterialBannerThemeData? bannerTheme,
    BottomAppBarTheme? bottomAppBarTheme,
    BottomNavigationBarThemeData? bottomNavigationBarTheme,
    BottomSheetThemeData? bottomSheetTheme,
    ButtonBarThemeData? buttonBarTheme,
    ButtonThemeData? buttonTheme,
    CardTheme? cardTheme,
    CheckboxThemeData? checkboxTheme,
    ChipThemeData? chipTheme,
    DataTableThemeData? dataTableTheme,
    DialogTheme? dialogTheme,
    DividerThemeData? dividerTheme,
    DrawerThemeData? drawerTheme,
    ElevatedButtonThemeData? elevatedButtonTheme,
    FloatingActionButtonThemeData? floatingActionButtonTheme,
    ListTileThemeData? listTileTheme,
    NavigationBarThemeData? navigationBarTheme,
    NavigationRailThemeData? navigationRailTheme,
    OutlinedButtonThemeData? outlinedButtonTheme,
    PopupMenuThemeData? popupMenuTheme,
    ProgressIndicatorThemeData? progressIndicatorTheme,
    RadioThemeData? radioTheme,
    SliderThemeData? sliderTheme,
    SnackBarThemeData? snackBarTheme,
    SwitchThemeData? switchTheme,
    TabBarTheme? tabBarTheme,
    TextButtonThemeData? textButtonTheme,
    TextSelectionThemeData? textSelectionTheme,
    TimePickerThemeData? timePickerTheme,
    ToggleButtonsThemeData? toggleButtonsTheme,
    TooltipThemeData? tooltipTheme,
    ExpansionTileThemeData? expansionTileTheme,
    // ...弃用的属性这里就不介绍了
    AndroidOverscrollIndicator? androidOverscrollIndicator,
  }) 

属性介绍

  1. applyElevationOverlayColor默认值是false 在brightness 为Brightness.dark是为有elevation 属性的 Material surfaces,添加一个半透明的遮罩,
    用来凸显阴影效果, 效果如下,可以看出,当为true的时候,背景会白一些。这个属性只适用于Material 2的dark theme,在Material 3中是无效的。
    applyElevationOverlayColor_false.png
applyElevationOverlayColor_true.png

2.cupertinoOverrideTheme用来设置iOS组件的样式

//没有为属性设置默认值
class NoDefaultCupertinoThemeData {
  const NoDefaultCupertinoThemeData({
    this.brightness,
    //这个颜色一般用在按钮和可点击的文本和图标上,如果 [primaryColor] 未指定,将使用 [ThemeData] 的 colorScheme.primary。
    this.primaryColor, 
    //如果未指定将使用 [ThemeData] 的colorScheme.onPrimary
    this.primaryContrastingColor,
    //iOS组件默认的字体样式
    this.textTheme,
    //iOS NavigationBar的颜色
    this.barBackgroundColor,
    //Scaffold 背景色
    this.scaffoldBackgroundColor,
  });
  //...
}

//为属性设置了默认值
class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable {
  const CupertinoThemeData({
    Brightness? brightness,
    Color? primaryColor,
    Color? primaryContrastingColor,
    CupertinoTextThemeData? textTheme,
    Color? barBackgroundColor,
    Color? scaffoldBackgroundColor,
  }) : this.raw(
        brightness,
        primaryColor,
        primaryContrastingColor,
        textTheme,
        barBackgroundColor,
        scaffoldBackgroundColor,
      );
}

//默认值
const _CupertinoThemeDefaults _kDefaultTheme = _CupertinoThemeDefaults(
  null,
  CupertinoColors.systemBlue,
  CupertinoColors.systemBackground,
  CupertinoDynamicColor.withBrightness(
    color: Color(0xF0F9F9F9),
    darkColor: Color(0xF01D1D1D),
    // Values extracted from navigation bar. For toolbar or tabbar the dark color is 0xF0161616.
  ),
  CupertinoColors.systemBackground,
  _CupertinoTextThemeDefaults(CupertinoColors.label, CupertinoColors.inactiveGray),
);
  1. extensions 用来添加自定义的主题颜色
abstract class ThemeExtension<T extends ThemeExtension<T>> {
  /// Enable const constructor for subclasses.
  const ThemeExtension();

  /// The extension's type.
  Object get type => T;

  /// Creates a copy of this theme extension with the given fields
  /// replaced by the non-null parameter values.
  ThemeExtension<T> copyWith();

  /// Linearly interpolate with another [ThemeExtension] object.
  ///
  /// {@macro dart.ui.shadow.lerp}
  ThemeExtension<T> lerp(ThemeExtension<T>? other, double t);
}
  1. inputDecorationTheme 用于设置TextField的样式
class InputDecorationTheme with Diagnosticable {
  /// Creates a value for [ThemeData.inputDecorationTheme] that
  /// defines default values for [InputDecorator].
  ///
  /// The values of [isDense], [isCollapsed], [filled], [floatingLabelAlignment],
  /// and [border] must not be null.
  const InputDecorationTheme({
    this.labelStyle,
    this.floatingLabelStyle,
    this.helperStyle,
    this.helperMaxLines,
    this.hintStyle,
    this.errorStyle,
    this.errorMaxLines,
    this.floatingLabelBehavior = FloatingLabelBehavior.auto,
    this.floatingLabelAlignment = FloatingLabelAlignment.start,
    this.isDense = false,
    this.contentPadding,
    this.isCollapsed = false,
    this.iconColor,
    this.prefixStyle,
    this.prefixIconColor,
    this.suffixStyle,
    this.suffixIconColor,
    this.counterStyle,
    this.filled = false,
    this.fillColor,
    this.focusColor,
    this.hoverColor,
    this.errorBorder,
    this.focusedBorder,
    this.focusedErrorBorder,
    this.disabledBorder,
    this.enabledBorder,
    this.border,
    this.alignLabelWithHint = false,
    this.constraints,
  }) : assert(isDense != null),
       assert(isCollapsed != null),
       assert(floatingLabelAlignment != null),
       assert(filled != null),
       assert(alignLabelWithHint != null);
//....
}
  1. materialTapTargetSize 配置某些 Material 小部件的点击目标和布局大小。

/// 一些受影响的小部件包括:
///
///   * [FloatingActionButton], only the mini tap target size is increased.
///   * [MaterialButton]
///   * [OutlinedButton]
///   * [TextButton]
///   * [ElevatedButton]
///   * [FlatButton]
///   * [RaisedButton]
///   * The time picker widget ([showTimePicker])
///   * [SnackBar]
///   * [Chip]
///   * [RawChip]
///   * [InputChip]
///   * [ChoiceChip]
///   * [FilterChip]
///   * [ActionChip]
///   * [Radio]
///   * [Switch]
///   * [Checkbox]

enum MaterialTapTargetSize {
  /// 将最小点击目标大小扩展为 48px x 48px。
   ///
   /// 这是 [ThemeData.materialTapTargetSize] 的默认值和
   /// 推荐大小以符合 Android 可访问性扫描仪
   /// 建议。
  padded,

  /// 将点击目标尺寸缩小到Material 规范提供的最小值。
  shrinkWrap,
}
  1. pageTransitionsTheme 定义[MaterialPageRoute]使用的页面过渡动画
/// 定义[MaterialPageRoute]使用的页面过渡动画
/// 用于不同的 [TargetPlatform]。
///
/// [MaterialPageRoute.buildTransitions] 方法使用 `Theme.of(context).pageTransitionsTheme` 查找当前当前的 [PageTransitionsTheme] 并委托给 [buildTransitions]。如果未找到具有匹配平台的构建器,则使用 [FadeUpwardsPageTransitionsBuilder]。
///
/// 也可以看看:
///
/// * [ThemeData.pageTransitionsTheme],定义默认页面
/// 整体主题的过渡。
/// * [FadeUpwardsPageTransitionsBuilder],定义了一个页面过渡
/// 与Android O提供的类似。
/// * [OpenUpwardsPageTransitionsBuilder],定义了一个页面过渡
/// 这与Android P提供的类似。
/// * [ZoomPageTransitionsBuilder],定义了默认的页面过渡
/// 这和Android Q提供的类似。
/// * [CupertinoPageTransitionsBuilder],定义一个水平页面
/// 匹配原生 iOS 页面转换的转换。

class PageTransitionsTheme with Diagnosticable {
  /// 默认情况下,构建器列表是:[ZoomPageTransitionsBuilder]
用于 [TargetPlatform.android],[CupertinoPageTransitionsBuilder] 用于 [TargetPlatform.iOS] 和 [TargetPlatform.macOS]。
  const PageTransitionsTheme({ Map<TargetPlatform, PageTransitionsBuilder> builders = _defaultBuilders }) : _builders = builders;

  static const Map<TargetPlatform, PageTransitionsBuilder> _defaultBuilders = <TargetPlatform, PageTransitionsBuilder>{
    TargetPlatform.android: ZoomPageTransitionsBuilder(),
    TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
    TargetPlatform.macOS: CupertinoPageTransitionsBuilder(),
  };
//.....
}

7.platform material 小部件应适应目标的平台。可用于确定 [typography] 和 [materialTapTargetSize] 的默认值。

TargetPlatform get defaultTargetPlatform => platform.defaultTargetPlatform;

/// The platform that user interaction should adapt to target.
///
/// The [defaultTargetPlatform] getter returns the current platform.
enum TargetPlatform {
  /// Android: <https://www.android.com/>
  android,

  /// Fuchsia: <https://fuchsia.dev/fuchsia-src/concepts>
  fuchsia,

  /// iOS: <https://www.apple.com/ios/>
  iOS,

  /// Linux: <https://www.linux.org>
  linux,

  /// macOS: <https://www.apple.com/macos>
  macOS,

  /// Windows: <https://www.windows.com>
  windows,
}

  1. scrollbarTheme 自定义[滚动条]颜色、粗细和形状的主题。
//定义后代 [Scrollbar] 小部件的默认属性值。
/// 后代小部件通过 `ScrollbarTheme.of(context)` 获取当前的 [ScrollbarThemeData] 对象。 [ScrollbarThemeData] 的实例可以使用 [ScrollbarThemeData.copyWith] 进行自定义。
///
/// 通常,[ScrollbarTheme] 的 [ScrollbarThemeData] 被指定为带有 [ThemeData.scrollbarTheme] 的整体 [Theme] 的一部分。
///
/// 所有 [ScrollbarThemeData] 属性默认为 `null`。 当为空时,
/// [滚动条] 计算自己的默认值,通常基于整体
/// 主题的 [ThemeData.colorScheme]。
///
class ScrollbarThemeData with Diagnosticable {
  /// Creates a theme that can be used for [ThemeData.scrollbarTheme].
  const ScrollbarThemeData({
    this.thumbVisibility,
    this.thickness,
    this.trackVisibility,
    this.radius,
    this.thumbColor,
    this.trackColor,
    this.trackBorderColor,
    this.crossAxisMargin,
    this.mainAxisMargin,
    this.minThumbLength,
    this.interactive,
    @Deprecated(
      'Use thumbVisibility instead. '
      'This feature was deprecated after v2.9.0-1.0.pre.',
    )
    this.isAlwaysShown,
    @Deprecated(
      'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. '
      'This feature was deprecated after v2.9.0-1.0.pre.',
    )
    this.showTrackOnHover,
  }) : assert(
         isAlwaysShown == null || thumbVisibility == null,
         'Scrollbar thumb appearance should only be controlled with thumbVisibility, '
         'isAlwaysShown is deprecated.'
       );


  1. splashFactory 定义由 [InkWell] 和 [InkResponse]产生的水波纹的外观

abstract class InteractiveInkFeatureFactory {
  const InteractiveInkFeatureFactory();

  @factory
  InteractiveInkFeature create({
    required MaterialInkController controller,
    required RenderBox referenceBox,
    required Offset position,
    required Color color,
    required TextDirection textDirection,
    bool containedInkWell = false,
    RectCallback? rectCallback,
    BorderRadius? borderRadius,
    ShapeBorder? customBorder,
    double? radius,
    VoidCallback? onRemoved,
  });
}

  1. visualDensity 定义用户界面组件的视觉密度。
/// 定义用户界面组件的视觉密度。
///
/// 密度,在 UI 的上下文中,是垂直和水平的
/// UI 中组件的“紧凑性”。它是无单位的,因为它对不同的 UI 组件意味着不同的东西。
///
/// 垂直和水平的视觉密度默认为零
/// 密度,对应Material Design规范中组件的默认视觉密度。它不影响文本大小、图标大小或填充值。
/// 例如,对于按钮,它会影响按钮子元素周围的间距。对于列表,它会影响列表中条目基线之间的距离。对于芯片,它只影响垂直尺寸,而不影响水平尺寸。
/// 以下是一些响应密度变化的小部件示例:
///
///  * [Checkbox]
///  * [Chip]
///  * [ElevatedButton]
///  * [FlatButton]
///  * [IconButton]
///  * [InputDecorator] (which gives density support to [TextField], etc.)
///  * [ListTile]
///  * [MaterialButton]
///  * [OutlinedButton]
///  * [Radio]
///  * [RawMaterialButton]
///  * [TextButton]


class VisualDensity with Diagnosticable {
  /// A const constructor for [VisualDensity].
  ///
  /// All of the arguments must be non-null, and [horizontal] and [vertical]
  /// must be in the interval between [minimumDensity] and [maximumDensity],
  /// inclusive.
  const VisualDensity({
    this.horizontal = 0.0,
    this.vertical = 0.0,
  }) : assert(horizontal != null),
       assert(vertical != null),
       assert(vertical <= maximumDensity),
       assert(vertical <= maximumDensity),
       assert(vertical >= minimumDensity),
       assert(horizontal <= maximumDensity),
       assert(horizontal >= minimumDensity);

  /// The minimum allowed density.
  static const double minimumDensity = -4.0;

  /// The maximum allowed density.
  static const double maximumDensity = 4.0;
//......
}
  1. useMaterial3 用于选择加入 Material 3 功能的临时标志。
 /// 用于选择加入 Material 3 功能的临时标志。
/// 如果为 true,则已迁移到 Material 3 的组件将使用 Material 3 的新颜色、排版和其他功能。
///如果为 false,它们将使用 Material 2 的外观。如果在 [useMaterial3] 设置为 true 的情况下构造 [ThemeData],则某些属性将获得特殊的默认值。
///但是,仅复制 [useMaterial3] 设置为 true 的 [ThemeData] 不会更改生成的 [ThemeData] 中的任何这些属性。
///这些属性是: 
  /// | Property        | Material 3 default           | Fallback default          |
  /// | :-------------- | :--------------------------- | :------------------------ |
  /// | [typography]    | [Typography.material2021]    | [Typography.material2014] |
  /// | [splashFactory] | [InkSparkle]* or [InkRipple] | [InkSplash]               |
/// 在迁移到 Material 3 期间,打开它可能会在您的应用中产生不一致的外观。一些组件将在其他组件之前迁移,并且排版更改将分阶段进行。
/// [useMaterial3] 默认为 false。在所有迁移的组件都登陆稳定后,我们将默认将其更改为 true。在该更改登陆稳定版后,我们将弃用此标志并删除它的所有用途。那时一切都将使用 Material 3 的外观和感觉。
/// 已经迁移到 Material 3 的组件有:
  ///   * [AlertDialog]
  ///   * [AppBar]
  ///   * [Card]
  ///   * [Dialog]
  ///   * [ElevatedButton]
  ///   * [FloatingActionButton]
  ///   * [Material]
  ///   * [NavigationBar]
  ///   * [NavigationRail]
  ///   * [OutlinedButton]
  ///   * [StretchingOverscrollIndicator], replacing the
  ///     [GlowingOverscrollIndicator]
  ///   * [TextButton]
  ///   * [Material Design 3](https://m3.material.io/).
  1. colorScheme 一组十二种颜色,可用于配置大多数组件的颜色属性。颜色属性的作用
/// * Primary colors用于整个 UI 的关键组件,例如 FAB、突出按钮和活动状态。
/// * Secondary colors 用于UI中不太突出的组件,例如滤镜芯片,同时扩大了颜色表达的机会。
/// * Tertiary colors 用于对比强调色,可用于平衡原色和二次色或提高对元素的关注,例如输入字段。第三色留给制造商自行决定使用,旨在支持
 产品中更广泛的色彩表达。
/// 该方案的其余颜色由用于背景和表面的中性颜色以及用于错误、分隔线和阴影的特定颜色组成。
/// 许多颜色都有匹配的“on”颜色,用于在匹配颜色之上绘制内容。例如,如果某物使用 [primary] 作为背景颜色,则 [onPrimary] 将用于在其上绘制文本和图标。出于这个原因,“打开”颜色应与其匹配颜色具有至少 4.5:1 的对比度,以便可读。

/// 如果未提供颜色,将使用与给定颜色最接近的备用颜色(例如 [primaryContainer] 将默认为 [primary])。 Material Design 3 将这些颜色用于许多组件的默认设置,因此为了获得最佳效果,应用程序应该
为所有参数提供颜色。确保这一点的一种简单方法是
使用 [ColorScheme.fromSeed] 生成全套颜色。
/// 在迁移到 Material Design 3 期间,如果应用程序的 [ThemeData.useMaterial3] 为 false,则组件将仅使用以下颜色作为默认颜色:
  ///
  /// * [primary]
  /// * [onPrimary]
  /// * [secondary]
  /// * [onSecondary]
  /// * [error]
  /// * [onError]
  /// * [background]
  /// * [onBackground]
  /// * [surface]
  /// * [onSurface]

//颜色属性
const ColorScheme({
    required this.brightness,
    // 主要角色用于整个 UI 中的关键组件,例如 FAB(FloatingActionButton)、突出按钮、活动状态以及提升表面的色调。
    required this.primary,
    // 应用于位于primary之上的内容(图标、文本等)
    required this.onPrimary,
    //应用于需要比primary更少强调的元素
    Color? primaryContainer,
    //应用于位于 primary container顶部的内容(图标、文本等)
    Color? onPrimaryContainer,
    //次要角色用于 UI 中不太突出的组件,例如  chips,同时扩大了颜色表达的机会。
    required this.secondary,
    //在辅助上绘制时清晰易读的颜色。
    required this.onSecondary,
    // 一种颜色,用于不需要强调次要的元素。
    Color? secondaryContainer,
    //在 secondaryContainer 上绘制时清晰易读的颜色。
    Color? onSecondaryContainer,
    //tertiary用于对比重音,可用于平衡主色和辅助色或增加对元素的关注,例如输入字段。 tertiary的作用留给制造商自行决定使用,旨在支持产品中更广泛的颜色表达。
    Color? tertiary,
    //在第三级上绘制时清晰易读的颜色。
    Color? onTertiary,
    //一种颜色,用于需要比第三级更少强调的元素。
    Color? tertiaryContainer,
    //在 tertiaryContainer 上绘制时清晰易读的颜色。
    Color? onTertiaryContainer,
   //用于输入验证错误的颜色,例如对于 InputDecoration.errorText。
    required this.error,
    //A color that's clearly legible when drawn on error.
    required this.onError,
    //一种用于错误元素的颜色,它需要的重点少于error。
    Color? errorContainer,
    //在 errorContainer 上绘制时清晰易读的颜色。
    Color? onErrorContainer,
    /// 通常出现在可滚动内容后面的颜色。
    required this.background,
    required this.onBackground,
    //Card等小部件的背景颜色。
    required this.surface,
    required this.onSurface,
    //一种表面的颜色变体,可用于区分使用表面的组件。
    Color? surfaceVariant,
    Color? onSurfaceVariant,
    Color? outline,
    //一种用于绘制elevated 组件的阴影的颜色。
    Color? shadow,
    //一种表面颜色,用于显示与周围 UI 中看到的相反的内容,例如在 SnackBar 中以引起对警报的注意。
    Color? inverseSurface,
    Color? onInverseSurface,
    //一种强调色,用于在 inverseSurface 背景上显示高亮颜色,例如 SnackBar 中的按钮文本。
    Color? inversePrimary,
    //一种颜色,用作表面颜色上的overlay ,以指示组件的elevation。
    Color? surfaceTint,
    @Deprecated(
      'Use primary or primaryContainer instead. '
      'This feature was deprecated after v2.6.0-0.0.pre.'
    )
    Color? primaryVariant,
    @Deprecated(
      'Use secondary or secondaryContainer instead. '
      'This feature was deprecated after v2.6.0-0.0.pre.'
    )
    Color? secondaryVariant,
  })
primary.png
secondary.png
tertiary.png
  1. 其他颜色属性
   //
   Color? colorSchemeSeed,
    Brightness? brightness, //调整亮度白天模式和夜间模式
    MaterialColor? primarySwatch,//Material风格的组件提供主题色
    Color? primaryColor,// 应用程序主要部分的背景颜色(toolbars、tab bars 等)
    Color? primaryColorLight,// primaryColor的浅色版
    Color? primaryColorDark,// primaryColor的深色版
    Color? focusColor,,//使用的焦点颜色表示组件具有输入焦点
    Color? hoverColor,//用于指示指针悬停颜色
    Color? shadowColor,  // 阴影层颜色
    Color? canvasColor, ////  MaterialType.canvas 的默认颜色
    Color? scaffoldBackgroundColor, // Scaffold的默认颜色。典型Material应用程序或应用程序内页面的背景颜色。
    Color? bottomAppBarColor,// BottomAppBar的默认颜色
    Color? cardColor,// Card的颜色
    Color? dividerColor,// Divider和PopupMenuDivider的颜色,也用于ListTile之间、DataTable的行之间等。
    Color? highlightColor,// 选中在泼墨动画期间使用的突出显示颜色,或用于指示菜单中的项。
    Color? splashColor, // 水波纹的颜色。InkWell
    Color? selectedRowColor,// 用于突出显示选定行的颜色。
    Color? unselectedWidgetColor,// 用于处于非活动(但已启用)状态的小部件的颜色。例如,未选中的复选框。通常与accentColor形成对比。也看到disabledColor。
    Color? disabledColor,// 禁用状态下部件的颜色,无论其当前状态如何。例如,一个禁用的复选框(可以选中或未选中)。
    Color? secondaryHeaderColor,// 选定行时PaginatedDataTable标题的颜色。
    Color? backgroundColor, // 与主色形成对比的颜色,例如用作进度条的剩余部分。
    Color? dialogBackgroundColor, // Dialog 元素的背景颜色
    Color? indicatorColor, // 选项卡中选定的选项卡指示器的颜色。
    Color? hintColor, // 用于提示文本或占位符文本的颜色,例如在TextField中。
    Color? errorColor, // 用于输入验证错误的颜色,例如在TextField中
    Color? toggleableActiveColor,// 用于突出显示Switch、Radio和Checkbox等可切换小部件的活动状态的颜色。
  1. 文本和排版
    String? fontFamily,//字体
    Typography? typography, //排版 可以产看https://material.io/design/typography/the-type-system.html
    TextTheme? textTheme,//颜色与卡片和画布颜色形成对比的文本
    TextTheme? primaryTextTheme,//与原色形成对比的文本主题 
    IconThemeData? iconTheme,//与卡片和画布颜色形成对比的图标主题
    IconThemeData? primaryIconTheme,,//与原色形成对比的图标主题 
//设置组件中Text的字体样式
ThemeData(
      // appBarTheme: AppBarTheme(titleTextStyle:TextStyle(color: Colors.red,fontSize: 30) ),//这里设置AppBar的背景颜色
      textTheme: const TextTheme(
        //用于 [showDatePicker] 显示的对话框中的日期。
        displayMedium: TextStyle(fontSize: 25.0, color: Colors.deepPurple),
        //用于应用栏和对话框中的主要文本(例如,[AppBar.title] 和 [AlertDialog.title])。这里设置AppBar的title字体颜色是没有用的
        titleLarge: TextStyle(fontSize: 25.0, color: Colors.blue),
        //用于列表中的主要文本(例如,[ListTile.title])。
        titleMedium: TextStyle(fontSize: 20.0, color: Colors.red),
        // [Material]的默认文本样式。
        bodyMedium: TextStyle(fontSize: 40, color: Colors.green),
        // 用于 [ElevatedButton]、[TextButton] 和 [OutlinedButton] 上的文本。
        labelLarge: TextStyle(fontSize: 40, color: Colors.yellow),
        // 用于与图像关联的辅助文本。
        bodySmall: TextStyle(fontSize: 40, color: Colors.cyan),
      ),
    );

15.组件主题设置

    AppBarTheme? appBarTheme,
    MaterialBannerThemeData? bannerTheme,
    BottomAppBarTheme? bottomAppBarTheme,
    BottomNavigationBarThemeData? bottomNavigationBarTheme,
    BottomSheetThemeData? bottomSheetTheme,
    ButtonBarThemeData? buttonBarTheme,
    ButtonThemeData? buttonTheme,
    CardTheme? cardTheme,
    CheckboxThemeData? checkboxTheme,
    ChipThemeData? chipTheme,
    DataTableThemeData? dataTableTheme,
    DialogTheme? dialogTheme,
    DividerThemeData? dividerTheme,
    DrawerThemeData? drawerTheme,
    ElevatedButtonThemeData? elevatedButtonTheme,
    FloatingActionButtonThemeData? floatingActionButtonTheme,
    ListTileThemeData? listTileTheme,
    NavigationBarThemeData? navigationBarTheme,
    NavigationRailThemeData? navigationRailTheme,
    OutlinedButtonThemeData? outlinedButtonTheme,
    PopupMenuThemeData? popupMenuTheme,
    ProgressIndicatorThemeData? progressIndicatorTheme,
    RadioThemeData? radioTheme,
    SliderThemeData? sliderTheme,
    SnackBarThemeData? snackBarTheme,
    SwitchThemeData? switchTheme,
    TabBarTheme? tabBarTheme,
    TextButtonThemeData? textButtonTheme,
    TextSelectionThemeData? textSelectionTheme,
    TimePickerThemeData? timePickerTheme,
    ToggleButtonsThemeData? toggleButtonsTheme,
    TooltipThemeData? tooltipTheme,
    ExpansionTileThemeData? expansionTileTheme,
    AndroidOverscrollIndicator? androidOverscrollIndicator,

简单使用

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class AppThemeConfig {
  //设置不允许字体放大
  static const double textScaleFactor = 1.0;

  //不允许字体跟随系统变化
  static Widget fixedTextScale(
      {required BuildContext context, required Widget child}) {
    return MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaleFactor: textScaleFactor),
        child: child);
  }

  //设置App支持的屏幕方向
  static const List<DeviceOrientation> supportOrientations = [
    DeviceOrientation.portraitUp
  ];

  //runApp 之前调用
  static void setupDevice() {
    WidgetsFlutterBinding.ensureInitialized();
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.green, //状态栏背景颜色
        statusBarIconBrightness: Brightness.light // dark:一般显示黑色   light:一般显示白色
        ));
    //设置屏幕的方向
    SystemChrome.setPreferredOrientations(supportOrientations);
  }

  //[AppBar.title] 和 [AlertDialog.title])等字体样式
  static const TextStyle titleLarge =
      TextStyle(fontSize: 30.0, color: Colors.red);

  //用于列表中的主要文本(例如,[ListTile.title])。
  static const TextStyle titleMedium =
      TextStyle(fontSize: 25.0, color: Colors.blue);

  // [Material]的默认文本样式。
  static const TextStyle defaultStyle =
      TextStyle(fontSize: 25.0, color: Colors.blue);

  // 用于 [ElevatedButton]、[TextButton] 和 [OutlinedButton] 上的文本。
  static const TextStyle buttonStyle =
      TextStyle(fontSize: 25.0, color: Colors.blue);

  //用于 [showDatePicker] 显示的对话框中的日期。
  static const TextStyle pickerStyle =
      TextStyle(fontSize: 25.0, color: Colors.blue);

  //字体
  static const String fontFamily = '';

  //AppBar标题颜色
  static const Color appBarTitleColor = Colors.green;

  //AppBar背景颜色
  static const Color appBarBgColor = Colors.green;

  //Scaffold背景颜色
  static const Color scaffoldBgColor = Colors.amberAccent;

  static const Color dialogBgColor = Colors.white;

  //可滚动组件的背景颜色
  static const Color scrollBgColor = Colors.cyan;

  //页面跳转样式
  static const PageTransitionsTheme pageTransitionsTheme =
      PageTransitionsTheme(builders: {
    TargetPlatform.android: CupertinoPageTransitionsBuilder(),
    TargetPlatform.iOS: CupertinoPageTransitionsBuilder()
  });

  //ThemeData
  static final ThemeData themeData = ThemeData(
      brightness: Brightness.light,
      pageTransitionsTheme: pageTransitionsTheme,
      fontFamily: fontFamily,
      textTheme: const TextTheme(
        displayMedium: pickerStyle,
        titleLarge: titleLarge,
        titleMedium: titleMedium,
        bodyMedium: defaultStyle,
        labelLarge: buttonStyle,
      ),
      scaffoldBackgroundColor: scaffoldBgColor,
      dialogBackgroundColor: dialogBgColor,
      colorScheme: const ColorScheme.light().copyWith(
        primary: Colors.white,
        background: scrollBgColor,
      ),
      //去掉水波纹
      splashColor: Colors.transparent,
      appBarTheme: const AppBarTheme(
          elevation: 1,
          titleTextStyle: titleLarge,
          backgroundColor: appBarBgColor),
      tabBarTheme: const TabBarTheme(
          labelColor: Colors.red,
          labelStyle: TextStyle(fontSize: 20),
          unselectedLabelColor: Colors.grey,
          unselectedLabelStyle: TextStyle(fontSize: 20),
          indicatorSize: TabBarIndicatorSize.label),
      bottomNavigationBarTheme: const BottomNavigationBarThemeData(
          elevation: 1,
          backgroundColor: Colors.white,
          type: BottomNavigationBarType.fixed,
          selectedItemColor: Colors.red,
          unselectedItemColor: Colors.grey,
          selectedLabelStyle: TextStyle(fontSize: 12),
          unselectedLabelStyle: TextStyle(fontSize: 12),
          showSelectedLabels: true,
          showUnselectedLabels: true),
      bottomSheetTheme: const BottomSheetThemeData(
          backgroundColor: Colors.white,
          elevation: 1,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.0),
            topRight: Radius.circular(20.0),
          ))),
      dialogTheme: DialogTheme(
          backgroundColor: Colors.white,
          elevation: 1,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))),
      //以下是可选的
      textButtonTheme: const TextButtonThemeData(),
      elevatedButtonTheme: const ElevatedButtonThemeData(),
      outlinedButtonTheme: const OutlinedButtonThemeData());
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容