{"id":20878682,"url":"https://github.com/nivisi/ensure_initialized","last_synced_at":"2026-05-01T12:33:13.768Z","repository":{"id":45006103,"uuid":"391926156","full_name":"nivisi/ensure_initialized","owner":"nivisi","description":"⏲ Await until an object initialises before using it.","archived":false,"fork":false,"pushed_at":"2022-11-18T12:15:50.000Z","size":59,"stargazers_count":3,"open_issues_count":5,"forks_count":0,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2025-09-03T09:44:52.830Z","etag":null,"topics":["await","await-async","dart","dart-package","dartlang","ensure","flutter","flutter-package","future","initialization"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/ensure_initialized","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/nivisi.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}},"created_at":"2021-08-02T11:40:08.000Z","updated_at":"2024-04-08T06:17:10.000Z","dependencies_parsed_at":"2023-01-21T17:32:43.863Z","dependency_job_id":null,"html_url":"https://github.com/nivisi/ensure_initialized","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/nivisi/ensure_initialized","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fensure_initialized","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fensure_initialized/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fensure_initialized/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fensure_initialized/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nivisi","download_url":"https://codeload.github.com/nivisi/ensure_initialized/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nivisi%2Fensure_initialized/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32497812,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"online","status_checked_at":"2026-05-01T02:00:05.856Z","response_time":64,"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":["await","await-async","dart","dart-package","dartlang","ensure","flutter","flutter-package","future","initialization"],"created_at":"2024-11-18T07:13:48.354Z","updated_at":"2026-05-01T12:33:13.746Z","avatar_url":"https://github.com/nivisi.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ensure_initialized [![pub version][pub-version-img]][pub-version-url]\n\n[![⚙️ CI][ci-badge-url]][ci-url] [![CodeFactor][code-factor--badge-url]][code-factor-app-url]  [![codecov][codecov-badge-url]][codecov-url]\n\nSometimes objects may perform long initialization or preparation before they can be used. This package allows to await for initialization and ensure that an object is ready to use.\n\n## Usage\n\nAdd the `EnsureInitializedMixin` mixin to a class:\n\n```dart\nclass YourObject with EnsureInitializedMixin {\n  /* Body */\n}\n```\n\nNow you can await for your object initialization:\n\n```dart\nfinal object = YourObject();\n\nawait object.ensureInitialized;\n\nobject.doSomethingAfterItIsReady();\n```\n\nIf your initialization has some output value, you can use `EnsureInitializedResultMixin\u003cT\u003e`:\n\n```dart\nclass YourObjectWithResult with EnsureInitializedResultMixin\u003cint\u003e {\n  /* Body */\n}\n\nfinal objectWithResult = YourObjectWithResult();\n\nfinal result = await objectWithResult.ensureInitialized;\n\nprint(result);\n```\n\nYou can also check whether your object was already initialized by reading the `isInitialized` property:\n\n```dart\nfinal object = YourObject();\n\nprint(object.isInitialized); // false\n\nawait object.init(); // object method that calls `initializedSuccessfully` under the hood\n\nprint(object.isInitialized); // true\n```\n\n### Successful Initialization\n\n`ensureInitialized` will be released after you call either `initializedSuccessfully`. Do it in your heavy initialization method:\n\n```dart\n```dart\nclass YourObject with EnsureInitializedMixin {\n  Future\u003cvoid\u003e init() async {\n    await Future.delayed(const Duration(seconds: 3));\n\n    initializedSuccessfully();\n  }\n}\n```\n\nIf you use `EnsureInitializedResultMixin\u003cT\u003e`, you must pass a value of type `T` to the call:\n\n```dart\ninitializedSuccessfully(5);\n```\n\nThis value will be returned by the `ensureInitialized`:\n\n```dart\nfinal result = await objectWithResult.ensureInitialized;\nprint(result); // prints 5\n```\n\n### Initialization Failure\n\nTo mark that the object has failed to initialize, call `initializedWithError`. It can take a message, an exception and a stacktrace.\n\nNote: you can either use a message or an exception. You'll get an assertion error in debug otherwise.\n\n```dart\nFuture\u003cvoid\u003e init() async {\n  try {\n    await Future.delayed(const Duration(seconds: 3));\n    \n    initializedSuccessfully();\n  } on Exception catch (e, s) {\n    initializedWithError(error: e, stackTrace: s);\n    // Or use message: initializedWithError(message: e.toString(), stackTrace: s);\n  }\n}\n```\n\nSo `ensureInitialized` may throw the specified exception. It could be used as following:\n\n```dart\ntry {\n  await object.ensureInitialized;\n  \n  /* Do the happy path */\n} on Exception catch (e ,s) {\n  /* Log it and do the unhappy path */\n}\n```\n\nNote that calling `initializedWithError` also turns `isInitialized` to true.\n\n### Streams\n\nThere are `whenInitialized` and `whenUninitialized` streams that will raise an event when the object is initialized and uninitialized (later on about the latter):\n\n```dart\nobject.whenInitialized.listen((_) {\n  print('My object was initialized!');\n});\n```\n\nIt can also be used with the result mixin. Then the event will be the result of initialization:\n\n```dart\nobjectWithResult.whenInitialized.listen((result) {\n  print('My object was initialized with $result!');\n});\n```\n\n`whenInitialized` is fired any time `initializedSuccessfully` or `initializedWithError` are called. If the object was initialized with an error, this error will be added to the stream as well.\n\n`whenUninitialized` is fired any time the object is marked as uninitialized.\n\n### Reinitialization\n\nSometimes it is needed to reinit an object. For instance, some service relies on the user service, that relies on what user is currently signed in. You can call `markAsUninitialized` to point that the object is not ready to be used again.\n\n```dart\nclass UserService with EnsureInitializedMixin {\n  Future signIn(credentials) async {\n    /* Do sign in */\n    \n    initializedSuccessfully();\n  }\n  \n  Future signOut() async {\n    /* Do sign out */\n    \n    markAsUninitialized();\n  }\n}\n```\n\nNow, if you call `signOut`, the object will return to its initial state: `isInitialized` will be false and `ensureInitialized` will again be awaitable. It will also fire the `whenUninitialized` event.\n\nSo now we can get notified about this in another service:\n\n```dart\nclass ServiceThatReliesOnUserService with EnsureInitializedMixin {\n  final UserService userService;\n  \n  late final StreamSubscription _onInitializedSubscription;\n  late final StreamSubscription _onUninitializedSubscription;\n  \n  ServiceThatReliesOnUserService(this.userService) {\n    _init();\n  }\n  \n  void _init() {\n    _onInitializedSubscription = userService.whenInitialized.listen(_whenUserServiceInitialized);\n    _onUninitializedSubscription = userService.whenUninitialized.listen(_whenUserServiceUninitialized);\n  }\n  \n  void _whenUserServiceInitialized(_) {\n    /* Do something with userService */\n    initializedSuccessfully();\n  }\n  \n  void _whenUserServiceUninitialized(_) {\n    markAsUninitialized();\n  }\n  \n  void dispose() {\n    _onInitializedSubscription.cancel();\n    _onUninitializedSubscription.cancel();\n  }\n}\n```\n\nWe can build chains with objects that rely on each other. Don'get overwhelmed, though!\n\nAlternatively, you can use a `reinitialize` method that takes a future as a parameter. The object will be marked as uninitialized before the future starts and will be marked as initialized after it completes. \n\n```dart\nFuture reinitMe() {\n  return reinitialize(() =\u003e Future.delayed(const Duration(seconds: 3)));\n}\n```\n\nNote: if any exception occur, `reinitialize` will rethrow it. It also takes a flag `callInitializedWithErrorOnException` that indicates whether to call `initializedWithError` on exception.\n\n\u003c!-- References --\u003e\n[pub-version-img]: https://img.shields.io/badge/pub-v0.1.0-0175c2?logo=dart\n[pub-version-url]: https://pub.dev/packages/ensure_initialized\n\n[code-factor--badge-url]: https://www.codefactor.io/repository/github/nivisi/ensure_initialized/badge\n[code-factor-app-url]: https://www.codefactor.io/repository/github/nivisi/ensure_initialized\n\n[ci-badge-url]: https://github.com/nivisi/ensure_initialized/actions/workflows/ci.yml/badge.svg\n[ci-url]: https://github.com/nivisi/ensure_initialized/actions/workflows/ci.yml\n\n[codecov-badge-url]: https://codecov.io/gh/nivisi/ensure_initialized/branch/develop/graph/badge.svg?token=80NZYCFQH3\n[codecov-url]: https://codecov.io/gh/nivisi/ensure_initialized\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnivisi%2Fensure_initialized","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnivisi%2Fensure_initialized","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnivisi%2Fensure_initialized/lists"}