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

2023-04-28,,

应用中切换深色主题和暗色主题是比较常见的操作,今天我们就来学习一下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

fluter usage---->动态更换Theme的相关教程结束。

《fluter usage---->动态更换Theme.doc》

下载本文的Word格式文档,以方便收藏与打印。