-
Equatable의 사용과 Blocflutter 2021. 7. 18. 02:26
플러터에서도 자바와 비슷하게
객체를 == 로 비교할 수 있습니다. 메모리 주소를 비교합니다.
mainBloc1 = MainBloc();
mainBloc2 = MainBloc();
print(mainBloc1==mainBloc2);
따로 한개의 인스턴스만 생성되도록 정의되어 있지 않다면 결과는 false입니다.
객체 비교에 대해서 재정의하려면 비교할 내용을 재정의하면 됩니다.
적용이 필요한 해당 모델 클래스에서
bool operator 를 오버라이드해서 비교로직을 작성하면됩니다.
@override
bool operator ==(Object other) {
return .. 비교하고자 하는 속성 재정의
}
이러한 객체의 세부적인 비교를 편리하게 해주기 위함이 Equatable의 상속입니다.
다트 패키지에서 equatable를 주입한뒤 구현이 가능 해집니다.
사용하고자 하는 모델 클래스에서 import equatable하고,
extends Equatable 할 수 있습니다.패키지 설명)
package:equatable/src/equatable.dart abstract class Equatable
{@template equatable} A base class to facilitate operator == and hashCode overrides.
class Person extends Equatable {
const Person(this.name);
final String name;
@override
List get props => [name];
}
{@endtemplate}-->
A base class to facilitate operator == and hashCode overrides.
연산자 == 및 hashCode 재정의를 용이하게 하는 기본 클래스라고 설명되어있습니다.
사용하기위해서
사용하고자 하는 클래스에서 다음 처럼 오버라이드해서 상황에 맞게 재정의해줍니다.
@override
List<Object?> get props => ['postList'];
[ ] 내부에 객체 비교의 세부사항을 작성할 수 있습니다.
이내용은 Bloc과도 연관이 되는데..
Bloc빌더나 Bloc리스너는 이벤트에 따른 상태가 달라질때마다 UI를 그려줍니다.
기본적으로 상태가 변하지 않으면 UI를 다시 그려주지 않습니다.
블록패턴은 이벤트클래스와 상태클래스, 그리고 그둘을 상속하는 블록클래스로 이뤄집니다.
블록에 이벤트가 들어오고 상태 클래스에서 상태를 바꿔줄때, 상태가 바뀌지 않았다고
판단되면 작동하지 않습니다.
블록의 상태클래스에서 내부적으로 다음과 같이 정의되어 있다고 가정합니다.
class BlocState extends Equatable {
final List<PostData> postList;
final bool? isInitial;
final bool? fetchNext;
final bool? filtering;
BlocState(this.postList);
factory BlocState.getData() {
return PostState(postList);
}
factory BlocState.getNextData() {
블라블라...
return PostState(postList);
}
@override
List<Object> get props => [postList];
}
이럴경우 블록이벤트가 여러번 들어오고, 이벤트가 각기 다르다고 해도
상태클래스의 postList가 변하지 않는다면 BlocBuilder가 작동하지 않고, 재빌드 되지 않습니다.
같은 상태라고 인식하기 때문입니다.
상태클래스에서 이벤트를 수신하고 이전과 달라진 postList가 인식되어야
블록빌더가 작동합니다.
List<Object?> get props => [isInitial, fetchNext, filtering, postList];
이런식으로 여러 멤버 필드 요소를 정의해주는 것도 가능합니다.참조
https://stackoverflow.com/questions/56850693/bloc-is-it-possible-to-yield-2-time-the-same-state
Bloc: is it possible to yield 2 time the same state?
In the login view, if the user taps on the login button without having inserted his credentials, the LoginFailState is yield and the view reacts to it. If he taps again, this LoginFailstate is yield
stackoverflow.com
'flutter' 카테고리의 다른 글
빌드오류 Cannot run with sound null safety because dependencies don't support null safety (0) 2021.08.02 bloc 이벤트 관리를 위한 transformEvents (0) 2021.07.26 bloc 패턴 - flutter_bloc 패키지 사용 (0) 2021.07.16 bloc패턴 -rxdart를 활용한 약식 (0) 2021.07.03 flutter bloc 패턴, rxdart.. (0) 2021.07.03