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
Objectas the type (though this is very broad and loses type safety):final Object project; - Create a shared abstract class or interface that both
DocumentSnapshotandDocumentReferenceimplement, 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

