Bloc
(Business Logic Component)은 Flutter 애플리케이션에서 상태 관리를 단순화하고, 비즈니스 로직을 UI와 분리하여 유지보수성을 높이는 데 사용되는 디자인 패턴이자 라이브러리입니다. 이를 통해 상태의 예측 가능성과 테스트 가능성을 높일 수 있습니다.
abstract class CounterEvent {}
class Increment extends CounterEvent {}
class Decrement extends CounterEvent {}
class CounterState {
final int counterValue;
CounterState(this.counterValue);
}
import 'package:bloc/bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0));
Stream<CounterState> mapEventToState(CounterEvent event) async* {
if (event is Increment) {
yield CounterState(state.counterValue + 1);
} else if (event is Decrement) {
yield CounterState(state.counterValue - 1);
}
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_bloc.dart';
import 'counter_event.dart';
import 'counter_state.dart';
void main() => runApp(CounterApp());
class CounterApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (_) => CounterBloc(),
child: CounterPage(),
),
);
}
}
class CounterPage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Center(
child: Text(
'${state.counterValue}',
style: TextStyle(fontSize: 24),
),
);
},
),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => context.read<CounterBloc>().add(Increment()),
),
const SizedBox(height: 4),
FloatingActionButton(
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterBloc>().add(Decrement()),
),
],
),
);
}
}
Bloc 패턴은 다음과 같은 특징과 단점을 가지고 있습니다: