You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart语言中如何为变量添加多个注解?

Handling Multiple Type Annotations (or Union Types) in Dart

Hey there! I noticed you're getting started with Dart and ran into a snag with specifying variable types that can hold multiple kinds of values—let's break this down clearly.

First, let's clarify a quick terminology mix-up: in your example, DocumentSnapshot is a type annotation (telling Dart what kind of value the variable can hold), not a metadata annotation (like @deprecated or @override). It sounds like you're trying to create a variable that can be either a DocumentSnapshot or DocumentReference—that's called a union type in Dart.

Correct Syntax for Union Types (Dart 3.0+)

Dart 3.0 introduced native support for union types using the | (pipe) operator. Here's how you'd write your variable correctly:

final DocumentSnapshot|DocumentReference project;

This tells Dart that the project variable can hold either a DocumentSnapshot instance or a DocumentReference instance—no commas needed!

If You're Using an Older Dart Version (Pre-3.0)

If you can't upgrade to Dart 3.0 yet, you have a couple of options:

  • Use Object as the type (though this is very broad and loses type safety):
    final Object project;
    
  • Create a shared abstract class or interface that both DocumentSnapshot and DocumentReference implement, then use that as the type (this is better for type safety):
    abstract class FirestoreDocument {}
    
    class DocumentSnapshot implements FirestoreDocument { /* ... */ }
    class DocumentReference implements FirestoreDocument { /* ... */ }
    
    final FirestoreDocument project;
    

Bonus: Adding Multiple Metadata Annotations

If you actually meant adding multiple metadata annotations (like @deprecated or custom annotations) to a variable, you just stack them above the variable declaration:

@deprecated
@visibleForTesting
final DocumentSnapshot project;

Hope that clears things up—happy coding with Dart!

内容的提问来源于stack exchange,提问作者Alvin Konda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:45:20