getX controller랑 비슷 but cubit과 bloc은 상태 타입을 하나만 설정!
class CountCubit extends Cubit<int> {
//<int>에 하나의 상태만 등록됨 but int 대신 class를 넣고
//class 내에 여러 상태를 넣어서 사용도 가능
CountCubit() : super(0);
//extends Cubit 부모값에 super()안에 초기설정값을 넣어야 함
//여기선 int로 설정해줬기 때문에 초기값을 숫자 '0'으로
void addCount() {
emit(state + 1);
// int의 초기값 super(0)의 '0'값이 state로
//그리고 emit 함수에 값을 넣어줬을 때, state에 변경된 값 적용
//+emit: 상태 변경할 때 쓰는 함수
}
void substractCount() {
emit(state - 1);
}
}
class CountBloc extends Bloc<CountEvent, int> {
CountBloc() : super(0) {
on<AddCountEvent>((event, emit) {
//event 안에서 CountEvent 안에 있던
// AddCountEvent 랑 SubstracCountEvent 두 개가 넘어오는데
// 제네릭으로 <AddCountEvent> 해줘서 이것만 넘어옴
emit(state + 1);
});
on<SubstracCountEvent>(
(event, emit) {
emit(state - 1);
},
);
}
}
//event
abstract class CountEvent extends Equatable {}
class AddCountEvent extends CountEvent {
List<Object?> get props => [];
}
class SubstracCountEvent extends CountEvent {
List<Object?> get props => [];
}
//state
class CountState extends Equtable{
final int count;
const CountState(this.count);
List<Object?> get props => [count];
}
// 화면
body: Center(
child: BlocBuilder<CountBloc, int>(
builder: (context, state) {
return Text(
state.toString(),
style: TextStyle(fontSize: 80),
);
},
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
context.read<CountBloc>().add(AddCountEvent());
},
child: Icon(Icons.add),
),
const SizedBox(width: 30),
FloatingActionButton(
onPressed: () {
context.read<CountBloc>().add(SubstracCountEvent());
},
backgroundColor: Colors.red,
child: Text('-'),
),
📍 터미널에서 flutter pub add get bloc flutter_block equatable 이라고 하면 자동으로 import?되는 거 처음 앎
📍 실제 라이브 코딩하는 거 보는 거 재밌당
ElevatedButton(
onPressed: () {
Get.to(
BlocProvider(
create: (context) => CountCubit(), child: CubitHome()),
//BlocProvider(create: (context) => CountCubit(0)
//여기에서 초기값을 넣어줘도 됨
//+ 이렇게 하려면 CountCubit 클래스에서
// CountCubit(super.initialState);로
❓ 다른 데이터로부터 초기화를 해주고 가져오고 싶을 떄
// Or CountCubit 클래스에서 super(0) 여기도 ㅇㅇ
duration: Duration.zero,
);
},
📍 cubit에 초기값을 넣어줄 떄도 상황에 따라 다른 방법이 있다
'꼭 이게 답이야'가 아니군
class CountCubit extends Cubit<int> {
CountCubit() : super(0);
📌오늘 강의에 나온 getx cubit bloc 예제로 만든 거 혼자 만들 수 있을까? 낼 해봐야게따