全屏浏览
缩小浏览
回到页首

fluter usage---->动态更换Theme

应用中切换深色主题和暗色主题是比较常见的操作,今天我们就来学习一下Flutter中动态的切换主题。

Simple Theme

import 'package:flutter/material.dart';

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

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

class _MyAppState extends State<MyApp> {
  bool isLight = true;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light().copyWith(
        textTheme: TextTheme(bodyText2: TextStyle(fontSize: 20, color: Colors.red)),
      ),
      darkTheme: ThemeData.dark().copyWith(
        textTheme: TextTheme(bodyText2: TextStyle(fontSize: 20, color: Colors.blue)),
      ),
      themeMode: isLight ? ThemeMode.light : ThemeMode.dark,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Theme"),
          centerTitle: true,
          actions: <Widget>[
            IconButton(icon: Icon(Icons.repeat), onPressed: () => setState(() => isLight = !isLight)),
          ],
        ),
        body: Center(child: Text("Hello World")),
      ),
    );
  }
}

这样我们可以通过点击Button来实现主题的动态切换,但是一旦我们重启应用,主题就会还原成深色。我们需要在切换主题的时候,保存我们现在的主题。可以使用shared_preferences库,以下是实现思路。

Save config in SharedPreference

  • add package denpendency
shared_preferences: ^0.5.7+3
  • final code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences preferences = await SharedPreferences.getInstance();
  final isLight = preferences.getBool("isLight") ?? true;
  runApp(MyApp(isLight));
}

class MyApp extends StatefulWidget {
  final bool isLight;

  MyApp(this.isLight);

  @override
  _MyAppState createState() => _MyAppState(isLight);
}

class _MyAppState extends State<MyApp> {
  bool isLight;

  _MyAppState(this.isLight);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light().copyWith(
        textTheme: TextTheme(bodyText2: TextStyle(fontSize: 20, color: Colors.red)),
      ),
      darkTheme: ThemeData.dark().copyWith(
        textTheme: TextTheme(bodyText2: TextStyle(fontSize: 20, color: Colors.blue)),
      ),
      themeMode: isLight ? ThemeMode.light : ThemeMode.dark,
      home: Scaffold(
        appBar: AppBar(
          title: Text("Theme"),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.repeat),
              onPressed: () async {
                setState(() => isLight = !isLight);
                SharedPreferences preferences = await SharedPreferences.getInstance();
                preferences.setBool("isLight", isLight);
              },
            )
          ],
        ),
        body: Center( child: Text("Hello World")),
      ),
    );
  }
}

Reference

video: https://v.youku.com/v_show/id_XNDczMTYyMDE4NA==.html

posted @ 2020-06-03 22:18  huhx  阅读(65)  评论(0编辑  收藏