BLOC

Bussiness Logic Component

비즈니스 로직과 ui를 구분 짓고 필요에 따라 원하는 부분만 데이터 처리

실 사용 예제

버튼 클릭시 증감

1. Stateful version

ui widget - 버튼 클릭시 증감

//stateless widget으로 count를 보내 화면에 그려줌
body: CountViewStateless(count: count),
floatingActionButton: Row(
  mainAxisAlignment: MainAxisAlignment.end,
  children: [
    IconButton(
      icon: Icon(Icons.add),
      onPressed: () {
        setState(() {
          count++;
        });
      },
    ),
    IconButton(
      icon: Icon(Icons.remove),
      onPressed: () {
        setState(() {
          count--;
        });
      },
    ),
  ],
),

view - 결과 출력

import 'package:flutter/material.dart';

class CountViewStateless extends StatelessWidget {
  int count;
  CountViewStateless({Key key, this.count}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("CountViewStateless Build !!");
    return Center(
        child: Text(
      count.toString(),
      style: TextStyle(fontSize: 80),
    ));
  }
}

2. bloc pattern

ui widget - 값을 변경시키는 이벤트 발생

// 전역변수로 bloc 생성
CountBloc countBloc;

class _BlocDisplayWidgetState extends State<BlocDisplayWidget> {
  @override
  void initState() {
    super.initState();
        // bloc
    countBloc = CountBloc();
  }

  @override
  void dispose() {
    super.dispose();
        // bloc 종료
    countBloc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("bloc 패턴"),
      ),
      body: CountView(),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
                            // add는 이벤트를 등록한다는 의미
                            // 숫자를 더하거나 빼는 로직이 현재파일에는 존재하지 않음
              countBloc.countEventBloc.countEventSink.add(CountEvent.ADD_EVENT);
            },
          ),
          IconButton(
            icon: Icon(Icons.remove),
            onPressed: () {
              countBloc.countEventBloc.countEventSink
                  .add(CountEvent.SUBTRACT_EVENT);
            },
          ),
        ],
      ),
    );
  }
}

count_bloc - 비즈니스 로직 처리

import 'dart:async';

//bloc
class CountBloc {
  CountEventBloc countEventBloc = CountEventBloc();
  int _count = 0;
    // broadcast를 넣어주면 여러군데에서 구독 가능
  final StreamController<int> _countSubject = StreamController<int>.broadcast();

    // count는 _countSubject.stream를 구독하고 있는 모든 widget에게 변경된 상태값을 전달
  Stream<int> get count => _countSubject.stream;

    // 생성자
  CountBloc() {
        // countEventBloc의 _countEventSubject을 구독
    countEventBloc._countEventSubject.stream.listen(_countEventListen);
  }
    // 생성자에서 변화를 감지하여 listen으로 리턴 받은 것
    // 인자값 event에 해당하는 것은 enum에 등록된 이벤트 
  _countEventListen(CountEvent event) {
        // 비즈니스 로직 부분
    switch (event) {
      case CountEvent.ADD_EVENT:
        _count++;
        break;
      case CountEvent.SUBTRACT_EVENT:
        _count--;
        break;
    }
        // 결과값인 _count를 sink에 add로  넣어줌 
    _countSubject.sink.add(_count);
  }

  dispose() {
    _countSubject.close();
    countEventBloc.dispose();
  }
}

// event 
class CountEventBloc {
  final StreamController<CountEvent> _countEventSubject =
      StreamController<CountEvent>();
    // event 값이 sink로 들어오면 _countEventSubject를 통해 구독자에게 알려줌  
  Sink<CountEvent> get countEventSink => _countEventSubject.sink;

  dispose() {
    _countEventSubject.close();
  }
}

// event에 해당하는 enum
enum CountEvent { ADD_EVENT, SUBTRACT_EVENT }

count_view 결과값 받아오는 곳

