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

插件详情v6.1.0+1

optional

Optional 类型的实现,有助于避免处理空引用

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
299
喜欢数
38
Pub 分数
150

安装插件

flutter pub add optional

插件介绍

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

可选包提供了一种安全、函数式的方法,用于在 Dart 中处理可能为 null 的值,使用 Optional 类型模式。受 Java 的 Optional 启发,它帮助开发者通过封装可能存在或不存在的值来避免空引用错误。方法不再返回 null,而是返回 Optional 实例,鼓励显式处理缺失情况。这促进了更清晰、更可预测的代码,并减少了因 null 导致的运行时崩溃。该包与 Dart 的空安全功能无缝集成。

适合场景

  • 处理可能返回 null 的方法
  • 使用链式操作避免空值检查
  • 提高数据管道中的代码可读性
  • 管理可能缺失的配置值
  • 实现安全的数据库或API响应解析

主要特点

  • 安全的空值包装
  • 方法链式调用与 map/flatMap
  • 安全提取使用 getOrElse
  • 对函数式编程模式的支持
  • 可组合且不可变的设计

适合对象

  • 使用 Dart 空安全的开发者
  • 致力于减少空值相关错误的团队
  • 需要干净错误处理的项目
  • 函数式风格的 Dart 代码库
  • 具有复杂数据流的应用程序

使用建议

  • 对简单情况增加轻微开销
  • 需要学习新的模式
  • 不适合用于性能关键路径
  • 可能增加简单情况下的代码冗余
  • 最好与空安全一起使用

原始 README

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

Coverage Status

Optional.dart

Optional.dart is an implementation of the Optional type, inspired by Java 8's Optional class.

Optional helps avoid null reference errors by wrapping values in an object that holds information regarding whether the value is present or not.

For example, when applying a set of operations to a value, any of which might return null, you can get rid of the null checks by using Optional.map():

String? getString() {
  // ..
  if (condition) {
    return null;
  } else {
    return "12";
  }
}

int? calculateSomething(String str) {
  // ...
  if (someCondition) {
    return null;
  } else {
    return 3 + int.parse(str);
  }
} 

double? calculateSomethingElse(int val) {
  // ...
  if (anotherCondition) {
    return null;
  } else {
    return val * 1.42;
  }
}

void main() {
  
  // before
  
  String? str;
  int? i;
  double? d;
  
  str = getString();
  
  if (str != null) {
    i = calculateSomething(str);
  }
  
  if (i != null) {
    d = calculateSomethingElse(i);
  }
  
  if (d != null) {
    print(d);
  }
  
  // with Optional
  
  Optional.ofNullable(getString())
    .map(calculateSomething)
    .map(calculateSomethingElse)
    .ifPresent(print);
}

所属分类

依赖

依赖清单 1 项

源码仓库

使用此插件的项目