Flutter適配深色模式(DarkMode)

唯鹿發表於2019-10-14

在這裡插入圖片描述

1.瞎叨叨

也不知道寫點什麼,本來想寫寫Flutter的整合測試。因為前一陣子給flutter_deer寫了一套,不過感覺也沒啥內容,寫不了幾句話就放棄了。(其實本篇內容也不多。。。)

那就寫寫最近在做的事情。沒錯,就是文章標題提到的適配深色模式(DarkMode),也可以說是實現夜間模式的功能。相信許多iOS的同學最近都比較關注,畢竟iOS 13上個月推送更新了。

說適配的原因是因為在iOS 13 和 Android 10系統上它都屬於新特性。適配的目的是為了達到應用的主題隨著系統主題模式的切換而變化,給使用者更好的一致性體驗。與它類似的就是系統語言的設定,當系統設定某種語言時,應用內的文字也相應變化。

好在Flutter也提供了適配的入口,使得我們可以一次適配兩個平臺。我手上的小米mix2s雖然是Android 9 的,沒想到也能適配。

2.準備工作

下面我就說說我在適配flutter_deer中的經驗,Flutter版本1.9.1。

首先是規範問題,標題、副標題、分割線、各種背景等顏色,以及深色模式下相對應的顏色一定要先規範起來。否則你自己不僅被這些顏色搞得眼冒金星,同時應用也沒有一個統一的風格。

3.適配開始

1.全域性調整

Flutter 在 MaterialApp中提供了themedarkTheme兩個入口讓我們設定兩種模式下的顏色及文字樣式。接收的ThemeData中近乎涵蓋了所有Material Widget中所使用的顏色及主題。(Cupertino系列元件官方還在適配中,所以Flutter版本1.9.1暫不支援。)

通過配置themedarkTheme可以讓我們省去很多的判斷程式碼,比如我的分割線在不同模式下是兩種不同顏色,我不可能每使用一次,就在使用的地方去判斷一次。通過配置全域性dividerTheme,我們就可以直接使用Divider()或者BorderSide

	ThemeData(
      dividerTheme: DividerThemeData(
        color: isDarkMode ? Colours.dark_line : Colours.line,
        space: 0.6,
        thickness: 0.6
      )
    );
複製程式碼

同樣我們的頁面背景色、文字樣式都可以這樣配置。以下就是deer中最終整理的配置。

	ThemeData(
      errorColor: isDarkMode ? Colours.dark_red : Colours.red,
      brightness: isDarkMode ? Brightness.dark : Brightness.light,
      primaryColor: isDarkMode ? Colours.dark_app_main : Colours.app_main,
      accentColor: isDarkMode ? Colours.dark_app_main : Colours.app_main,
      // Tab指示器顏色
      indicatorColor: isDarkMode ? Colours.dark_app_main : Colours.app_main,
      // 頁面背景色
      scaffoldBackgroundColor: isDarkMode ? Colours.dark_bg_color : Colors.white,
      // 主要用於Material背景色
      canvasColor: isDarkMode ? Colours.dark_material_bg : Colors.white,
      // 文字選擇色(輸入框複製貼上選單)
      textSelectionColor: Colours.app_main.withAlpha(70),
      textSelectionHandleColor: Colours.app_main,
      textTheme: TextTheme(
        // TextField輸入文字顏色
        subhead: isDarkMode ? TextStyles.textDark : TextStyles.text,
        // Text預設文字樣式
        body1: isDarkMode ? TextStyles.textDark : TextStyles.text,
        // 這裡用於小文字樣式
        subtitle: isDarkMode ? TextStyles.textDarkGray12 : TextStyles.textGray12,
      ),
      inputDecorationTheme: InputDecorationTheme(
        hintStyle: isDarkMode ? TextStyles.textHint14 : TextStyles.textDarkGray14,
      ),
      appBarTheme: AppBarTheme(
        elevation: 0.0,
        color: isDarkMode ? Colours.dark_bg_color : Colors.white,
        brightness: isDarkMode ? Brightness.dark : Brightness.light,
      ),
      dividerTheme: DividerThemeData(
        color: isDarkMode ? Colours.dark_line : Colours.line,
        space: 0.6,
        thickness: 0.6
      )
    );
複製程式碼

使用:

	MaterialApp (
      title: 'Flutter Deer',
      theme: getTheme(),
      darkTheme: getTheme(isDarkMode: true),
      home: TestPage()
    );			
複製程式碼

當然有些Widget沒有使用到,所以也就沒有去適配。以上這些color、theme具體的使用地方需要自己去翻看原始碼及註釋才能知道,所以這是一個比較費力的過程。

其實這裡你也可以利用某些“坑位”,比如應用內的另外一種功能文字在字號、顏色上都與主文字不一樣,使用的地方還很多,每次使用再判斷也很麻煩,這樣就可以設定到未使用的屬性上,比如上面程式碼中的subtitle。這樣使用時就可以通過呼叫Theme.of(context).textTheme.subtitle來實現。