StreamBuilder(
    // stream을 리스닝 
  stream: countBloc.count, // Stream<int> get count => _countSubject.stream; 구독
  initialData: 0,
    // snapshot으로 값이 들어옴
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) { 
    if (snapshot.hasData) {
      return Text(
        snapshot.data.toString(),
        style: TextStyle(fontSize: 80),
      );
    }
    return CircularProgressIndicator();
  },
),

3. Skip event bloc pattern

ui 위와 다르게 바로 이벤트 호출함

class _BlocDisplayWidgetState extends State<BlocDisplayWidget> {
  @override
  void initState() {
    super.initState();
    countBloc = CountBloc();
  }

  @override
  void dispose() {
    super.dispose();
    countBloc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("bloc 패턴"),
      ),
      body: CountView(),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
                            // 이벤트 호출
              countBloc.add();
            },
          ),
          IconButton(
            icon: Icon(Icons.remove),
            onPressed: () {
              countBloc.subtract();
            },
          ),
        ],
      ),
    );
  }
}

count_bloc - skip event 비즈니스 로직 처리

import 'dart:async';

class CountBloc {
  int _count = 0;
  final StreamController<int> _countSubject = StreamController<int>.broadcast();
  Stream<int> get count => _countSubject.stream;

  add() {
    _count++;
    _countSubject.sink.add(_count);
  }

  subtract() {
    _count--;
    _countSubject.sink.add(_count);
  }

  dispose() {
    _countSubject.close();
  }
}

참고

https://www.youtube.com/watch?v=AY6i0a4BM7o 

 

728x90

Rendering 조건

stateful widget에서 rebuild를 초래하는 것은 state 클래스이며 이를 통해 스크린을 랜더링함

  • child 위젯의 생성자를 통해서 새로운 데이터가 전달될때
  • internal state가 바뀔때

왜 StatefulWidget 클래스는 두개로 이루어져 있을까?

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Charactor card',
      home: MyPage(),
    );
  }
}

먼저, StatefulWidget클래스는 아래와 같이 widget 클래스를 상속하고 있습니다.

abstract class StatefulWidget extends Widget {
  const StatefulWidget({ Key? key }) : super(key: key);
  @override
  StatefulElement createElement() => StatefulElement(this);
  @protected
  @factory
  State createState(); // ignore: no_logic_in_create_state, this is the original sin
}

widget클래스는 기본적으로 immutable 즉, 한번 생성되면 state가 변하지 않습니다.

그렇기에 StatefulWidget은 StatelessWiget처럼 immutable한 위젯입니다.

그러나 반드시 statefulwidget은 state의 변화를 반영해야 합니다.

이런 문제를 해결하기 위해 두개의 클래스로 나눠 StatefulWidget인 MyApp 위젯은 immutable한 특징을 유지하고 _MyAppState 클래스는 mutable한 속성을 대신하게 만든 것입니다.

어떻게 두개의 클래스를 연결시킬 수 있을까 - 1

먼저, state 클래스의 코드입니다.

@optionalTypeArgs
abstract class State<T extends StatefulWidget> with Diagnosticable {
  ...
}

State클래스는 제네릭 타입으로 어떤 타입이 오든지 StatefulWidget을 상속받게 하고 있습니다.

_MyAppState 클래스는 state클래스를 상속 받았고 이제, _MyAppState 클래스는 state 타입이 되었습니다.

class _MyAppState extends State<MyApp>{...}

그리고 상속 받은 state클래스의 제네릭 타입을 MyApp 클래스로 지정해준다면 이 state 클래스는 오직 MyApp타입만을 가질 수 있게 됩니다.

이를 통해 _MyAppState 클래스가 StatefulWidget인 MyApp 위젯에 연결된다고 flutter에 알려줄수 있습니다.

왜 state 클래스는 제네릭 타입을 가지게 되었을까

제네릭 타입의 장점인 코드의 재사용성, 안정성 때문입니다.

check box

Checkbox(value: false, onChanged: (value){})

check box source code

// StatefulWidget을 상속 받고 있음
class Checkbox extends StatefulWidget {
    const Checkbox({...})
    ...
}
// 상속받은 state의 제네릭 타입은 checkbox 타입으로 되어있음
class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin, ToggleableStateMixin {...}

