Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

dart.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more
Variables

Dart 3.11 is live!Learn more

Variables

Learn about variables in Dart.

Here's an example of creating a variable and initializing it:

dart
varname='Bob';

Variables store references. The variable calledname contains a reference to aString object with a value of "Bob".

The type of thename variable is inferred to beString, but you can change that type by specifying it. If an object isn't restricted to a single type, specify theObject type (ordynamic if necessary).

dart
Objectname='Bob';

Another option is to explicitly declare the type that would be inferred:

dart
Stringname='Bob';
Note

This page follows thestyle guide recommendation of usingvar, rather than type annotations, for local variables.

Null safety

#

The Dart language enforces sound null safety.

Null safety prevents an error that results from unintentional access of variables set tonull. The error is called a null dereference error. A null dereference error occurs when you access a property or call a method on an expression that evaluates tonull. An exception to this rule is whennull supports the property or method, liketoString() orhashCode. With null safety, the Dart compiler detects these potential errors at compile time.

For example, say you want to find the absolute value of anint variablei. Ifi isnull, callingi.abs() causes a null dereference error. In other languages, trying this could lead to a runtime error. Dart's compiler prevents this error by prohibiting these actions.

Null safety introduces three key changes:

  1. When you specify a type for a variable, parameter, or another relevant component, you can control whether the type allowsnull. To enable nullability, you add a? to the end of the type declaration.

    dart
    String?name// Nullable type. Can be `null` or string.Stringname// Non-nullable type. Cannot be `null` but can be string.
  2. You must initialize variables before using them. Nullable variables default tonull, so they are initialized by default. Dart doesn't set initial values to non-nullable types. It forces you to set an initial value. Dart doesn't allow you to observe an uninitialized variable. This prevents you from accessing properties or calling methods where the receiver's type can benull butnull doesn't support the method or property used.

  3. You can't access properties or call methods on an expression with a nullable type. The same exception applies where it's a property or method thatnull supports likehashCode ortoString().

Sound null safety changes potentialruntime errors intoedit-time analysis errors. Null safety flags a non-null variable when it has been either:

  • Not initialized with a non-null value.
  • Assigned anull value.

This check allows you to fix these errorsbefore deploying your app.

Default value

#

Uninitialized variables that have a nullable type have an initial value ofnull. Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.

dart
int?lineCount;assert(lineCount==null);
Note

With null safety, you must initialize the values of non-nullable variables before you use them:

dart
intlineCount=0;

You don't have to initialize a local variable where it's declared, but you do need to assign it a value before it's used. For example, the following code is valid because Dart can detect thatlineCount is non-null by the time it's passed toprint():

dart
intlineCount;if(weLikeToCount){lineCount=countLines();}else{lineCount=0;}print(lineCount);

Top-level and class variables are lazily initialized; the initialization code runs the first time the variable is used.

Late variables

#

Thelate modifier has two use cases:

  • Declaring a non-nullable variable that's initialized after its declaration.
  • Lazily initializing a variable.

Often Dart's control flow analysis can detect when a non-nullable variable is set to a non-null value before it's used, but sometimes analysis fails. Two common cases are top-level variables and instance variables: Dart often can't determine whether they're set, so it doesn't try.

If you're sure that a variable is set before it's used, but Dart disagrees, you can fix the error by marking the variable aslate:

dart
lateStringdescription;voidmain(){description='Feijoada!';print(description);}
Notice

If you fail to initialize alate variable, a runtime error occurs when the variable is used.

When you mark a variable aslate but initialize it at its declaration, then the initializer runs the first time the variable is used. This lazy initialization is handy in a couple of cases:

  • The variable might not be needed, and initializing it is costly.
  • You're initializing an instance variable, and its initializer needs access tothis.

In the following example, if thetemperature variable is never used, then the expensivereadThermometer() function is never called:

dart
// This is the program's only call to readThermometer().lateStringtemperature=readThermometer();// Lazily initialized.

If you never intend to change a variable, usefinal orconst, either instead ofvar or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant. (Const variables are implicitly final.)

Note

Instance variables can befinal but notconst.

Here's an example of creating and setting afinal variable:

dart
finalname='Bob';// Without a type annotationfinalStringnickname='Bobby';

You can't change the value of afinal variable:

static analysis: failuredart
name='Alice';// Error: a final variable can only be set once.

Useconst for variables that you want to becompile-time constants. If the const variable is at the class level, mark itstatic const. Where you declare the variable, set the value to a compile-time constant such as a number or string literal, a const variable, or the result of an arithmetic operation on constant numbers:

dart
constbar=1000000;// Unit of pressure (dynes/cm2)constdoubleatm=1.01325*bar;// Standard atmosphere

Theconst keyword isn't just for declaring constant variables. You can also use it to create constantvalues, as well as to declare constructors thatcreate constant values. Any variable can have a constant value.

dart
varfoo=const[];finalbar=const[];constbaz=[];// Equivalent to `const []`

You can omitconst from the initializing expression of aconst declaration, like forbaz above. For details, seeDON'T use const redundantly.

You can change the reference of a non-final, non-const variable, even if it used to have aconst value:

dart
foo=[1,2,3];// Was const []

You can't change the value of aconst variable:

static analysis: failuredart
baz=[42];// Error: Constant variables can't be assigned a value.

You can define constants that usetype checks and casts (is andas),collectionif, andspread operators (... and...?):

dart
constObjecti=3;// Where i is a const Object with an int value...constlist=[iasint];// Use a typecast.constmap={if(iisint)i:'int'};// Use is and collection if.constset={if(listisList<int>)...list};// ...and a spread.
Note

Although afinal object cannot be modified, its fields can be changed. In comparison, aconst object and its fields cannot be changed: they'reimmutable.

For more information on usingconst to create constant values, seeLists,Maps, andClasses.

Wildcard variables

#
Version note

A wildcard variable with the name_ declares a local variable or parameter that is non-binding; essentially, a placeholder. The initializer, if there is one, is still executed, but the value isn't accessible. Multiple declarations named_ can exist in the same namespace without a collision error.

Top-level declarations or members where library privacy might be affected are not valid uses for wildcard variables. Declarations local to a block scope, such as the following examples, can declare a wildcard:

  • Local variable declaration.

    dart
    main(){var_=1;int_=2;}
  • For loop variable declaration.

    dart
    for(var_inlist){}
  • Catch clause parameters.

    dart
    try{throw'!';}catch(_){print('oops');}
  • Generic type and function type parameters.

    dart
    classT<_>{}voidgenericFunction<_>(){}takeGenericCallback(<_>()=>true);
  • Function parameters.

    dart
    Foo(_,this._,super._,void_()){}list.where((_)=>true);voidf(voidg(int_,bool_)){}typedefT=voidFunction(String_,String_);
Tip

Enable the lintunnecessary_underscores to identify where a single non-binding wildcard variable_ can replace the previous convention of using multiple binding underscores (__,___, etc.) to avoid name collisions.

Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Page last updated on 2025-11-13.View source orreport an issue.


[8]ページ先頭

©2009-2026 Movatter.jp