音乐播放器:浅色和深色模式
本课属于 Coddy Flutter 学习旅程的“适配不同屏幕的布局”单元。第 30 课,共 30 课。
人们会在晚上听音乐,所以播放器增加了深色模式,并在顶部栏放置了一个按钮来切换模式。
AppBar 接受 actions:,这是一个列表,用于放置显示在右侧末端的按钮。这里有一个 IconButton,它会切换状态中的 bool,而 themeMode: 会根据它改变。按钮的图标表示它的功能:播放器处于浅色模式时显示月亮图标 Icons.dark_mode,处于深色模式时显示太阳图标 Icons.light_mode。
屏幕上所有来自主题的颜色都会随之改变:背景、文本、滑块和按钮。专辑封面会保留自己的颜色,就像图片一样。
挑战
简单添加深色模式:
- 一个字段
bool _dark = false; - 使用种子颜色
Colors.deepPurple和brightness: Brightness.dark设置darkTheme:,并根据_dark选择themeMode: - 在
AppBar的actions:中添加一个IconButton,深色模式下显示Icons.light_mode,浅色模式下显示Icons.dark_mode,并在setState中切换_dark
亲手试试
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
double _position = 0.3;
bool _playing = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(title: const Text('Now Playing')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Stack(
children: [
Container(
width: double.infinity,
height: 300,
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: BorderRadius.circular(24),
),
child: const Center(
child: Icon(Icons.album, size: 120, color: Colors.white),
),
),
Positioned(
top: 12,
right: 12,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(8),
),
child: const Text(
'HD',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
),
],
),
const SizedBox(height: 24),
const Text(
'Midnight Drive',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
const Text('The Night Owls', style: TextStyle(color: Colors.grey)),
const SizedBox(height: 16),
Slider(
value: _position,
onChanged: (value) {
setState(() {
_position = value;
});
},
),
const Row(
children: [
Text('1:12'),
Spacer(),
Text('3:45'),
],
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: IconButton(
iconSize: 40,
icon: const Icon(Icons.skip_previous),
onPressed: () {},
),
),
Expanded(
child: IconButton(
iconSize: 64,
icon: Icon(_playing ? Icons.pause : Icons.play_arrow),
onPressed: () {
setState(() {
_playing = !_playing;
});
},
),
),
Expanded(
child: IconButton(
iconSize: 40,
icon: const Icon(Icons.skip_next),
onPressed: () {},
),
),
],
),
],
),
),
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
适配不同屏幕的布局中的所有课
自己练习: Flutter 在线编译器