关于flutter:flutter系列之在flutter中自定义themes

简介

个别状况下咱们在flutter中搭建的app基本上都是用的是MaterialApp这种设计模式,MaterialApp中为咱们接下来应用的按钮,菜单等提供了对立的款式,那么这种款式能不能进行批改或者自定义呢?

答案是必定的,一起来看看吧。

MaterialApp中的themes

MaterialApp也是一种StatefulWidget,在MaterialApp中跟theme相干的属性有这样几个:

  final ThemeData? theme;
  final ThemeData? darkTheme;
  final ThemeData? highContrastTheme;
  final ThemeData? highContrastDarkTheme;
  final ThemeMode? themeMode;

先来看下ThemeMode的定义:

enum ThemeMode {
  system,
  light,
  dark,
}

ThemeMode是一个枚举类,外面有三个枚举值,别离是system,light和dark。

咱们都晓得当初手机有一个暗黑模式,ThemeMode的这三种模式就是为了适应暗黑模式而生的。

system示意是零碎默认的模式,light是亮堂模式,dark是暗黑模式。

而ThemeData则定义了主题中各种组件或者口头的配色。

那么如果咱们想要实现自定义themes的性能,就能够利用这个ThemeData类来重写其中要重写的色彩。

ThemeData中还有专门为color变动定义的ColorScheme,还有为Text变动设置的TextTheme,这两个theme实际上是一系列的color汇合。

除了ThemeData,flutter中还有一个类叫做Theme。

Theme是一个StatelessWidget,这个widget中蕴含了ThemeData,它提供了一个Theme.of办法来让子widget取得最近的ThemeData数据。

这就意味着,在flutter中,子widget能够应用和父widget不同的主题,十分的棒。

自定义themes的应用

那么如何应用自定义themes呢?有两种形式。

第一种就是在应用MaterialApp的时候传入自定义的themes,如下所示:

  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

然而这种操作理论是传入了一个全新的ThemeData,如果咱们只想批改局部ThemeData中的数据应该如何解决呢?

咱们能够应用Theme.of办法从以后的Theme中拷贝一份,而后再调用copyWith办法,传入要批改的自定义属性即可。

如下所示:

  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: Theme.of(context).copyWith(useMaterial3: true),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

后面咱们提到了Theme这个widget,咱们还能够将要自定义Theme的widget用Theme包裹起来,实践上咱们能够将任何widget都用Theme来进行包装。

比方之前的floatingActionButton的实现是间接返回一个FloatingActionButton:

floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        )

而后咱们能够把FloatingActionButton用Theme包装起来,如下所示:

floatingActionButton: Theme(
        data: Theme.of(context).copyWith(focusColor: Colors.yellow),
        child: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      )

这样不同的组件就领有了不同的theme。

总结

当咱们须要自定义theme或者不同theme的时候,就能够思考应用本文中应用的办法来进行theme的自定义了。

本文的例子:https://github.com/ddean2009/learn-flutter.git

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理