result_type 0.1.0 copy "result_type: ^0.1.0" to clipboard
result_type: ^0.1.0 copied to clipboard

outdated

Result Type represents either a success or a failure, including an associated value in each case.

Result Type for Dart

CI Status Result Type is released under the Apache license. Effective Dart PRs welcome!

Content #

Features #

Result is a type that represents either Success or Failure.

Inspired by functional programming, Rust and Swift.

Requirements #

  • Dart: 2.12.0+

Install #

dependencies:
  result_type: ^0.1.0

Example #

The detailed example can be found at result_type/example/example.dart.

import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:http/http.dart' as http;
import 'package:result_type/result_type.dart';

void main() async {
  final random = Random();
  final client = http.Client();
  final result = await getPhotos(client);

  /// Do something with successful operation results or handle an error.
  if (result.isSuccess) {
    print('Photos Items: ${result.success}');
  } else {
    print('Error: ${result.failure}');
  }

  /// Apply transformation to successful operation results or handle an error.
  if (result.isSuccess) {
    final items = result.map((i) => i.where((j) => j.title.length > 60)).success;
    print('Number of Long Titles: ${items.length}');
  } else {
    print('Error: ${result.failure}');
  }

  /// In this example, note the difference in the result of using `map` and
  /// `flatMap` with a transformation that returns an result type.
  Result<int, Error> getNextInteger() => Success(random.nextInt(4));
  Result<int, Error> getNextAfterInteger(int n) => Success(random.nextInt(n + 1));

  final nextIntegerNestedResults = getNextInteger().map(getNextAfterInteger);
  print(nextIntegerNestedResults.runtimeType);
  /// `Prints`: Success<Result<int, Error>, dynamic>

  final nextIntegerUnboxedResults =  getNextInteger().flatMap(getNextAfterInteger);
  print(nextIntegerUnboxedResults.runtimeType);
  /// `Prints`: Success<int, Error>

  /// Use completion handler / callback style API if you want to.
  await getPhotos(client)
    ..result((photos) {
      print('Photos: $photos');
    }, (error) {
      print('Error: $error');
    });
}

To see examples of the following package in action:

cd example && dart run

Support #

Post issues and feature requests on the GitHub issue tracker.

License #

The source code of Result Type project is available under the Apache license. See the LICENSE file for more info.

33
likes
0
pub points
88%
popularity

Publisher

verified publisherminikin.me

Result Type represents either a success or a failure, including an associated value in each case.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

meta

More

Packages that depend on result_type