音楽プレーヤー:ライトモードとダークモード
CoddyのFlutterジャーニー「画面サイズに合わせたレイアウト」セクションの一部。レッスン 30/30。
夜に音楽を聴く人もいるため、プレーヤーにダークモードを追加し、トップバーのボタンで切り替えられるようにします。
AppBar は actions: を受け取り、右端に表示するボタンのリストを指定します。そこにある IconButton の1つで状態の bool を切り替え、themeMode: もそれに連動させます。ボタンのアイコンは機能を表します。プレーヤーがライトモードのときは月の Icons.dark_mode、ダークモードのときは太陽の Icons.light_mode です。
テーマに由来する画面上の色はすべて、それに合わせて変わります。背景、テキスト、スライダー、ボタンが変わります。アルバムアートは絵と同じように、それ自体の色を保ちます。
チャレンジ
簡単ダークモードを追加します:
- フィールド
bool _dark = false; - シード
Colors.deepPurpleを使ったdarkTheme:と、brightness: Brightness.dark、および_darkによって選択されるthemeMode: AppBarのactions:に、ダークモード時はIcons.light_mode、ライトモード時はIcons.dark_modeを表示し、setState内で_darkを切り替えるIconButton
自分で試してみよう
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オンラインコンパイラ