搜索插件、代码仓与 APP 分类

插件详情v1.0.0

result_type

Dart 的结果类型。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
4850
喜欢数
35
Pub 分数
150

安装插件

flutter pub add result_type

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

Result Type 是一个 Dart 包,提供了一种强大且类型安全的方式来处理可能成功返回值或失败返回错误的操作。受函数式编程概念启发,它引入了 `Result<T, E>` 类来表示计算结果,使错误处理更加明确,并减少了对异常的依赖。它支持链式调用、映射和错误传播,提升了代码的可读性和可维护性。非常适合需要明确成功/失败状态的业务逻辑和数据处理流程。

适合场景

  • 处理 API 响应
  • 处理用户输入验证
  • 管理异步操作
  • 使用显式错误实现业务逻辑
  • 用结构化流程替换 try-catch 块

主要特点

  • 类型安全的成功与错误类型
  • 链式调用和转换方法
  • 内置错误传播
  • 可组合的结果处理
  • 最小化样板代码

适合对象

  • 使用函数式编程模式的开发者在 Dart 中
  • 需要清晰错误处理的项目
  • 致力于可预测状态管理的团队
  • 具有复杂数据流的应用程序
  • 那些寻求异常之外的控制流替代方案的人

使用建议

  • 如果对 Result 类型不熟悉,则需要学习新的模式
  • 在简单情况下可能会增加冗余
  • 不适合用于低级系统错误
  • 与某些现有的基于异常的库集成有限
  • 最好与空安全实践结合使用

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Result Type for Dart

CI Status Result Type is released under the MIT license. PRs welcome!

Content

Features

Result is a type that represents either Success or Failure.

Inspired by functional programming, Rust and Swift.

Requirements

  • Dart: 3.3.0+

Install

dependencies:
  result_type: ^1.0.0

Example

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

import 'dart:math';

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

import 'imaginary_service.dart';
import 'photo.dart';
import 'photos_service.dart';

final client = http.Client();
final random = Random();

void main() async {
  final photosResult = await PhotosService.getPhotos(client);

  final photosOr = photosResult.unwrapOr([Photo.initial()]);

  print(photosOr);

  /// Use `switch` to handle both success and failure.
  final _ = switch (photosResult) {
    Success(value: final data) => data,
    Failure(value: final error) => 'Error: $error'
  };

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

  // Chain multiple asynchronous operations.
  final result1 = await ImaginaryService.fetchData1();
  final result2 = await ImaginaryService.fetchData2(result1.success);
  final result3 = await ImaginaryService.fetchData2(result2.success);

  // Print the result of the last operation: `Success: Default Data`
  print(result3.unwrapOr('Default Data'));

  // This will throw an exception as `_handleResult`
  // has a case with 'Wrong Data'.
  //print(result3.unwrap());

  String length(String string) => string.length.toString();

  final unwrapOrElse = result3.unwrapOrElse('Default (((((Data)))))', length);
  // Print the result of the last operation: `22`
  print(unwrapOrElse);

  /// Apply transformation to successful operation results or handle an error.
  if (photosResult.isSuccess) {
    final items = photosResult
        .map(
          (i) => i.where(
            (j) => j.title.length > 60,
          ),
        )
        .success;
    print('Number of Long Titles: ${items.length}');
  } else {
    print('Error: ${photosResult.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, Exception> getNextInteger() => Success(random.nextInt(4));
  Result<int, Exception> 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 PhotosService.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 is distributed under the MIT license. See the LICENSE file for more info.

所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目

暂无相关数据。