{"id":16401733,"url":"https://github.com/dev-hwang/flutter_bloc_provider","last_synced_at":"2026-06-22T07:31:31.368Z","repository":{"id":116518095,"uuid":"510644898","full_name":"Dev-hwang/flutter_bloc_provider","owner":"Dev-hwang","description":"[Flutter 2.0] This package provides tools to easily implement the bloc pattern.","archived":false,"fork":false,"pushed_at":"2022-07-05T08:12:19.000Z","size":7,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-23T15:45:57.166Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Dev-hwang.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-05T08:11:20.000Z","updated_at":"2022-08-15T16:07:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"d516a84e-b593-4a78-8fa4-fa794a5ae30f","html_url":"https://github.com/Dev-hwang/flutter_bloc_provider","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/Dev-hwang/flutter_bloc_provider","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dev-hwang%2Fflutter_bloc_provider","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dev-hwang%2Fflutter_bloc_provider/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dev-hwang%2Fflutter_bloc_provider/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dev-hwang%2Fflutter_bloc_provider/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Dev-hwang","download_url":"https://codeload.github.com/Dev-hwang/flutter_bloc_provider/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Dev-hwang%2Fflutter_bloc_provider/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34639704,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-22T02:00:06.391Z","response_time":106,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-11T05:44:01.120Z","updated_at":"2026-06-22T07:31:31.350Z","avatar_url":"https://github.com/Dev-hwang.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"This package provides tools to easily implement the bloc pattern.\n\n## Directory\n\n``` bash\n├── src\n│   ├── bloc.dart\n│   ├── bloc_provider_utils.dart\n│   └── bloc_stream_builder.dart\n└── flutter_bloc_provider.dart\n```\n\n## Getting started\n\nTo use this package, add `flutter_bloc_provider` as a [dependency in your pubspec.yaml file](https://flutter.io/platform-plugins/). For example:\n\n```yaml\ndependencies:\n  flutter_bloc_provider:\n    git:\n      url: https://github.com/Dev-hwang/flutter_bloc_provider.git\n      ref: master\n```\n\n## Usage\n\n이 패키지에는 일반 상태 관리를 위한 BLoC 구현 인터페이스 `Bloc`와 비동기 작업 처리를 목적으로 하는 BLoC 구현 인터페이스 `FetchBloc`를 제공합니다. 구현 방법은 아래와 같습니다.\n\n```dart\n// CounterBloc extends Bloc\u003cBLoC 클래스명, 상태 타입\u003e\nclass CounterBloc extends Bloc\u003cCounterBloc, int\u003e {\n  // super 함수를 사용하여 상태를 초기화한다. 여기서는 상태 타입이 정수형이므로 0으로 초기화했다.\n  CounterBloc() : super(0);\n\n  // initialize 함수는 BLoC 내부 리소스를 초기화하기 위한 용도로 사용된다.\n  @override\n  CounterBloc initialize(BuildContext context) =\u003e this;\n\n  // dispose 함수는 BLoC 내부 리소스를 정리하기 위한 용도로 사용된다.\n  @override\n  void dispose() =\u003e super.dispose();\n\n  void increment() {\n    // state 필드에 접근하여 현재 상태를 가져올 수 있다.\n    if (state \u003e 8) return;\n\n    // setState 함수를 사용하여 현재 상태를 업데이트할 수 있다.\n    setState(state + 1);\n  }\n\n  void decrement() {\n    if (state \u003c 1) return;\n\n    setState(state - 1);\n  }\n}\n```\n\n```dart\n// AsyncBloc extends FetchBloc\u003cBLoC 클래스명, 데이터 타입\u003e\nclass AsyncBloc extends FetchBloc\u003cAsyncBloc, List\u003cString\u003e\u003e {\n  // 내부적으로 FetchResult\u003c테이터 타입\u003e 상태를 만들기 때문에 초기화가 필요없다.\n  // AsyncBloc() : super();\n\n  // initialize 함수는 BLoC 내부 리소스를 초기화하기 위한 용도로 사용된다.\n  @override\n  AsyncBloc initialize(BuildContext context) =\u003e this;\n\n  // dispose 함수는 BLoC 내부 리소스를 정리하기 위한 용도로 사용된다.\n  @override\n  void dispose() =\u003e super.dispose();\n\n  Future\u003cvoid\u003e fetchMenuList() async {\n    // 로딩 이벤트를 추가한다. 검색 중일 때 프로그레스 위젯을 보여주고 싶은 경우 주로 사용한다.\n    addLoadingEvent();\n\n    _getMenuListFromApiServer().then((data) {\n      // 완료 이벤트를 추가한다.\n      addDoneEvent(data);\n\n      // state.data 필드에 접근하여 데이터를 확인할 수 있다.\n      print('data: ${state.data}');\n    }).catchError((error, stackTrace) {\n      // 오류 이벤트를 추가한다.\n      addErrorEvent(error, stackTrace: stackTrace);\n\n      // state.err 및 state.stackTrace 필드에 접근하여 오류 정보를 확인할 수 있다.\n      print('error: ${state.err}');\n      print('stackTrace: ${state.stackTrace}');\n    });\n  }\n\n  // 이 함수는 API 서버에 있다고 가정한다.\n  Future\u003cList\u003cString\u003e\u003e _getMenuListFromApiServer() async {\n    await Future.delayed(const Duration(seconds: 5));\n\n    if (Random().nextInt(2) == 0) {\n      return ['hello', 'bloc', 'provider'];\n    } else {\n      throw Exception('메뉴 정보를 찾을 수 없습니다.');\n    }\n  }\n}\n```\n\n다음으로 `BlocProviderUtils` 클래스를 이용하여 BLoC을 생성하고 초기화해야 합니다.\n\n```dart\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: BlocProviderUtils.create(\n        bloc: CounterBloc(),\n        child: const BlocTestPage(),\n      ),\n    );\n  }\n}\n```\n\n2개 이상의 BLoC을 생성하려면 `MultiProvider` 위젯을 사용하세요.\n\n```dart\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      home: MultiProvider(\n        providers: [\n          BlocProviderUtils.create(bloc: CounterBloc()),\n          BlocProviderUtils.create(bloc: AsyncBloc()),\n        ],\n        child: const BlocTestPage(),\n      ),\n    );\n  }\n}\n```\n\n`context.read\u003cT\u003e()` 함수를 사용하여 상위 위젯에서 생성된 BLoC 및 데이터에 접근할 수 있습니다.\n\n```dart\nclass BlocTestPage extends StatefulWidget {\n  const BlocTestPage({Key? key}) : super(key: key);\n\n  @override\n  _BlocTestPageState createState() =\u003e _BlocTestPageState();\n}\n\nclass _BlocTestPageState extends State\u003cBlocTestPage\u003e {\n  void _onIncrementActionButtonPressed() {\n    context.read\u003cCounterBloc\u003e().increment();\n  }\n\n  void _onDecrementActionButtonPressed() {\n    context.read\u003cCounterBloc\u003e().decrement();\n  }\n\n  void _onFetchMenuListActionButtonPressed() {\n    context.read\u003cAsyncBloc\u003e().fetchMenuList();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: const Text('Hello, Bloc Provider'),\n      ),\n      body: _buildContentView(),\n      floatingActionButton: Column(\n        mainAxisAlignment: MainAxisAlignment.end,\n        crossAxisAlignment: CrossAxisAlignment.end,\n        children: [\n          FloatingActionButton(\n            child: const Icon(Icons.add),\n            onPressed: _onIncrementActionButtonPressed,\n          ),\n          const SizedBox(height: 8.0),\n          FloatingActionButton(\n            child: const Icon(Icons.remove),\n            onPressed: _onDecrementActionButtonPressed,\n          ),\n          const SizedBox(height: 8.0),\n          FloatingActionButton(\n            child: const Icon(Icons.request_page),\n            onPressed: _onFetchMenuListActionButtonPressed,\n          ),\n        ],\n      ),\n    );\n  }\n}\n```\n\n마지막으로 `BlocStreamBuilder\u003cB, S\u003e` 위젯을 사용하여 BLoC 상태 변화를 구독하고 UI를 업데이트하세요.\n\n```dart\nWidget _buildContentView() {\n  return Center(\n    child: Column(\n      mainAxisAlignment: MainAxisAlignment.center,\n      children: [\n        // CounterBloc\n        BlocStreamBuilder\u003cCounterBloc, int\u003e(\n          listener: (context, state) {\n            // BLoC 상태가 변경되거나 업데이트되면 호출됩니다.\n            // 주로 상태에 따라 팝업이나 토스트 메시지를 출력할 때 사용됩니다.\n            print('CounterBloc state: $state');\n          },\n          listenWhen: (widgetState, blocState) {\n            // listener 호출 조건을 정의할 수 있습니다.\n            return blocState != 5;\n          },\n          builder: (context, state) {\n            return Text('count: $state');\n          },\n        ),\n\n        // AsyncBloc\n        BlocStreamBuilder\u003cAsyncBloc, FetchResult\u003cList\u003cString\u003e\u003e\u003e(\n          buildWhen: (widgetState, blocState) {\n            // builder 호출 조건을 정의할 수 있습니다.\n            return widgetState.status != blocState.status;\n          },\n          builder: (context, state) {\n            if (state.status == FetchStatus.error)\n              return const Text('오류가 발생하여 메뉴 정보를 확인할 수 없습니다.');\n\n            if (state.status == FetchStatus.loading)\n              return const CircularProgressIndicator();\n\n            return Text('menuList: ${state.data.toString()}');\n          },\n        ),\n      ],\n    ),\n  );\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-hwang%2Fflutter_bloc_provider","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdev-hwang%2Fflutter_bloc_provider","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-hwang%2Fflutter_bloc_provider/lists"}