Last active
October 26, 2022 15:34
-
-
Save internetova/8d292cae6286002de74a78af58afc3fa to your computer and use it in GitHub Desktop.
Пример переключения темы в простом варианте
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const App()); | |
} | |
class App extends StatefulWidget { | |
const App({Key? key}) : super(key: key); | |
@override | |
State<App> createState() => _AppState(); | |
} | |
class _AppState extends State<App> { | |
@override | |
Widget build(BuildContext context) { | |
return ValueListenableBuilder<bool>( | |
valueListenable: AppSettings.themeIsLight, | |
builder: (_, isLight, __) => MaterialApp( | |
title: 'Places', | |
theme: isLight ? AppTheme.lightTheme : AppTheme.darkTheme, | |
home: const SettingsScreen(), | |
), | |
); | |
} | |
} | |
/// Экран настроек | |
class SettingsScreen extends StatelessWidget { | |
const SettingsScreen({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
final isDark = Theme.of(context).brightness == Brightness.dark; | |
return Scaffold( | |
appBar: AppBar(), | |
body: Column( | |
children: [ | |
ListTile( | |
title: const Text('Тема темная'), | |
trailing: CupertinoSwitch( | |
value: isDark, | |
onChanged: (value) { | |
AppSettings.themeIsLight.value = !value; | |
}, | |
), | |
), | |
], | |
), | |
); | |
} | |
} | |
/// Хранилище настроек (временно, до прохождения стейт менеджеров) | |
abstract class AppSettings { | |
/// настройки темы | |
static ValueNotifier<bool> themeIsLight = ValueNotifier(true); | |
} | |
/// Тема приложения | |
class AppTheme { | |
static ThemeData get lightTheme => _buildTheme(); | |
static ThemeData get darkTheme => _buildThemeDark(); | |
AppTheme._(); | |
/// Светлая тема | |
// ignore: long-method | |
static ThemeData _buildTheme() { | |
final _base = ThemeData.light(); | |
return _base.copyWith( | |
brightness: Brightness.light, | |
); | |
} | |
/// Темная тема | |
// ignore: long-method | |
static ThemeData _buildThemeDark() { | |
final _base = ThemeData.dark(); | |
return _base.copyWith( | |
brightness: Brightness.dark, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dartpad.dev/?id=8d292cae6286002de74a78af58afc3fa