플러터(Flutter) BLoC 기본 : Counter using Cubit

Flutter-Practice/Tutorials/bloc_counter at main · WOOSHIK-M/Flutter-Practice

프로젝트 시작하기

# make flutter project
>>> flutter create bloc_counter

# open the dir
>>> cd bloc_counter

# open the simulator and run
>>> open -s Simulator && flutter run

main.dart 살펴보기

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }
	...
}

Untitled

어떻게 바꿀까?

├── lib
				// CounterPage() Home으로 페이지 라우트
│   ├── app.dart
│   ├── counter
						// counter 캡슐화
│   │   ├── counter.dart
│   │   ├── cubit
								// 상태 변화 정의 increment(), decrement()
│   │   │   └── counter_cubit.dart
│   │   └── view
								// BlocProvider()로 CounterView()에 CounterCubit() State 연결
│   │       ├── counter_page.dart
								// 상태 변화 전달 context.read<CounterCubit>().increment() ...
│   │       └── counter_view.dart
				// CounterObserver로 감시자 구현
│   ├── counter_observer.dart
				// CounterObserver()를 감시할 위젯인 RunApp에 연결
│   └── main.dart
├── pubspec.lock
├── pubspec.yaml
>>> flutter pub add bloc
>>> flutter pub add flutter_bloc
...

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter
	
	bloc: ^8.0.3
  flutter_bloc: ^8.0.1
  equatable: ^0.2.0
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.0

...

Untitled