Flutter_Bloc라고 패키지도 있는걸로 알지만 이번 코드 예제는 Bloc패턴을 직접 stream으로 구현하였다.
코드는 아래와 같다.
import 'dart:async';
class CounterBloc {
int _counter = 0;
final _streamController = StreamController.broadcast();
StreamSink get _sink => _streamController.sink;
Stream get counter => _streamController.stream;
void increase() {
_sink.add(++_counter);
}
void decrease() {
_sink.add(--_counter);
}
void dispose() {
_streamController.close();
}
int currentNumber() {
return _counter;
}
}
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'package:shw_test/bloc/bloc.dart';
import 'package:shw_test/components/button.dart';
class BlocScreen extends StatelessWidget {
const BlocScreen({super.key});
@override
Widget build(BuildContext context) {
final counterBloc = GetIt.I<CounterBloc>();
return Scaffold(
appBar: AppBar(
title: const Text("Counter"),
backgroundColor: Colors.red[100],
),
body: Center(
child: Column(
children: [
StreamBuilder(
stream: counterBloc.counter,
initialData: counterBloc.currentNumber(),
builder: (context, snapshot) {
return Text(
snapshot.data.toString(),
style: const TextStyle(fontSize: 50),
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Button(
text: "+",
fontSize: 30,
onPressed: () {
counterBloc.increase();
},
),
const SizedBox(
width: 20,
),
Button(
text: "-",
fontSize: 30,
onPressed: () {
counterBloc.decrease();
},
),
],
),
],
),
),
);
}
}
Bloc 패턴에 대해 가볍게 설명을 하고 넘어가자면
Business logic과 UI를 완벽하게 분리하기 위해 나온 패턴이다. 실제로 구현해보면 굉장히 명확하다.
Bloc의 구조는 아래 그림이 완벽하게 설명을 해준다.
UI는 특정 이벤트에 대한 스트림을 구독하고 언제든지 데이터를 받을 수 있도록 준비가 되어 있고 이 상태에서 비즈니스 로직과 상태관련 처리는 bloc 안에서 처리가 된다.
굉장히 명료한 패턴이라 좋은 상태관리라고는 생각하지만 그럼에도 Bloc의 단점이 있다.
내가 생각하는 단점은 아래와 같다.
1. 복잡한 구조 및 많은 boilerplate코드
- 앞전에 올린 Getx에 비하면 코드를 보면 상대적으로 복잡하다는 것을 알수있다.
참조: https://blog.arong.info/flutter/2023/01/10/Flutter-BLoC-%ED%8C%A8%ED%84%B4-1.html
'개발 > Flutter' 카테고리의 다른 글
[상태관리#4]RiverPod (1) | 2023.11.22 |
---|---|
[상태관리#3]Provider (1) | 2023.11.22 |
[상태관리#1] GetX (1) | 2023.11.22 |
[상태관리#0] 상태관리 공부에 앞서.. (0) | 2023.11.21 |
Flutter Package 첫 배포 (1) | 2023.11.04 |