30 天的最後一個部份就是要用狀態管理來實現 App 設定頁面功能。
今天要先來面對的是主題切換。
前面二十幾天,都在作其他頁面的功能,其實 Flutter 主打的功能之一是能夠很迅速的找到適合自己 App 的主題色彩。先前全部都是使用 Colors.bluegrey
當作主色調,要有切換不同主題的功能前必須要先宣告一些主題常數。
lib/constants/themes.dart
import "package:flutter/material.dart";
final BlueTheme = ThemeData(
primarySwatch: Colors.blue,
buttonTheme: ButtonThemeData(
buttonColor: Colors.blue,
textTheme: ButtonTextTheme.primary,
),
);
final BlueGreyTheme = ThemeData(
primarySwatch: Colors.blueGrey,
buttonTheme: ButtonThemeData(
buttonColor: Colors.blueGrey,
textTheme: ButtonTextTheme.primary,
),
);
final BrownTheme = ThemeData(
primarySwatch: Colors.brown,
buttonTheme: ButtonThemeData(
buttonColor: Colors.brown,
textTheme: ButtonTextTheme.primary,
),
);
final BlackTheme = ThemeData(
primarySwatch: Colors.black,
buttonTheme: ButtonThemeData(
buttonColor: Colors.black,
textTheme: ButtonTextTheme.primary,
),
);
加上四個主題顏色的常數。
lib/stores/setting.dart
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gitme_reborn/constants/themes.dart';
class SettingModel extends ChangeNotifier {
ThemeData _themeData = BlueGreyTheme;
ThemeData get theme => _themeData;
changeTheme(themeData) {
_themeData = themeData;
notifyListeners();
}
}
lib/main.dart
lib/pages/setting/setting.dart
先來跑看看改完的程式碼
不過出現了一個小問題,在切換成黑色主題時會出現以下錯誤。
主要是因為 Colors.black
並非 MaterialColor
,而 MaterialColor
這類別是針對 Material Design 中 The color system 作的程式設計。
在參考 StackOverflow - Error while changing the flutter theme color to black 後,新增修改些程式碼。
lib/constants/materialColors.dart
import "package:flutter/material.dart";
const MaterialColor materialBlack = MaterialColor(
_blackPrimaryValue,
<int, Color>{
50: Color(0xFF000000),
100: Color(0xFF000000),
200: Color(0xFF000000),
300: Color(0xFF000000),
400: Color(0xFF000000),
500: Color(_blackPrimaryValue),
600: Color(0xFF000000),
700: Color(0xFF000000),
800: Color(0xFF000000),
900: Color(0xFF000000),
},
);
const int _blackPrimaryValue = 0xFF000000;
lib/constants/themes.dart
--
成果
參考