Flutter ThemeMode 实现主题切换

ThemeMode 是 Flutter 提供的一个枚举类,用于控制应用程序的主题模式。它定义了三种模式:

ThemeMode.system:根据系统的设置选择浅色或深色主题。
ThemeMode.light:总是使用浅色主题。
ThemeMode.dark:总是使用深色主题。
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 默认使用系统主题模式
  ThemeMode _themeMode = ThemeMode.system;

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ThemeMode Example',
      theme: ThemeData.light(), // 浅色主题
      darkTheme: ThemeData.dark(), // 深色主题
      themeMode: _themeMode, // 当前主题模式
      home: Scaffold(
        appBar: AppBar(title: Text('ThemeMode Example')),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Select Theme Mode:',
              style: TextStyle(fontSize: 20),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _themeMode = ThemeMode.light;
                });
              },
              child: Text('Light Mode'),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _themeMode = ThemeMode.dark;
                });
              },
              child: Text('Dark Mode'),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _themeMode = ThemeMode.system;
                });
              },
              child: Text('System Mode'),
            ),
          ],
        ),
      ),
    );
  }
}

效果 :

在这里插入图片描述

------------------------我是分割线--------------------------

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值