{"id":27168212,"url":"https://github.com/michaelpiper/result-library-dart","last_synced_at":"2025-04-09T05:29:35.713Z","repository":{"id":282545954,"uuid":"948954810","full_name":"michaelpiper/result-library-dart","owner":"michaelpiper","description":"A robust Result type implementation for handling success and error states in Flutter and Dart applications.","archived":false,"fork":false,"pushed_at":"2025-03-15T10:53:16.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-15T11:17:26.448Z","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/michaelpiper.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":"2025-03-15T10:46:26.000Z","updated_at":"2025-03-15T10:53:20.000Z","dependencies_parsed_at":"2025-03-15T11:17:27.794Z","dependency_job_id":"ca9d49a8-fdc9-48ea-815b-9ec8b54af82c","html_url":"https://github.com/michaelpiper/result-library-dart","commit_stats":null,"previous_names":["michaelpiper/result-library-dart"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library-dart","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library-dart/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library-dart/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michaelpiper%2Fresult-library-dart/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michaelpiper","download_url":"https://codeload.github.com/michaelpiper/result-library-dart/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247985830,"owners_count":21028765,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":"2025-04-09T05:29:35.154Z","updated_at":"2025-04-09T05:29:35.702Z","avatar_url":"https://github.com/michaelpiper.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Author\n\nThis package was created by **Michael Piper**. You can reach out via email at [pipermichael@aol.com](mailto:pipermichael@aol.com)\n\n# Result Library\n\n[![pub package](https://img.shields.io/pub/v/result_library.svg)](https://pub.dev/packages/result_library)\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n\nA robust `Result\u003cT, E\u003e` type implementation for handling success and error states in Flutter and Dart applications. Inspired by functional programming paradigms, this library provides a clean and type-safe way to manage operations that may succeed or fail.\n\n## Why Use This Package?\n\n- **Type-Safe Error Handling**: Avoid runtime errors by explicitly handling success (`Ok`) and failure (`Err`) cases.\n- **Functional Programming Style**: Encourages immutability and composability, making your code more predictable and easier to debug.\n- **Flutter-Friendly**: Designed with Flutter in mind, this library integrates seamlessly into your app's architecture.\n- **Comprehensive API**: Includes methods like `isOk`, `isErr`, `unwrap`, and `unwrapErr` for flexible error handling.\n\n## Installation\n\nAdd the following to your `pubspec.yaml`:\n\n```yaml\ndependencies:\n  result_library: ^1.0.0\n```\n\nThen run:\n\n```bash\nflutter pub get\n```\n\n## Usage\n\n### Basic Example\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nvoid main() {\n  // Success case\n  var success = ResultBuilder.ok\u003cint, String\u003e(42);\n  print(success.isOk()); // true\n  print(success.unwrap()); // 42\n\n  // Error case\n  var failure = ResultBuilder.err\u003cint, String\u003e('Something went wrong');\n  print(failure.isErr()); // true\n  print(failure.unwrapErr()); // Something went wrong\n}\n```\n\n### Advanced Example\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nResult\u003cint, String\u003e divide(int a, int b) {\n  if (b == 0) {\n    return Err('Division by zero');\n  }\n  return Ok(a ~/ b);\n}\n\nvoid main() {\n  var result = divide(10, 2);\n\n  if (result.isOk()) {\n    print('Result: ${result.unwrap()}'); // Result: 5\n  } else {\n    print('Error: ${result.unwrapErr()}'); // Handles division by zero\n  }\n}\n```\n\nTo expand the use cases of the `result_library` package, we can cover a variety of scenarios such as API calls, file operations, and more complex error handling. Below are additional examples that demonstrate how the `Result\u003cT, E\u003e` type can be used in different contexts.\n\n---\n\n### 1. **API Call Example**\nThis example demonstrates how to handle API responses using the `Result\u003cT, E\u003e` type. It simulates fetching data from an API and handling success or failure cases.\n\n```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'package:result_library/result_library.dart';\n\nFuture\u003cResult\u003cMap\u003cString, dynamic\u003e, String\u003e\u003e fetchUserData(String userId) async {\n  final url = Uri.parse('https://api.example.com/users/$userId');\n\n  try {\n    final response = await http.get(url);\n\n    if (response.statusCode == 200) {\n      // Parse the JSON response\n      final Map\u003cString, dynamic\u003e data = json.decode(response.body);\n      return Ok(data);\n    } else {\n      // Handle HTTP errors\n      return Err('Failed to fetch user data: ${response.statusCode}');\n    }\n  } catch (e) {\n    // Handle network or parsing errors\n    return Err('An error occurred: $e');\n  }\n}\n\nvoid main() async {\n  final result = await fetchUserData('123');\n\n  if (result.isOk()) {\n    print('User Data: ${result.unwrap()}');\n  } else {\n    print('Error: ${result.unwrapErr()}');\n  }\n}\n```\n\n**Explanation**:\n- The `fetchUserData` function returns a `Result\u003cMap\u003cString, dynamic\u003e, String\u003e`.\n- If the API call succeeds, it returns an `Ok` with the parsed JSON data.\n- If the API call fails (e.g., due to network issues or invalid status code), it returns an `Err` with an error message.\n\n---\n\n### 2. **File Operations Example**\nThis example demonstrates how to handle file reading operations using the `Result\u003cT, E\u003e` type.\n\n```dart\nimport 'dart:io';\nimport 'package:result_library/result_library.dart';\n\nResult\u003cString, String\u003e readFile(String filePath) {\n  try {\n    final file = File(filePath);\n    if (!file.existsSync()) {\n      return Err('File not found: $filePath');\n    }\n\n    final content = file.readAsStringSync();\n    return Ok(content);\n  } catch (e) {\n    return Err('Error reading file: $e');\n  }\n}\n\nvoid main() {\n  final result = readFile('example.txt');\n\n  if (result.isOk()) {\n    print('File Content: ${result.unwrap()}');\n  } else {\n    print('Error: ${result.unwrapErr()}');\n  }\n}\n```\n\n**Explanation**:\n- The `readFile` function attempts to read the contents of a file.\n- If the file exists and is successfully read, it returns an `Ok` with the file content.\n- If the file does not exist or an error occurs, it returns an `Err` with an appropriate error message.\n\n---\n\n### 3. **Validation Example**\nThis example demonstrates how to validate user input using the `Result\u003cT, E\u003e` type.\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nResult\u003cint, String\u003e validateAge(String input) {\n  final age = int.tryParse(input);\n\n  if (age == null) {\n    return Err('Invalid input: Age must be a number');\n  }\n\n  if (age \u003c 0 || age \u003e 120) {\n    return Err('Invalid age: Must be between 0 and 120');\n  }\n\n  return Ok(age);\n}\n\nvoid main() {\n  final inputs = ['25', '-5', 'abc'];\n\n  for (final input in inputs) {\n    final result = validateAge(input);\n\n    if (result.isOk()) {\n      print('Valid age: ${result.unwrap()}');\n    } else {\n      print('Error: ${result.unwrapErr()}');\n    }\n  }\n}\n```\n\n**Explanation**:\n- The `validateAge` function checks if the input is a valid integer and falls within a reasonable range.\n- If the input is valid, it returns an `Ok` with the parsed age.\n- If the input is invalid, it returns an `Err` with an appropriate error message.\n\n---\n\n### 4. **Chained Operations Example**\nThis example demonstrates how to chain multiple operations using the `Result\u003cT, E\u003e` type.\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nResult\u003cint, String\u003e calculateSquare(int value) {\n  if (value \u003c 0) {\n    return Err('Value cannot be negative');\n  }\n  return Ok(value * value);\n}\n\nResult\u003cint, String\u003e addTen(int value) {\n  return Ok(value + 10);\n}\n\nvoid main() {\n  final input = 5;\n\n  final result = calculateSquare(input)\n      .map((square) =\u003e addTen(square).unwrap());\n\n  if (result.isOk()) {\n    print('Final Result: ${result.unwrap()}');\n  } else {\n    print('Error: ${result.unwrapErr()}');\n  }\n}\n```\n\n**Explanation**:\n- The `calculateSquare` function squares the input value if it's non-negative.\n- The `addTen` function adds 10 to the input value.\n- The operations are chained using `.map`, which allows you to transform the success value while propagating errors.\n\n---\n\n### 5. **Complex Error Handling Example**\nThis example demonstrates how to handle multiple error types and provide detailed error messages.\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nenum DivisionError { divisionByZero, invalidInput }\n\nResult\u003cint, DivisionError\u003e safeDivide(int a, int b) {\n  if (b == 0) {\n    return Err(DivisionError.divisionByZero);\n  }\n  if (a \u003c 0 || b \u003c 0) {\n    return Err(DivisionError.invalidInput);\n  }\n  return Ok(a ~/ b);\n}\n\nvoid main() {\n  final result = safeDivide(10, 0);\n\n  if (result.isOk()) {\n    print('Result: ${result.unwrap()}');\n  } else {\n    switch (result.unwrapErr()) {\n      case DivisionError.divisionByZero:\n        print('Error: Division by zero');\n        break;\n      case DivisionError.invalidInput:\n        print('Error: Invalid input');\n        break;\n    }\n  }\n}\n```\n\n**Explanation**:\n- The `safeDivide` function handles two types of errors: division by zero and invalid input.\n- The error type is represented as an `enum`, making it easy to handle different error cases.\n\n---\n\n### 6. **Combining Multiple Results**\nThis example demonstrates how to combine multiple `Result` values into a single result.\n\n```dart\nimport 'package:result_library/result_library.dart';\n\nResult\u003cint, String\u003e multiply(int a, int b) {\n  if (a \u003c 0 || b \u003c 0) {\n    return Err('Inputs must be non-negative');\n  }\n  return Ok(a * b);\n}\n\nResult\u003cint, String\u003e add(int a, int b) {\n  return Ok(a + b);\n}\n\nvoid main() {\n  final result1 = multiply(3, 4);\n  final result2 = add(5, 7);\n\n  if (result1.isOk() \u0026\u0026 result2.isOk()) {\n    final combinedResult = result1.unwrap() + result2.unwrap();\n    print('Combined Result: $combinedResult');\n  } else {\n    print('Error: ${result1.isErr() ? result1.unwrapErr() : result2.unwrapErr()}');\n  }\n}\n```\n\n**Explanation**:\n- Two operations (`multiply` and `add`) are performed independently.\n- Their results are combined only if both succeed. Otherwise, the first error encountered is reported.\n\n---\n\n### Conclusion\n\nThese examples showcase the versatility of the `Result\u003cT, E\u003e` type in handling various scenarios such as API calls, file operations, validation, chaining, and error handling. By using this pattern, you can write robust, type-safe, and maintainable Dart code that gracefully handles success and failure cases.\n\nYou can include these examples in your package's documentation or `README.md` to help users understand how to use the library effectively.\n\n## API Reference\n\n- `Result\u003cT, E\u003e`: Represents either a successful value (`Ok`) or an error (`Err`).\n- `isOk()`: Returns `true` if the result is `Ok`.\n- `isErr()`: Returns `true` if the result is `Err`.\n- `ok()`: Retrieves the success value. Throws an exception if called on an `Err`.\n- `err()`: Retrieves the error value. Throws an exception if called on an `Ok`.\n- `unwrap()`: Unwraps the success value. Throws an exception if the result is `Err`.\n- `unwrapErr()`: Unwraps the error value. Throws an exception if the result is `Ok`.\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request.\n\n## License\n\nMIT License\n---\n\n# result-library-dart\n# result-library-dart\n# result-library-dart\n# result-library-dart\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelpiper%2Fresult-library-dart","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichaelpiper%2Fresult-library-dart","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichaelpiper%2Fresult-library-dart/lists"}