sync86 블로그

[Dart/Flutter] BLoC Concepts - 훑어보기 (2) 본문

개발기

[Dart/Flutter] BLoC Concepts - 훑어보기 (2)

sync86 2024. 10. 14. 07:00
728x90

 

아래의 링크의 BLoC  "시작하기 가이드" 문서 내용 중 onChnage(Change<int> change)의 내용이 나온다. 이 코드도 테스트를 해보았다. 테스트 내용은 이전 내용과 동일하다.

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);

  @override
  void onChange(Change<int> change) {
    super.onChange(change);
    print(change);
  }
}

void main() {
  final cubit = CounterCubit();
  cubit.increment();
}

 

이전과 달라진 점은 아래와 같다.

  • CounterCubit 클래스에 onChnage(Change<int> change) 함수 추가
  • main() 함수에 print('$state') 호출 삭제

문서의 내용대로 전달된 Change 객체에는 currentState와 nextState 가진다. 이름에서 풍기는 뉘양스가 현재의 state와 변경된 state인 것 같다. currentState는 변경 이전의 값을 의미하는 것 같고, nextState는 변경된 이후 현재의 값을 의미한다. 의미상으로 보면 nextState가 현재의 값이란 의미가 아닐까 생각든다.

 

실행 결과는 아래와 같다.

$ dart ./lib/main.dart
Change { currentState: 0, nextState: 1 }

 

이번에도 여러번 호출해 보았다.

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);

  @override
  void onChange(Change<int> change) {
    super.onChange(change);
    print(change);
  }
}

void main() {
  final cubit = CounterCubit();
  cubit.increment();
  cubit.increment();
  cubit.increment();
  cubit.increment();
  cubit.increment();
}

 

여러번 호출 했을 때의 실행 결과는 아래와 같다.

dart ./lib/main.dart
Change { currentState: 0, nextState: 1 }
Change { currentState: 1, nextState: 2 }
Change { currentState: 2, nextState: 3 }
Change { currentState: 3, nextState: 4 }
Change { currentState: 4, nextState: 5 }

 

이전 글에서도 테스트했었던 조건을 다시 한번 더 테스트 해보았다.

  • state 값이 9이하이면 증가, 9를 초과하면 9 할당
class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state < 9 ? state + 1 : 9);

  @override
  void onChange(Change<int> change) {
    super.onChange(change);
    print(change);
  }
}

void main() {
  final cubit = CounterCubit();
  cubit.increment(); // 0 -> 1
  cubit.increment(); // 1 -> 2
  cubit.increment(); // 2 -> 3
  cubit.increment(); // 3 -> 4
  cubit.increment(); // 4 -> 5
  cubit.increment(); // 5 -> 6
  cubit.increment(); // 6 -> 7
  cubit.increment(); // 7 -> 8
  cubit.increment(); // 8 -> 9
  cubit.increment(); // 9 -> 9
  cubit.increment(); // 9 -> 9
}


마찬가지로 예상되는 결과 값을 주석으로 코드에 작성하였다.

dart ./lib/main.dart
Change { currentState: 0, nextState: 1 }
Change { currentState: 1, nextState: 2 }
Change { currentState: 2, nextState: 3 }
Change { currentState: 3, nextState: 4 }
Change { currentState: 4, nextState: 5 }
Change { currentState: 5, nextState: 6 }
Change { currentState: 6, nextState: 7 }
Change { currentState: 7, nextState: 8 }
Change { currentState: 8, nextState: 9 }

 

어라? 예상과는 좀 다르다.

 

onChnage(Change<int> change)는 변경이 있어야만 호출되는 것일까? 아직 "시작하기 가이드"에서는 특별히 언급이 없었다. 나중에 이 부분에 대해서 언급이 되는지 확인하면서 문서를 읽어나가야 겠다.

728x90