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.