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

插件详情v1.0.0

global_assert

一个微型库,可轻松在编译时对常量进行断言,以便配置错误的应用程序在编译时失败,而不是在运行时失败。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
9570
喜欢数
7
Pub 分数
160

安装插件

flutter pub add global_assert

插件介绍

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

GlobalAssert 是一个轻量级的 Dart 包,可在构建时对常量启用断言,帮助在构建过程中尽早发现配置错误,而不是在运行时。通过在编译时验证关键值,它提高了应用程序的可靠性,并降低了生产环境中无声失败的风险。非常适合用于强制执行静态数据上的不变条件,可无缝集成到所有主要平台的 Flutter 项目中。

适合场景

  • 验证配置常量
  • 防止因配置错误导致的运行时错误
  • 在构建过程中强制执行不变量检查
  • 提高测试可靠性
  • 尽早检测无效状态
  • 确保安全初始化

主要特点

  • 编译时断言求值
  • 用于常量验证的简单 API
  • 无运行时开销
  • 跨平台支持
  • 与 Flutter 构建系统集成
  • 最小依赖足迹

适合对象

  • 注重构建时安全性的开发者
  • 使用静态分析进行质量控制的团队
  • 具有严格配置要求的项目
  • 需要强大初始化检查的 Flutter 应用
  • 需要早期失败检测的 CI/CD 流水线

使用建议

  • 仅适用于编译时常量
  • 仅限简单的布尔条件
  • 不替换运行时验证
  • 需要理解构建时执行
  • 可能会略微增加构建时间
  • 不适用于动态或用户提供的数据

原始 README

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

A micro-library for asserting at build time.

pub package Build Status Coverage

It's a common practice to configure a Dart app using const (build-time) values. There are benefits to this approach, such as enabling tree shaking of unused code.

This library makes it easy to do build-time assertions about such constants so that misconfigured apps fail at build-time instead of failing at runtime.

Usage

Use this library to validate your app's const values at build time. Anything can be annotated with @Assert.

//
// This app will fail compilation with '--define=MY_VAL=foo'
//

@Assert(
  myBuildTimeVal == 'val1' || myBuildTimeVal == 'val2',
  'myBuildTimeVal must be one of "val1" or "val2"',
)
const myBuildTimeVal = String.fromEnvironment('MY_VAL');

void main() {
  print('myBuildTimeVal is "$myBuildTimeVal"');
}

FAQ

🤔 How does this even work?!

The Dart compiler invokes annotation constructors at compile-time. This micro-library takes advantage of that to "trick" the compiler into allowing build-time asserts that can be placed (almost) anywhere. Special thanks to Kyle Turney for the inspiration behind this approach.

Why not allow an assert without a message?

Unfortunately, Dart doesn't treat an assert with a null message the same as an assert without any message at all. This means that we would need two constructors for @Assert to enable both messageless asserts and asserts with messages. Instead, we made the design choice when creating this micro-library that @Assert should require a non-null message. This enforces more meaningful compilation failure messages.

Will this always be needed?

We expect that when Dart supports metaprogramming, this library will be deprecated.

所属分类

源码仓库

使用此插件的项目

暂无相关数据。