Flutter Widget 之Theme

286 阅读2分钟

你是否厌倦了自家应用程序不够骇人,实际上你可能正是觉得如此。

因为预设主题一点也不可怕,所以正好说到你的情况。利用Theme部件,让用户实际体验应景的时节气氛,你或许已看过MaterialApp类中数据库中所含的默认主题。

MaterialApp就位于应用程序中的root权限中。这主题设置提供了一些快速、实用的方法。

像是明亮和黑暗模式

MaterialApp(
    theme: ThemeData(),
)

image.png

MaterialApp(
    theme: ThemeData(),
    darkTheme: ThhemeData.dark(),
)

image.png

不过,尽管你可能以为黑暗模式已足以让用户感到深刻的战栗,但实际上,能做的远不只如此

首先你就注意到theme参数,实际上需要一个ThemeData实例,若你还记得提过的一项严正警告,这最好是ThemeData类中最重要的属性,也就是所属的colorTheme和textTheme

ThemeData(
    colorScheme:
    textTheme:
)

将colorTheme参数设置为橙色,以立即提升惊悚的效果,这样就好多了

ThemeData(
    colorScheme: ColorScheme.fromSwatch(
        primarySwarch: Colors.orange,
    ),
)

image.png

你对这参数的认识或者来自于它的另一个身份:primarySwatch

ThemeData(
    primarySwatch: Colors.orange,
)

接下来谈着另一项重要的参数 textTheme,因为普通字型不敷所需,我偏好使用GoogleFonts插件来达成所需的效果

ThemeData(
    primarySwatch: Colors.orange,
    textTheme: GoogleFons.emilysCandyTextTheme(),
)

image.png

这看起来真的很可怕。

还有很多其他的配色参数可应付应用程序的其他所需

ThemeData(
    primarySwatch: Colors.orange,
    textTheme: GoogleFonts.emilysCandyTextTheme(),
    scaffoldBackgroundColor: Colors.orange[100].
)

image.png

这些参数配置常是由colorScheme中提取默认值。

但也可由您设置调整。其余ThemeData类则是形形色色的次要主题聚合在一块儿。这些套用都会涵盖整个应用程序

  • inputDecorationTheme: InputDecorationTheme()
  • iconTheme: IconTheme()
  • primaryIconTheme: PrimaryIconTheme()
  • sliderTheme: SliderTheme()
  • tabBarTheme: TabBarTheme()
  • tooltipTheme: TooltipTheme()
  • cardTheme: CardTheme()
  • chipTheme: ChipTheme()
  • platform: Platform()
  • materialTapTargetSize: MaterialTapTargetSize()
  • applyElevationOverlayColor: ApplyElevationOverlayColor()
  • pageTransitionsTheme: PageTransitionsTheme()
  • scrollbarTheme: ScrollbarTheme()
  • dialogTheme: DialogTheme()
  • floatingActionButtonTheme: FloatingActionButtonTheme()
  • navigationRailTheme: NavigationRailTheme()
  • typography: Typography()
  • cupertionOverrideTheme: CupertionOverrideTheme()
  • snackBarTheme: SnackBarTheme()
  • bottomSheetTheme: BottomSheetTheme()
  • popupMenuTheme: PopupMenuTheme()
  • bannerTheme: BannerTheme()
  • dividerTheme: DividerTheme()
  • buttoomBarTheme: ButtonBarTheme()
  • bottomNavigationBarTheme: BottomNavigationBarTheme()
  • timePickerTheme: TimePickerTheme()
  • textButtonTheme: TextButtonTheme()
  • elevatedButtonTheme: ElevatedButtonTheme()
  • outlinedButtonTheme: OutlinedButtonTheme()
  • textSelectionTheme: TextSelectionTheme()
  • dataTableTheme: DataTableTheme()
  • checkboxTheme: CheckboxTheme()
  • radioTheme: TadioTheme()
  • switchTheme: SwitchTheme()
  • progressIndicatorTheme: ProgressIndicatorTheme()
  • drawerTheme: DrawerTheme()

但若只要做细部调整怎么办?或许利用主题选择器便可让用户预览将套用的惊悚效果

利用Theme Widget部件再提供新数据或复制既有主题并依需求调整

Theme(
    data: Theme.of(context).copyWith(...),
    child: MyWidget(),
)

但这两种方式中,无论何时写入theme.of(context),Flutter都会搜寻部件的树状结构查找第一个ThemeData,可能会是你安排在某处的Theme Widget部件或是会一路溯源MaterialApp, 这样就行了

ezgif.com-gif-maker.gif

如果想了解有关Theme的内容,或者关于Flutter的其他功能,请访问flutter.dev

原文翻译自视频:视频地址