Text(
  "文字", 
  style: Theme.of(context).textTheme.subtitle
)
複製程式碼

需要注意的是:畢竟是全域性配置,儘量保持通用,不要影響其他widget也是要考慮的地方。

這部分配置完成後,你需要的是"去同存異"。

  1. 比如你指定的文字樣式與全域性配置相同時,就需要刪除它。

  2. 如果文字顏色相同,但是字號不同。那就刪除顏色配置資訊,保留字號設定:

Text(
  "僅保留不同資訊",
  style: const TextStyle(
    fontSize: 12.0,
  )
)
複製程式碼

因為Text的原始碼中就是通過merge方法來合併全域性配置與區域性配置。merge中其實就是呼叫copyWith來實現的。所以也可以這樣寫:

Text(
  "僅保留不同資訊",
  style: Theme.of(context).textTheme.body1.copyWith(fontSize: 12.0)
)
複製程式碼
  1. 顏色不同。因為深色模式主要就是顏色變化,所以可以考慮上面的“subtitle”方案。如果僅有幾處,可以封裝一些方法統一判斷處理。

2.區域性調整

在經過全域性的配置後,大多數適配問題得到了解決。但可能還有一些細節要調整,比如圖示、個別的文字顏色、背景色。這時需要的就是如何判斷深色模式:

  bool isDarkMode(BuildContext context){
    return Theme.of(context).brightness == Brightness.dark;
  }
複製程式碼

這裡的brightness就是上面在全域性配置ThemeData中指定的brightness

Tips:

  1. 有些純色的小圖示可以直接使用Image.assetcolor來修改。

  2. ButtontextColor屬性最好還是區域性處理,因為原始碼中“非黑即白”,我很痛苦啊!

  /// The foreground color of the [button]'s text and icon.
  ///
  /// If [button] is not [MaterialButton.enabled], the value of
  /// [getDisabledTextColor] is returned. If the button is enabled and
  /// [buttonTextColor] is non-null, then [buttonTextColor] is returned.
  ///
  /// Otherwise the text color depends on the value of [getTextTheme]
  /// and [getBrightness].
  ///
  ///  * [ButtonTextTheme.normal]: [Colors.white] is used if [getBrightness]
  ///    resolves to [Brightness.dark]. [Colors.black87] is used if
  ///    [getBrightness] resolves to [Brightness.light].
  ///  * [ButtonTextTheme.accent]: [colorScheme.secondary].
  ///  * [ButtonTextTheme.primary]: If [getFillColor] is dark then [Colors.white],
  ///    otherwise if [button] is a [FlatButton] or an [OutlineButton] then
  ///    [colorScheme.primary], otherwise [Colors.black].
  Color getTextColor(MaterialButton button) {
    if (!button.enabled)
      return getDisabledTextColor(button);

    if (button.textColor != null)
      return button.textColor;

    switch (getTextTheme(button)) {
      case ButtonTextTheme.normal:
        return getBrightness(button) == Brightness.dark ? Colors.white : Colors.black87;

      case ButtonTextTheme.accent:
        return colorScheme.secondary;

      case ButtonTextTheme.primary: {
        final Color fillColor = getFillColor(button);
        final bool fillIsDark = fillColor != null
          ? ThemeData.estimateBrightnessForColor(fillColor) == Brightness.dark
          : getBrightness(button) == Brightness.dark;
        if (fillIsDark)
          return Colors.white;
        if (button is FlatButton || button is OutlineButton)
          return colorScheme.primary;
        return Colors.black;
      }
    }

    assert(false);
    return null;
  }
複製程式碼

3.功能擴充

如果你適配好了深色模式,其實可以稍微擴充一下這個功能。我想到了微信中的多語言功能,在多語言這類功能中,預設選項是“跟隨系統”,當然你也可以指定某種語言。

按照這個思路我在設定中新增了“夜間模式”的功能,預設也是跟隨系統,當然你也可以手動的開啟和關閉。

Flutter適配深色模式(DarkMode)

這裡暫時有個問題,在iOS手機上開啟深色模式,當我應用內關閉深色模式後,狀態列文字無法變為黑色

問題主要還是Flutter 1.9.1的版本並沒有適配iOS 13 Status Bar增的UIStatusBarStyleDarkContent

在這裡插入圖片描述

這個問題Flutter的issues中也有人反饋了,期待官方的適配修復吧。

上述這些,基本就是適配深色模式主要內容了。本身沒有什麼複雜的,主是是個細心活。

說了這麼多,最後放幾張適配的效果圖給大家看看:

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

詳細的程式碼以及實現細節,可以參看flutter_deer的程式碼。深色模式相關的設計圖也已經同步更新了。最後希望可以點贊支援一波!!!

相關文章