즉, state클래스를 제네릭 타입으로 만들어서 필요한 타입을 편하게 지정하고 그 외의 타입을 전달 받지 못하도록 안전장치를 해둔 것

어떻게 두개의 클래스를 연결시킬 수 있을까 - 2

이제, _MyAppState 클래스를 createState Method를 통해 MyApp 위젯 내에서 불러와야합니다.

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Charactor card',
      home: MyPage(),
    );
  }
}

createState Method는 state 타입으로 지정되어 있고 제네릭 타입으로 StatefulWidget이 지정되어 있습니다.

즉, createState Method는 반드시 state 타입의 객체를 리턴해야 하는데 결국, StatefulWidget타입만이 올 수있는 객체여야 하며 이 객체는 _MyAppState 클래스에 근거하여 만들어진 것입니다.

StatefulWidget과 StatelessWidget 차이

createState Method는 StatefulWidget이 생성될 때 마다 호출되는 메서드입니다.

StatelessWidget은 build method에서 생성한 객체를 바로 반환하지만 StatefulWidget은 이 createState Method에서 생성한 객체를 반환합니다.

이제 어떻게 State를 변화시켜 랜더링 시킬까

state를 변화시킬려면 반드시 build 메서드를 호출해서 위젯을 rebuild하는 방법 뿐입니다.

단순히 버튼을 누른다고 build메서드를 호출할 수는 없습니다.

TextButton(
  onPressed: () {
      counter++;
  },
  child: Icon(Icons.add),
)

그래서, flutter는 우리 대신 build 메서드를 호출해 줄 수 있는 setState 메서드를 가지고 있습니다.

setState의 역할은 두가지 입니다.

  • 매개 변수로 전달된 함수 호출
  • build 메서드 호출
TextButton(
  onPressed: () {
    setState((){
      counter++;
    })
  },
  child: Icon(Icons.add),
)

정리

flutter는 widget tree를 기반으로 element tree를 생성합니다.

MyApp Stateful widget을 만나면 관련된 MyApp Stateful element를 추가하지만 createState 메서드를 호출해서 MyApp Stateful element와 연결된 MyAppState 객체도 생성합니다.

그런데 이 객체는 MyApp Stateful widget과 간접적으로만 연결되어 있습니다.

여기서 특이점은 MyApp Stateful element는 위젯 관련 중요 정보들을 가지고 있지만, 메모리 상에서 어디에도 종속되지 않는 독립된 객체로서 MyAppState 객체에 대한 정보도 가지게 되는 것입니다.

이제 setState메서드가 호출되고 build 메서드로 인해서 state객체가 rebuild 되면서 새로운 state를 반영한 새로운 MyApp Stateful widget이 rebuild 됩니다. 그러면 MyApp Stateful element에 연결되어 있는 MyAppState객체에 새로운 state가 저장이 되고 이제 MyAppState객체는 새롭게 rebuild된 MyAppStateful widget을 가리키게 됩니다.

왜 MyAppState 객체는 MyAppStateful widget처럼 widget tree상에서 매번 rebuild되지 않는 것일까?

비용문제

state가 변한 state 객체를 비용이 싼 Stateful widget으로 만들어서 계속 rebuild하고 MyAppState 객체는 element tree에서 mutable하게 존재하면서 필요할때마다 새로운 state를 저장함과 동시에 새롭게 rebuild된 Stateful Widget과의 링크만을 업데이트 해줍니다.

참고

https://www.youtube.com/watch?v=OvWrOKMqSG0&list=PLQt_pzi-LLfoOpp3b-pnnLXgYpiFEftLB&index=2 

 

728x90

'Study > Flutter' 카테고리의 다른 글

[Flutter] Factory 패턴  (0) 2021.07.13
[Flutter] Provider pattern (bloc -> provider )  (0) 2021.06.16
[UI초급] Container, materialApp, Scaffold  (0) 2021.06.07

+ Recent posts