Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 운영체제의 분류
- this()
- object클래스
- 기본형 매개변수
- 객체 배열
- 초기화 순서
- stateless widget
- 인스턴스 메서드
- 오버라이딩과 오버로딩 차이점
- PriorityQueue
- 운영체제의 구조
- 참조형 반환타입
- static import문
- 조상의 생성자
- this()와 참조변수 this 차이점
- 명예의전당(1)
- 프로그래머스
- FLUTTER
- 오버로딩
- 운영체제란 무엇인가
- 운영체제의 목적
- stateful widget 생명주기
- 참조형 매개변수
- 운영체제의 예
- 이것이코딩테스트다
- webview_flutter
- 클래스 변수
- stateful widget
- 호출스택
- static 메서드
Archives
- Today
- Total
Coram Deo
[Flutter] Provider에서 발생한 Dark mode 전환 문제 해결 본문
1. 문제
Twitter 클론 코딩 중 light mode ↔ Dark mode가 전환이 되지 않음
아무리 토글 버튼을 눌러도 토글버튼의 UI도 바뀌지 않고 전환도 안됨
2. 원인
set 사용 안하고 바로 _themeData 변경해서 notifyListeners 호출 안됨. 그 결과 상태 업데이트가 안됨
theme_provider.dart 파일에 있는
토글로 다크모드와 라이트모드를 전환해주는 toggleTheme() 함수가 문제였다.
나는 직접 _themeData를 설정해줘도 괜찮을 것이라고 생각했는데,
그게 아니었다...! set을 통해 설정해줘야 notifyListeners()가 호출이 되기 때문에 UI가 바뀌고 상태도 바뀌는 것이었다.
같은 클래스 안에 있는 함수라서 방심했다 !
3. 느낀점
Provider 패턴을 사용할 때, 같은 클래스 안의 변수라도 상태 변경이 필요할 경우, 반드시 set을 사용해야 적절한 상태 관리와 UI 반영이 가능하다는 점을 이해하게 되었다. (이렇게 해야 notifyListeners()가 호출되어 UI와 상태가 업데이트 되기 때문 !)
- theme_provider.dart 전체 코드
class ThemeProvider with ChangeNotifier {
// initially, set it as light mode
ThemeData _themeData = lightMode;
// get the current theme
ThemeData get themeData => _themeData;
// is it dark mode currently?
bool get isDarkMode => _themeData == darkMode;
// set the theme
set themeData(ThemeData themeData) {
_themeData = themeData;
// update UI
notifyListeners();
}
// toggle between dark & light mode
void toggleTheme() {
if (_themeData == lightMode) {
themeData = darkMode;
} else {
themeData = lightMode;
}
}
}
- 수정 전, 잘못된 코드
// toggle between dark & light mode
void toggleTheme() {
if (_themeData == lightMode) {
_themeData = darkMode;
} else {
_themeData = lightMode;
}
}
- 수정 후, 맞는 코드
// toggle between dark & light mode
void toggleTheme() {
if (_themeData == lightMode) {
themeData = darkMode;
} else {
themeData = lightMode;
}
}