반응형

1. 사용 목적

 

  1) 특정한 값을 비동기 방식으로 결과를 받아서 처리할 때 사용한다.

  2) 여러 곳으로 결과를 알릴 때 사용한다.

 

 

2. StreamController

 

A controller with the stream it controls.
This controller allows sending data, error and done events on its stream.
This class can be used to create a simple stream that others can listen on, and to push events to that stream.
It's possible to check whether the stream is paused or not, and whether it has subscribers or not, as well as getting a callback when either of these change.

제어하는 스트림이 있는 컨트롤러입니다.
이 컨트롤러를 사용하면 스트림 에서 데이터, 오류 및 완료 이벤트를 보낼 수 있습니다 .
이 클래스를 사용하면 다른 사람이 수신할 수 있는 간단한 스트림을 만들고 해당 스트림에 이벤트를 푸시할 수 있습니다.
스트림이 일시 중지되었는지 여부, 구독자가 있는지 여부를 확인할 수 있을 뿐만 아니라 이러한 변경이 있을 때 콜백을 받을 수도 있습니다.

- 출처 : https://api.flutter.dev/flutter/dart-async/StreamController-class.html

 

StreamController class - dart:async library - Dart API

A controller with the stream it controls. This controller allows sending data, error and done events on its stream. This class can be used to create a simple stream that others can listen on, and to push events to that stream. It's possible to check whethe

api.flutter.dev

 

3. 예제(Example)

 

1) controller.dart

mport 'dart:async';

class Controller {

      // instance
     static Controller? controller;

     // 상태 broad cast stream
     StreamController stateStreamController = StreamController();

     /// instance 반환
     Controller? getInstance() {
         controller ??= Controller();
         return controller ;
     }

     /// 초기화
     void init(){
          getInstance();
     }

     /// 상태 체크 StreamController 반환
     StreamController? getStreamController() {

           // cloase 하지 않으면 이전에 사용한 stream 으로 인해서
           // fluuter tream has already been listened to 에러 발생
          stateStreamController.close();

          stateStreamController = StreamController();

          return stateStreamController;

     }

     /// BoradCast 전송
     void sendBroadCast(){
          // 상태 값 borad cast 알림
          stateStreamController.add("state");
     }
}

 

 

2) main.dart

        Controller? controller = Controller().getInstance();
        Stream? stateStream = controller?.getStreamController()?.stream;

        stateStream?.listen((event) {
            print("$event");
          },
          onDone: () {
            print('Done');
          },
          onError: (error) {
            print(error);
          },
        );

 

 

4. 설명

  controller.dart 에서 StreamController 객체를 생성하여

 

controller.dart

 

  stream 객체를 얻어와서

 

main.dart

 

   stateStream?. listen을 아래와 같이 구현 후,

 

main.dart

 

   StreamController 객체인 stateStreamController의 메서드 add를 추가하면,

 

controller.dart

 

   event의 값으로 데이터가 넘어온다.

 

main.dart

 

반응형

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

[Flutter] Http POST (json)  (0) 2024.03.17
[Flutter] CRC16 From Dart  (0) 2024.03.10
[Flutter] Flutter 시작하기 & 후기  (0) 2021.03.28