搜尋套件、儲存庫與 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 項

原始碼儲存庫

使用此套件的專案