adaptive_number 套件提供了一種可根據執行環境自適應的數字類型。在 JavaScript 平台,它使用 64 位有符號固定寬度整數以確保一致的精確度,而在所有其他平台則預設使用 Dart 的原生 int 類型。這確保了在 Web 與原生環境中都能可靠運作,特別是在處理大型整數或需要跨平台數值運算一致性時。
適用情境
跨平台整數處理
基於網路的應用程式,數量龐大
跨平台的一致性算術
涉及整數的資料序列化
Flutter Web 應用中的數值計算
主要特色
基於平台自適應的整數大小
JS 上的 64 位固定寬度整數
原生 int 在非 JS 平台上的回退
跨執行時的一致行為
與現有程式碼的簡單整合
適合對象
面向網頁和原生平台的開發者
需要精確整數運算的應用程式
需要數值邏輯可移植性的專案
避免 JavaScript 特定數字限制的 Teams
具有共享業務邏輯的 Flutter 應用
使用建議
僅限整數值
不支援浮點數
非 JS 平台上的效能開銷
對於簡單用例可能不需要
需要在 JS 目標上進行仔細測試
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
adaptive_number
A library providing a Number implementation that is dependent on the platform it is compiled for.
For JS runtimes, the implementation uses a 64-bit signed fixed-width integer, for all other platforms
the default Dart int data type.
Use cases of this library
The Number substitute is useful in situations where a value may overflow on JS runtimes since the available value range
is not the same compared to mobile or desktop platforms:
The overflow on JS environments can be circumvented by using a BigInt or the fixed-with implementation of this library:
https://pub.dev/packages/fixnum
The disadvantage of just replacing all usages of int with BigInt or fixnum/Int64 is that the performance on
mobile platforms may suffer significantly.
The adpative_number library takes a conditional import approach to ease this problem:
If it runs on a JS runtime, Number wraps a fixnum/Int64
For all other platforms Number wraps a default Dart int type.
Some historical background of this library can also be seen in: https://github.com/MixinNetwork/libsignal_protocol_dart/pull/43
Usage
A Number instance is created by wrapping it around a default int value:
import'package:adaptive_number/adaptive_number.dart';
voidmain() {
final number1 = Number(93432);
final number2 = Number(42435);
assert((number1 + number2) == Number(51777));
}
All other operations on Number behave the same way as with int.
Features and bugs
Please file feature requests and bugs at the issue tracker.