Темы и стилизация Flutter
В этом разделе будет представлена настройка темы во Flutter, включая темы Material Design, пользовательские темы и тёмный режим.
ThemeData - тема приложения
Использование ThemeData позволяет единообразно настроить цвета темы приложения, шрифты, стили и многое другое.
Пример: Настройка темы приложения
void main() {
runApp(
MaterialApp(
theme: ThemeData(
// Основной цвет
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blue,
brightness: Brightness.light,
),
// Использовать Material 3
useMaterial3: true,
// Шрифт
fontFamily: 'Roboto',
// Тема AppBar
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
// Тема кнопки
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
// Тема поля ввода
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
),
),
home: const MyHomePage(),
),
);
}
runApp(
MaterialApp(
theme: ThemeData(
// Основной цвет
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blue,
brightness: Brightness.light,
),
// Использовать Material 3
useMaterial3: true,
// Шрифт
fontFamily: 'Roboto',
// Тема AppBar
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
),
// Тема кнопки
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
// Тема поля ввода
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
),
),
home: const MyHomePage(),
),
);
}
Theme.of - Использование темы
Используйте Theme.of(context) в виджете, чтобы получить текущую тему.
Пример: использование цветов темы
class ThemedButton extends StatelessWidget {
const ThemedButton({super.key});
@override
Widget build(BuildContext context) {
// Получить тему
final theme = Theme.of(context);
return Column(
children: [
// Использовать цвет темы
Контейнер(
color: theme.colorScheme.primary,
padding: const EdgeInsets.all(16),
child: Text(
'Основной цвет',
style: TextStyle(color: theme.colorScheme.onPrimary),
),
),
const SizedBox(height: 16),
// Использовать вторичный цвет
Контейнер(
color: theme.colorScheme.secondary,
padding: const EdgeInsets.all(16),
child: Text(
'Вторичный цвет',
style: TextStyle(color: theme.colorScheme.onSecondary),
),
),
const SizedBox(height: 16),
// Использовать цвет ошибки
Контейнер(
color: theme.colorScheme.error,
padding: const EdgeInsets.all(16),
child: Text(
'Цвет ошибки',
style: TextStyle(color: theme.colorScheme.onError),
),
),
],
);
}
}
const ThemedButton({super.key});
@override
Widget build(BuildContext context) {
// Получить тему
final theme = Theme.of(context);
return Column(
children: [
// Использовать цвет темы
Контейнер(
color: theme.colorScheme.primary,
padding: const EdgeInsets.all(16),
child: Text(
'Основной цвет',
style: TextStyle(color: theme.colorScheme.onPrimary),
),
),
const SizedBox(height: 16),
// Использовать вторичный цвет
Контейнер(
color: theme.colorScheme.secondary,
padding: const EdgeInsets.all(16),
child: Text(
'Вторичный цвет',
style: TextStyle(color: theme.colorScheme.onSecondary),
),
),
const SizedBox(height: 16),
// Использовать цвет ошибки
Контейнер(
color: theme.colorScheme.error,
padding: const EdgeInsets.all(16),
child: Text(
'Цвет ошибки',
style: TextStyle(color: theme.colorScheme.onError),
),
),
],
);
}
}
Тёмный режим
Пример: Поддержка тёмного режима
void main() {
runApp(
MaterialApp(
theme: ThemeData(
// Светлая тема
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
),
darkTheme: ThemeData(
// Тёмная тема
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blue,
brightness: Brightness.dark,
),
),
// Включить оба (необязательно)
themeMode: ThemeMode.system, // На основе системных настроек
// themeMode: ThemeMode.light // Принудительно светлая тема
// themeMode: ThemeMode.dark // Принудительно тёмная тема
home: const ThemeTogglePage(),
),
);
}
// Переключить тему
class ThemeTogglePage extends StatelessWidget {
const ThemeTogglePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Переключение темы')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Текущая тема'),
const SizedBox(height: 20),
// Кнопка переключения темы
ElevatedButton(
onPressed: () {
final currentMode = Theme.of(context).brightness;
if (currentMode == Brightness.light) {
// Переключиться в тёмный режим
Theme.of(context).setThemeMode(ThemeMode.dark);
} else {
// Переключиться в светлый режим
Theme.of(context).setThemeMode(ThemeMode.light);
}
},
child: const Text('Переключить тему'),
),
],
),
),
);
}
}
runApp(
MaterialApp(
theme: ThemeData(
// Светлая тема
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
),
darkTheme: ThemeData(
// Тёмная тема
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blue,
brightness: Brightness.dark,
),
),
// Включить оба (необязательно)
themeMode: ThemeMode.system, // На основе системных настроек
// themeMode: ThemeMode.light // Принудительно светлая тема
// themeMode: ThemeMode.dark // Принудительно тёмная тема
home: const ThemeTogglePage(),
),
);
}
// Переключить тему
class ThemeTogglePage extends StatelessWidget {
const ThemeTogglePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Переключение темы')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Текущая тема'),
const SizedBox(height: 20),
// Кнопка переключения темы
ElevatedButton(
onPressed: () {
final currentMode = Theme.of(context).brightness;
if (currentMode == Brightness.light) {
// Переключиться в тёмный режим
Theme.of(context).setThemeMode(ThemeMode.dark);
} else {
// Переключиться в светлый режим
Theme.of(context).setThemeMode(ThemeMode.light);
}
},
child: const Text('Переключить тему'),
),
],
),
),
);
}
}
Пользовательские расширения стиля
Пример: Пользовательская TextTheme
ThemeData(
textTheme: const TextTheme(
// Отображаемый текст (заголовок)
displayLarge: TextStyle(fontSize: 57, fontWeight: FontWeight.w400),
displayMedium: TextStyle(fontSize: 45, fontWeight: FontWeight.w400),
displaySmall: TextStyle(fontSize: 36, fontWeight: FontWeight.w400),
// Текст заголовка
headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.w400),
headlineMedium: TextStyle(fontSize: 28, fontWeight: FontWeight.w400),
headlineSmall: TextStyle(fontSize: 24, fontWeight: FontWeight.w400),
// Текст заголовка
titleLarge: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
titleMedium: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
titleSmall: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
// Основной текст
bodyLarge: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
bodyMedium: TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
bodySmall: TextStyle(fontSize: 12, fontWeight: FontWeight.w400),
// Текст метки
labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
labelMedium: TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
labelSmall: TextStyle(fontSize: 11, fontWeight: FontWeight.w500),
),
)
textTheme: const TextTheme(
// Отображаемый текст (заголовок)
displayLarge: TextStyle(fontSize: 57, fontWeight: FontWeight.w400),
displayMedium: TextStyle(fontSize: 45, fontWeight: FontWeight.w400),
displaySmall: TextStyle(fontSize: 36, fontWeight: FontWeight.w400),
// Текст заголовка
headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.w400),
headlineMedium: TextStyle(fontSize: 28, fontWeight: FontWeight.w400),
headlineSmall: TextStyle(fontSize: 24, fontWeight: FontWeight.w400),
// Текст заголовка
titleLarge: TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
titleMedium: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
titleSmall: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
// Основной текст
bodyLarge: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
bodyMedium: TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
bodySmall: TextStyle(fontSize: 12, fontWeight: FontWeight.w400),
// Текст метки
labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
labelMedium: TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
labelSmall: TextStyle(fontSize: 11, fontWeight: FontWeight.w500),
),
)
Другие расширенияИспользование ThemeData для централизованного управления стилями приложения облегчает переключение тем и поддержание согласованности стилей, упрощая сопровождение.