728x90
프로젝트에 추가용으로 간단하게 다크모드 예제를 만들어보겠습니다.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
static final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.light);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: themeNotifier,
builder: (_, ThemeMode currentMode, __) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'example_mode',
theme: ThemeData(primarySwatch: Colors.amber),
darkTheme: ThemeData.dark(),
themeMode: currentMode,
home: const Example(),
);
},
);
}
}
class Example extends StatelessWidget {
const Example({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
print('MyApp.themeNotifier.value ${MyApp.themeNotifier.value == ThemeMode.light}');
return Scaffold(
appBar: AppBar(
title: const Text('appbar'),
actions: [
IconButton(icon: Icon(MyApp.themeNotifier.value == ThemeMode.light ? Icons.light_mode : Icons.dark_mode),
onPressed: () {
MyApp.themeNotifier.value = MyApp.themeNotifier.value == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
},)
],
),
);
}
}
여기서 부터 더 간단하게 Getx 라이브러리를 사용해서 더 간단하게 만들 수 있다.
get 4.6.5
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'get',
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.system,
home: const Example(),
);
}
}
class Example extends StatelessWidget {
const Example({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('get_appbar'),
actions: [
IconButton(
icon: const Icon(Icons.lightbulb),
onPressed: () {
Get.isDarkMode
? Get.changeTheme(ThemeData.light())
: Get.changeTheme(ThemeData.dark());
})
],
),
);
}
}
이렇게 두 방법으로 다크 모드 변환을 만들어보았습니다.
728x90
'⭐️ 개발' 카테고리의 다른 글
Flutter가 대세다!! 중고나라에서도 플러터 사용한다!! (1) | 2023.08.08 |
---|---|
가로모드 세로모드에 맞게 위젯 설정하기 (0) | 2023.08.01 |
함수 작동 시간 체크 (0) | 2023.07.06 |
Node - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client (0) | 2023.07.03 |