Flutter 夜间模式

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  ThemeMode themeMode = ThemeMode.light;

  void updateThemeMode() {
    setState(() => themeMode = getThemeMode());
  }

  ThemeMode getThemeMode() {
    switch (themeMode) {
      case ThemeMode.light:
        return ThemeMode.dark;
      case ThemeMode.dark:
        return ThemeMode.light;
      default:
        // 跟随系统
        return ThemeMode.system;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      // 确定应用程序将使用哪个主题(请实现自定义)
      themeMode: themeMode,
      theme: ThemeProvider().getTheme(),
      darkTheme: ThemeProvider().getTheme(isDark: true),
      home: Scaffold(
        appBar: AppBar(
          title: Text('app title'),
        ),
        floatingActionButton: FloatingActionButton(
          child: Text('theme'),
          onPressed: () => updateThemeMode(),
        ),
      ),
    );
  }
}

class ThemeProvider {
  static ThemeProvider _instance;

  ThemeProvider._internal();

  factory ThemeProvider() {
    if (_instance == null) {
      _instance = ThemeProvider._internal();
    }
    return _instance;
  }

  getTheme({bool isDark: false}) {
    // 更多配置看内部实现,不配则使用默认样式
    return ThemeData(
      appBarTheme: AppBarTheme(
        brightness: isDark ? Brightness.dark : Brightness.light,
      ),
      brightness: isDark ? Brightness.dark : Brightness.light,
      cupertinoOverrideTheme: CupertinoThemeData(
        brightness: isDark ? Brightness.dark : Brightness.light,
      ),
    );
  }
}

内部获取当前主题

bool _isDark = Theme.of(context).brightness == Brightness.dark;

你可能感兴趣的:(Flutter 夜间模式)