ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://dart.dev/language |
| Last Crawled | 2026-04-18 18:02:00 (15 hours ago) |
| First Indexed | 2023-03-13 19:36:06 (3 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Introduction to Dart |
| Meta Description | A brief introduction to Dart programs and important concepts. |
| Meta Canonical | null |
| Boilerpipe Text | Language
A brief introduction to Dart programs and important concepts.
This page provides a brief introduction to the Dart language
through samples of its main features.
To learn more about the Dart language,
visit the in-depth, individual topic pages
listed under
Language
in the left side menu.
For coverage of Dart's core libraries,
check out the
core library documentation
.
You can also check out the
Dart cheatsheet
,
for a more interactive introduction.
Hello World
#
Every app requires the top-level
main()
function, where execution starts.
Functions that don't explicitly return a value have the
void
return type.
To display text on the console, you can use the top-level
print()
function:
dart
void
main
(
)
{
print
(
'
Hello, World!
'
)
;
}
Read more about
the
main()
function
in Dart,
including optional parameters for command-line arguments.
Variables
#
Even in
type-safe
Dart code,
you can declare most variables without explicitly specifying their type using
var
.
Thanks to type inference, these variables' types are determined by their initial values:
dart
var
name
=
'
Voyager I
'
;
var
year
=
1977
;
var
antennaDiameter
=
3.7
;
var
flybyObjects
=
[
'
Jupiter
'
,
'
Saturn
'
,
'
Uranus
'
,
'
Neptune
'
]
;
var
image
=
{
'
tags
'
:
[
'
saturn
'
]
,
'
url
'
:
'
//path/to/saturn.jpg
'
,
}
;
Read more
about variables in Dart,
including default values, the
final
and
const
keywords, and static types.
Control flow statements
#
Dart supports the usual control flow statements:
dart
if
(
year
>=
2001
)
{
print
(
'
21st century
'
)
;
}
else
if
(
year
>=
1901
)
{
print
(
'
20th century
'
)
;
}
for
(
final
object
in
flybyObjects
)
{
print
(
object
)
;
}
for
(
int
month
=
1
;
month
<=
12
;
month
++
)
{
print
(
month
)
;
}
while
(
year
<
2016
)
{
year
+
=
1
;
}
Read more about control flow statements in Dart,
including
break
and
continue
,
switch
and
case
,
and
assert
.
Functions
#
We recommend
specifying the types of each function's arguments and return value:
dart
int
fibonacci
(
int
n
)
{
if
(
n
==
0
||
n
==
1
)
return
n
;
return
fibonacci
(
n
-
1
)
+
fibonacci
(
n
-
2
)
;
}
var
result
=
fibonacci
(
20
)
;
A shorthand
=>
(
arrow
) syntax is handy for functions that
contain a single statement.
This syntax is especially useful when passing anonymous functions as arguments:
dart
flybyObjects
.
where
(
(
name
)
=>
name
.
contains
(
'
turn
'
)
)
.
forEach
(
print
)
;
Besides showing an anonymous function (the argument to
where()
),
this code shows that you can use a function as an argument:
the top-level
print()
function is an argument to
forEach()
.
Read more
about functions in Dart,
including optional parameters, default parameter values, and lexical scope.
Dart comments usually start with
//
.
dart
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/*
Comments like these are also supported.
*/
Read more
about comments in Dart,
including how the documentation tooling works.
To access APIs defined in other libraries, use
import
.
dart
// Importing core libraries
import
'
dart:math
'
;
// Importing libraries from external packages
import
'
package:test/test.dart
'
;
// Importing files
import
'
path/to/my_other_file.dart
'
;
Read more
about libraries and visibility in Dart,
including library prefixes,
show
and
hide
,
and lazy loading through the
deferred
keyword.
Here's an example of a class with three properties, two constructors,
and a method. One of the properties can't be set directly, so it's
defined using a getter method (instead of a variable). The method
uses string interpolation to print variables' string equivalents inside
of string literals.
dart
class
Spacecraft
{
String
name
;
DateTime
?
launchDate
;
// Read-only non-final property
int
?
get
launchYear
=>
launchDate
?.
year
;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft
(
this
.
name
,
this
.
launchDate
)
{
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft
.
unlaunched
(
String
name
)
:
this
(
name
,
null
)
;
// Method.
void
describe
(
)
{
print
(
'
Spacecraft:
$name
'
)
;
// Type promotion doesn't work on getters.
var
launchDate
=
this
.
launchDate
;
if
(
launchDate
!=
null
)
{
int
years
=
DateTime
.
now
(
)
.
difference
(
launchDate
)
.
inDays
~/
365
;
print
(
'
Launched:
$launchYear
(
$years
years ago)
'
)
;
}
else
{
print
(
'
Unlaunched
'
)
;
}
}
}
Read more
about strings,
including string interpolation, literals, expressions, and the
toString()
method.
You might use the
Spacecraft
class like this:
dart
var
voyager
=
Spacecraft
(
'
Voyager I
'
,
DateTime
(
1977
,
9
,
5
)
)
;
voyager
.
describe
(
)
;
var
voyager3
=
Spacecraft
.
unlaunched
(
'
Voyager III
'
)
;
voyager3
.
describe
(
)
;
Read more
about classes in Dart,
including initializer lists, optional
new
and
const
, redirecting constructors,
factory
constructors, getters, setters, and much more.
Enums are a way of enumerating a predefined set of values or instances
in a way which ensures that there cannot be any other instances of that type.
Here is an example of a simple
enum
that defines
a simple list of predefined planet types:
dart
enum
PlanetType
{
terrestrial
,
gas
,
ice
}
Here is an example of an enhanced enum declaration
of a class describing planets,
with a defined set of constant instances,
namely the planets of our own solar system.
dart
/// Enum that enumerates the different planets in our solar system
/// and some of their properties.
enum
Planet
{
mercury
(
planetType
:
PlanetType
.
terrestrial
,
moons
:
0
,
hasRings
:
false
)
,
venus
(
planetType
:
PlanetType
.
terrestrial
,
moons
:
0
,
hasRings
:
false
)
,
// ···
uranus
(
planetType
:
PlanetType
.
ice
,
moons
:
27
,
hasRings
:
true
)
,
neptune
(
planetType
:
PlanetType
.
ice
,
moons
:
14
,
hasRings
:
true
)
;
/// A constant generating constructor
const
Planet
(
{
required
this
.
planetType
,
required
this
.
moons
,
required
this
.
hasRings
,
}
)
;
/// All instance variables are final
final
PlanetType
planetType
;
final
int
moons
;
final
bool
hasRings
;
/// Enhanced enums support getters and other methods
bool
get
isGiant
=>
planetType
==
PlanetType
.
gas
||
planetType
==
PlanetType
.
ice
;
}
You might use the
Planet
enum like this:
dart
final
yourPlanet
=
Planet
.
earth
;
if
(
!
yourPlanet
.
isGiant
)
{
print
(
'
Your planet is not a "giant planet".
'
)
;
}
When the compiler can infer the enum type from the context,
you can use the more concise dot-shorthand syntax to access enum values.
Instead of writing the full
EnumName.value
,
you can just write
.value
. This can make your code cleaner
and easier to read.
For example, when declaring a variable with an explicit type of
Planet
,
you can omit the enum name because
the type of
Planet
is already established:
dart
// Instead of the full, explicit syntax:
Planet
myPlanet
=
Planet
.
venus
;
// You can use a dot shorthand:
Planet
myPlanet
=
.
venus
;
Dot shorthands aren't limited to variable declarations.
They can also be used in contexts like function arguments
and switch cases where the enum type is clear to the compiler.
Read more
about enums in Dart,
including enhanced enum requirements, automatically introduced properties,
accessing enumerated value names, switch statement support, and much more.
Read more
about dot shorthand syntax.
Inheritance
#
Dart has single inheritance.
dart
class
Orbiter
extends
Spacecraft
{
double
altitude
;
Orbiter
(
super
.
name
,
DateTime
super
.
launchDate
,
this
.
altitude
)
;
}
Read more
about extending classes, the optional
@override
annotation, and more.
Mixins are a way of reusing code in multiple class hierarchies. The following is
a mixin declaration:
dart
mixin
Piloted
{
int
astronauts
=
1
;
void
describeCrew
(
)
{
print
(
'
Number of astronauts:
$astronauts
'
)
;
}
}
To add a mixin's capabilities to a class, just extend the class with the mixin.
dart
class
PilotedCraft
extends
Spacecraft
with
Piloted
{
// ···
}
PilotedCraft
now has the
astronauts
field as well as the
describeCrew()
method.
Read more
about mixins.
Interfaces and abstract classes
#
All classes implicitly define an interface.
Therefore, you can implement any class.
dart
class
MockSpaceship
implements
Spacecraft
{
// ···
}
Read more about
implicit interfaces
, or
about the explicit
interface
keyword
.
You can create an abstract class
to be extended (or implemented) by a concrete class.
Abstract classes can contain abstract methods (with empty bodies).
dart
abstract
class
Describable
{
void
describe
(
)
;
void
describeWithEmphasis
(
)
{
print
(
'
=========
'
)
;
describe
(
)
;
print
(
'
=========
'
)
;
}
}
Any class extending
Describable
has the
describeWithEmphasis()
method,
which calls the extender's implementation of
describe()
.
Read more
about abstract classes and methods.
Avoid callback hell and make your code much more readable by
using
async
and
await
.
dart
const
oneSecond
=
Duration
(
seconds
:
1
)
;
// ···
Future
<
void
>
printWithDelay
(
String
message
)
async
{
await
Future
.
delayed
(
oneSecond
)
;
print
(
message
)
;
}
The method above is equivalent to:
dart
Future
<
void
>
printWithDelay
(
String
message
)
{
return
Future
.
delayed
(
oneSecond
)
.
then
(
(
_
)
{
print
(
message
)
;
}
)
;
}
As the next example shows,
async
and
await
help make asynchronous code
easy to read.
dart
Future
<
void
>
createDescriptions
(
Iterable
<
String
>
objects
)
async
{
for
(
final
object
in
objects
)
{
try
{
var
file
=
File
(
'
$object
.txt
'
)
;
if
(
await
file
.
exists
(
)
)
{
var
modified
=
await
file
.
lastModified
(
)
;
print
(
'
File for
$object
already exists. It was modified on
$modified
.
'
,
)
;
continue
;
}
await
file
.
create
(
)
;
await
file
.
writeAsString
(
'
Start describing
$object
in this file.
'
)
;
}
on
IOException
catch
(
e
)
{
print
(
'
Cannot create description for
$object
:
$e
'
)
;
}
}
}
You can also use
async*
, which gives you a nice, readable way to build streams.
dart
Stream
<
String
>
report
(
Spacecraft
craft
,
Iterable
<
String
>
objects
)
async
*
{
for
(
final
object
in
objects
)
{
await
Future
.
delayed
(
oneSecond
)
;
yield
'
${craft.name}
flies by
$object
'
;
}
}
Read more
about
asynchrony support, including
async
functions,
Future
,
Stream
,
and the asynchronous loop (
await for
).
Exceptions
#
To raise an exception, use
throw
:
dart
if
(
astronauts
==
0
)
{
throw
StateError
(
'
No astronauts.
'
)
;
}
To catch an exception, use a
try
statement with
on
or
catch
(or both):
dart
Future
<
void
>
describeFlybyObjects
(
List
<
String
>
flybyObjects
)
async
{
try
{
for
(
final
object
in
flybyObjects
)
{
var
description
=
await
File
(
'
$object
.txt
'
)
.
readAsString
(
)
;
print
(
description
)
;
}
}
on
IOException
catch
(
e
)
{
print
(
'
Could not describe object:
$e
'
)
;
}
finally
{
flybyObjects
.
clear
(
)
;
}
}
Note that the code above is asynchronous;
try
works for both synchronous and asynchronous code in an
async
function.
Read more
about exceptions,
including stack traces,
rethrow
,
and the difference between
Error
and
Exception
.
Important concepts
#
As you continue to learn about the Dart language,
keep these facts and concepts in mind:
Everything you can place in a variable is an
object
, and every
object is an instance of a
class
. Even numbers, functions, and
null
are objects.
With the exception of
null
(if you enable
sound null safety
),
all objects inherit from the
Object
class.
Although Dart is strongly typed, type annotations are optional
because Dart can infer types. In
var number = 101
,
number
is inferred to be of type
int
.
Variables can't contain
null
unless you say they can.
You can make a variable nullable by
putting a question mark (
?
) at the end of its type.
For example, a variable of type
int?
might be an integer,
or it might be
null
.
If you
know
that an expression never evaluates to
null
but Dart disagrees,
you can add
!
to assert that it isn't null
(and to throw an exception if it is).
An example:
int x = nullableButNotNullInt!
When you want to explicitly say
that any type is allowed, use the type
Object?
(if you've enabled null safety),
Object
,
or—if you must defer type checking until runtime—the
special type
dynamic
.
Dart supports generic types, like
List<int>
(a list of integers)
or
List<Object>
(a list of objects of any type).
Dart supports top-level functions (such as
main()
), as well as
functions tied to a class or object (
static
and
instance
methods
, respectively). You can also create functions within
functions (
nested
or
local functions
).
Similarly, Dart supports top-level
variables
, as well as variables
tied to a class or object (static and instance variables). Instance
variables are sometimes known as
fields
or
properties
.
Unlike Java, Dart doesn't have the keywords
public
,
protected
,
and
private
. If an identifier starts with an underscore (
_
), it's
private to its library. For details, see
Libraries and imports
.
Identifiers
can start with a letter or underscore (
_
), followed by any
combination of those characters plus digits.
Dart has both
expressions
(which have runtime values) and
statements
(which don't).
For example, the
conditional expression
condition ? expr1 : expr2
has a value of
expr1
or
expr2
.
Compare that to an
if-else statement
, which has no value.
A statement often contains one or more expressions,
but an expression can't directly contain a statement.
Dart tools can report two kinds of problems:
warnings
and
errors
.
Warnings are just indications that your code might not work, but
they don't prevent your program from executing. Errors can be either
compile-time or run-time. A compile-time error prevents the code
from executing at all; a run-time error results in an
exception
being raised while the code executes.
Additional resources
#
You can find more documentation and code samples in the
core library documentation
and the
Dart API reference
.
This site's code follows the conventions in the
Dart style guide
.
Next
Variables
Was this page's content helpful?
Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Page last updated on 2025-12-16.
View source
or
report an issue
. |
| Markdown | [Skip to main content](https://dart.dev/language#site-content-title)
dart.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.
[Learn more](https://policies.google.com/technologies/cookies)
OK, got it
[Dart](https://dart.dev/ "Go to the Dart homepage")[Docs](https://dart.dev/docs)
- [Overview](https://dart.dev/overview)
- [Docs](https://dart.dev/docs)
- [Blog](https://dart.dev/blog)
- [Community](https://dart.dev/community)
- [Learn](https://dart.dev/learn)
- [Try Dart](https://dart.dev/#try-dart)
- [Get Dart](https://dart.dev/get-dart)
[search](https://dart.dev/search "Navigate to the dart.dev search page.")
routine
- light\_modeLight
- dark\_modeDark
- night\_sight\_autoAutomatic
apps
- [Dart](https://dart.dev/ "Navigate to the Dart website.")
- [DartAPI](https://api.dart.dev/ "Navigate to the Dart API website.")
- [DartPad](https://dartpad.dev/ "Navigate to the DartPad website.")
- [pub.dev](https://pub.dev/ "Navigate to the pub.dev website.")
menuclose
- [asteriskOverview](https://dart.dev/overview)
- [docsDocs](https://dart.dev/docs)
- [newsmodeBlog](https://dart.dev/blog)
- [publicCommunity](https://dart.dev/community)
- [play\_lessonLearn Dart](https://dart.dev/learn)
- [downloadGet Dart](https://dart.dev/get-dart)
- Languageexpand\_more
- [Introduction](https://dart.dev/language)
- [Variables](https://dart.dev/language/variables)
- [Operators](https://dart.dev/language/operators)
- [Comments](https://dart.dev/language/comments)
- Typesexpand\_more
- [Built-in types](https://dart.dev/language/built-in-types)
- [Records](https://dart.dev/language/records)
- [Collections](https://dart.dev/language/collections)
- [Generics](https://dart.dev/language/generics)
- [Typedefs](https://dart.dev/language/typedefs)
- [Type system](https://dart.dev/language/type-system)
- Patternsexpand\_more
- [Overview & usage](https://dart.dev/language/patterns)
- [Pattern types](https://dart.dev/language/pattern-types)
- [Applied tutorialopen\_in\_new](https://codelabs.developers.google.com/codelabs/dart-patterns-records)
- Control flowexpand\_more
- [Loops](https://dart.dev/language/loops)
- [Branches](https://dart.dev/language/branches)
- [Error handling](https://dart.dev/language/error-handling)
- [Functions](https://dart.dev/language/functions)
- [Metadata](https://dart.dev/language/metadata)
- [Libraries & imports](https://dart.dev/language/libraries)
- Classes & objectsexpand\_more
- [Classes](https://dart.dev/language/classes)
- [Constructors](https://dart.dev/language/constructors)
- [Methods](https://dart.dev/language/methods)
- [Extend a class](https://dart.dev/language/extend)
- [Mixins](https://dart.dev/language/mixins)
- [Enums](https://dart.dev/language/enums)
- [Dot shorthands](https://dart.dev/language/dot-shorthands)
- [Extension methods](https://dart.dev/language/extension-methods)
- [Extension types](https://dart.dev/language/extension-types)
- [Callable objects](https://dart.dev/language/callable-objects)
- Class modifiersexpand\_more
- [Overview & usage](https://dart.dev/language/class-modifiers)
- [Class modifiers for API maintainers](https://dart.dev/language/class-modifiers-for-apis)
- [Reference](https://dart.dev/language/modifier-reference)
- Concurrencyexpand\_more
- [Overview](https://dart.dev/language/concurrency)
- [Asynchronous programming](https://dart.dev/language/async)
- [Isolates](https://dart.dev/language/isolates)
- Null safetyexpand\_more
- [Sound null safety](https://dart.dev/null-safety)
- [Understanding null safety](https://dart.dev/null-safety/understanding-null-safety)
- [Dart keywords](https://dart.dev/language/keywords)
- [Language versioning](https://dart.dev/language/versioning)
- Core librariesexpand\_more
- [Overview](https://dart.dev/libraries)
- [dart:core](https://dart.dev/libraries/dart-core)
- [dart:async](https://dart.dev/libraries/dart-async)
- [dart:math](https://dart.dev/libraries/dart-math)
- [dart:convert](https://dart.dev/libraries/dart-convert)
- [dart:io](https://dart.dev/libraries/dart-io)
- [dart:js\_interop](https://dart.dev/interop/js-interop)
- [Iterable collections](https://dart.dev/libraries/collections/iterables)
- Asynchronous programmingexpand\_more
- [Tutorial](https://dart.dev/libraries/async/async-await)
- [Futures and error handling](https://dart.dev/libraries/async/futures-error-handling)
- [Using streams](https://dart.dev/libraries/async/using-streams)
- [Creating streams](https://dart.dev/libraries/async/creating-streams)
- Effective Dartexpand\_more
- [Overview](https://dart.dev/effective-dart)
- [Style](https://dart.dev/effective-dart/style)
- [Documentation](https://dart.dev/effective-dart/documentation)
- [Usage](https://dart.dev/effective-dart/usage)
- [Design](https://dart.dev/effective-dart/design)
- Packagesexpand\_more
- [How to use packages](https://dart.dev/tools/pub/packages)
- [Creating packages](https://dart.dev/tools/pub/create-packages)
- [Publishing packages](https://dart.dev/tools/pub/publishing)
- [Writing package pages](https://dart.dev/tools/pub/writing-package-pages)
- [Workspaces (monorepo support)](https://dart.dev/tools/pub/workspaces)
- [Hooks](https://dart.dev/tools/hooks)
- Package referenceexpand\_more
- [Dependencies](https://dart.dev/tools/pub/dependencies)
- [Package layout conventions](https://dart.dev/tools/pub/package-layout)
- [Pub environment variables](https://dart.dev/tools/pub/environment-variables)
- [Pubspec file](https://dart.dev/tools/pub/pubspec)
- [Troubleshooting pub](https://dart.dev/tools/pub/troubleshoot)
- [Verified publishers](https://dart.dev/tools/pub/verified-publishers)
- [Security advisories](https://dart.dev/tools/pub/security-advisories)
- [Versioning](https://dart.dev/tools/pub/versioning)
- [Custom package repositories](https://dart.dev/tools/pub/custom-package-repositories)
- [What not to commit](https://dart.dev/tools/pub/private-files)
- [Commonly used packages](https://dart.dev/resources/useful-packages)
- [Dart team packages](https://dart.dev/resources/dart-team-packages)
- Developmentexpand\_more
- [JSON serialization](https://dart.dev/libraries/serialization/json)
- [Number representation](https://dart.dev/resources/language/number-representation)
- [Google APIs](https://dart.dev/resources/google-apis)
- [Multi-platform apps](https://dart.dev/multiplatform-apps)
- Command-line & server appsexpand\_more
- [Overview](https://dart.dev/server)
- [Fetch data from the internet](https://dart.dev/server/fetch-data)
- [Libraries & packages](https://dart.dev/server/libraries)
- [Google Cloud](https://dart.dev/server/google-cloud)
- Web appsexpand\_more
- [Overview](https://dart.dev/web)
- [Get started](https://dart.dev/web/get-started)
- [Deployment](https://dart.dev/web/deployment)
- [Libraries & packages](https://dart.dev/web/libraries)
- [Wasm compilation](https://dart.dev/web/wasm)
- [Environment declarations](https://dart.dev/libraries/core/environment-declarations)
- Interoperabilityexpand\_more
- [C interop](https://dart.dev/interop/c-interop)
- [Objective-C & Swift interop](https://dart.dev/interop/objective-c-interop)
- [Java & Kotlin interop](https://dart.dev/interop/java-interop)
- JavaScript interopexpand\_more
- [Overview](https://dart.dev/interop/js-interop)
- [Usage](https://dart.dev/interop/js-interop/usage)
- [JS types](https://dart.dev/interop/js-interop/js-types)
- [Tutorials](https://dart.dev/interop/js-interop/tutorials)
- [Past JS interop](https://dart.dev/interop/js-interop/past-js-interop)
- [Web interop](https://dart.dev/interop/js-interop/package-web)
- Tools & techniquesexpand\_more
- [Overview](https://dart.dev/tools)
- Editors & debuggersexpand\_more
- [IntelliJ & Android Studio](https://dart.dev/tools/jetbrains-plugin)
- [VS Code](https://dart.dev/tools/vs-code)
- [Troubleshoot analyzer performance](https://dart.dev/tools/analyzer-performance)
- [Dart DevTools](https://dart.dev/tools/dart-devtools)
- DartPadexpand\_more
- [Overview](https://dart.dev/tools/dartpad)
- [Troubleshooting DartPad](https://dart.dev/tools/dartpad/troubleshoot)
- Command-line toolsexpand\_more
- Dart SDKexpand\_more
- [Overview](https://dart.dev/tools/sdk)
- [dart](https://dart.dev/tools/dart-tool)
- [dart analyze](https://dart.dev/tools/dart-analyze)
- [dart build](https://dart.dev/tools/dart-build)
- [dart compile](https://dart.dev/tools/dart-compile)
- [dart create](https://dart.dev/tools/dart-create)
- [dart doc](https://dart.dev/tools/dart-doc)
- [dart fix](https://dart.dev/tools/dart-fix)
- [dart format](https://dart.dev/tools/dart-format)
- [dart info](https://dart.dev/tools/dart-info)
- [dart install](https://dart.dev/tools/dart-install)
- [dart pub](https://dart.dev/tools/pub/cmd)
- [dart run](https://dart.dev/tools/dart-run)
- [dart test](https://dart.dev/tools/dart-test)
- [dartaotruntime](https://dart.dev/tools/dartaotruntime)
- [Experiment flags](https://dart.dev/tools/experiment-flags)
- Other command-line toolsexpand\_more
- [build\_runner](https://dart.dev/tools/build_runner)
- [webdev](https://dart.dev/tools/webdev)
- Static analysisexpand\_more
- [Customizing static analysis](https://dart.dev/tools/analysis)
- [Fixing type promotion failures](https://dart.dev/tools/non-promotion-reasons)
- [Linter rules](https://dart.dev/tools/linter-rules)
- [Analyzer plugins](https://dart.dev/tools/analyzer-plugins)
- [Diagnostic messages](https://dart.dev/tools/diagnostics)
- Testing & optimizationexpand\_more
- [Testing](https://dart.dev/tools/testing)
- [Debugging web apps](https://dart.dev/web/debugging)
- Learn Dartexpand\_more
- [Overview](https://dart.dev/learn)
- [Tutorial](https://dart.dev/learn/tutorial)
- Build with AIexpand\_more
- [Dart and Flutter MCP serveropen\_in\_new](https://docs.flutter.dev/ai/mcp-server)
- [Genkit for Dartopen\_in\_new](https://genkit.dev/docs/dart/get-started/)
- Stay up to dateexpand\_more
- [Dart Blogopen\_in\_new](https://blog.dart.dev/)
- [Changelog](https://dart.dev/changelog)
- [What's new in the docs](https://dart.dev/resources/whats-new)
- Resourcesexpand\_more
- [Language cheatsheet](https://dart.dev/resources/dart-cheatsheet)
- [Language specification](https://dart.dev/resources/language/spec)
- [Dart 3 migration guide](https://dart.dev/resources/dart-3-migration)
- [Glossary](https://dart.dev/resources/glossary)
- [Books](https://dart.dev/resources/books)
- [Videos](https://dart.dev/resources/videos)
- Related sitesexpand\_more
- [API referenceopen\_in\_new](https://api.dart.dev/)
- [DartPad (online editor)open\_in\_new](https://dartpad.dev/)
- [Flutteropen\_in\_new](https://flutter.dev/)
- [Package siteopen\_in\_new](https://pub.dev/)
listOn this page chevron\_rightIntroduction to Dart
[vertical\_align\_top Introduction to Dart](https://dart.dev/language#site-content-title)
- [Hello World](https://dart.dev/language#hello-world)
- [Variables](https://dart.dev/language#variables)
- [Control flow statements](https://dart.dev/language#control-flow-statements)
- [Functions](https://dart.dev/language#functions)
- [Comments](https://dart.dev/language#comments)
- [Imports](https://dart.dev/language#imports)
- [Classes](https://dart.dev/language#classes)
- [Enums](https://dart.dev/language#enums)
- [Inheritance](https://dart.dev/language#inheritance)
- [Mixins](https://dart.dev/language#mixins)
- [Interfaces and abstract classes](https://dart.dev/language#interfaces-and-abstract-classes)
- [Async](https://dart.dev/language#async)
- [Exceptions](https://dart.dev/language#exceptions)
- [Important concepts](https://dart.dev/language#important-concepts)
- [Additional resources](https://dart.dev/language#additional-resources)
Dart 3.11 is live! [Learn more](https://blog.dart.dev/announcing-dart-3-11-b6529be4203a)
listOn this page
- [Hello World](https://dart.dev/language#hello-world)
- [Variables](https://dart.dev/language#variables)
- [Control flow statements](https://dart.dev/language#control-flow-statements)
- [Functions](https://dart.dev/language#functions)
- [Comments](https://dart.dev/language#comments)
- [Imports](https://dart.dev/language#imports)
- [Classes](https://dart.dev/language#classes)
- [Enums](https://dart.dev/language#enums)
- [Inheritance](https://dart.dev/language#inheritance)
- [Mixins](https://dart.dev/language#mixins)
- [Interfaces and abstract classes](https://dart.dev/language#interfaces-and-abstract-classes)
- [Async](https://dart.dev/language#async)
- [Exceptions](https://dart.dev/language#exceptions)
- [Important concepts](https://dart.dev/language#important-concepts)
- [Additional resources](https://dart.dev/language#additional-resources)
1. [Language](https://dart.dev/language)
# Introduction to Dart
A brief introduction to Dart programs and important concepts.
more\_vert
- copyCopy link
- [docsView source](https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md)
- [bug\_reportReport issue](https://github.com/dart-lang/site-www/issues/new?template=1_page_issue.yml&page-url=https://dart.dev/language&page-source=https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md)
This page provides a brief introduction to the Dart language through samples of its main features.
To learn more about the Dart language, visit the in-depth, individual topic pages listed under **Language** in the left side menu.
For coverage of Dart's core libraries, check out the [core library documentation](https://dart.dev/libraries). You can also check out the [Dart cheatsheet](https://dart.dev/resources/dart-cheatsheet), for a more interactive introduction.
## Hello World
[\#](https://dart.dev/language#hello-world)
Every app requires the top-level `main()` function, where execution starts. Functions that don't explicitly return a value have the `void` return type. To display text on the console, you can use the top-level `print()` function:
dart
```
void main() {
print('Hello, World!');
}
```
content\_copy
Read more about [the `main()` function](https://dart.dev/language/functions#the-main-function) in Dart, including optional parameters for command-line arguments.
## Variables
[\#](https://dart.dev/language#variables)
Even in [type-safe](https://dart.dev/language/type-system) Dart code, you can declare most variables without explicitly specifying their type using `var`. Thanks to type inference, these variables' types are determined by their initial values:
dart
```
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg',
};
```
content\_copy
[Read more](https://dart.dev/language/variables) about variables in Dart, including default values, the `final` and `const` keywords, and static types.
## Control flow statements
[\#](https://dart.dev/language#control-flow-statements)
Dart supports the usual control flow statements:
dart
```
if (year >= 2001) {
print('21st century');
} else if (year >= 1901) {
print('20th century');
}
for (final object in flybyObjects) {
print(object);
}
for (int month = 1; month <= 12; month++) {
print(month);
}
while (year < 2016) {
year += 1;
}
```
content\_copy
Read more about control flow statements in Dart, including [`break` and `continue`](https://dart.dev/language/loops), [`switch` and `case`](https://dart.dev/language/branches), and [`assert`](https://dart.dev/language/error-handling#assert).
## Functions
[\#](https://dart.dev/language#functions)
[We recommend](https://dart.dev/effective-dart/design#types) specifying the types of each function's arguments and return value:
dart
```
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
```
content\_copy
A shorthand `=>` (*arrow*) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:
dart
```
flybyObjects.where((name) => name.contains('turn')).forEach(print);
```
content\_copy
Besides showing an anonymous function (the argument to `where()`), this code shows that you can use a function as an argument: the top-level `print()` function is an argument to `forEach()`.
[Read more](https://dart.dev/language/functions) about functions in Dart, including optional parameters, default parameter values, and lexical scope.
## Comments
[\#](https://dart.dev/language#comments)
Dart comments usually start with `//`.
dart
```
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/* Comments like these are also supported. */
```
content\_copy
[Read more](https://dart.dev/language/comments) about comments in Dart, including how the documentation tooling works.
## Imports
[\#](https://dart.dev/language#imports)
To access APIs defined in other libraries, use `import`.
dart
```
// Importing core libraries
import 'dart:math';
// Importing libraries from external packages
import 'package:test/test.dart';
// Importing files
import 'path/to/my_other_file.dart';
```
content\_copy
[Read more](https://dart.dev/language/libraries) about libraries and visibility in Dart, including library prefixes, `show` and `hide`, and lazy loading through the `deferred` keyword.
## Classes
[\#](https://dart.dev/language#classes)
Here's an example of a class with three properties, two constructors, and a method. One of the properties can't be set directly, so it's defined using a getter method (instead of a variable). The method uses string interpolation to print variables' string equivalents inside of string literals.
dart
```
class Spacecraft {
String name;
DateTime? launchDate;
// Read-only non-final property
int? get launchYear => launchDate?.year;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
// Method.
void describe() {
print('Spacecraft: $name');
// Type promotion doesn't work on getters.
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
```
content\_copy
[Read more](https://dart.dev/language/built-in-types#strings) about strings, including string interpolation, literals, expressions, and the `toString()` method.
You might use the `Spacecraft` class like this:
dart
```
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();
var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();
```
content\_copy
[Read more](https://dart.dev/language/classes) about classes in Dart, including initializer lists, optional `new` and `const`, redirecting constructors, `factory` constructors, getters, setters, and much more.
## Enums
[\#](https://dart.dev/language#enums)
Enums are a way of enumerating a predefined set of values or instances in a way which ensures that there cannot be any other instances of that type.
Here is an example of a simple `enum` that defines a simple list of predefined planet types:
dart
```
enum PlanetType { terrestrial, gas, ice }
```
content\_copy
Here is an example of an enhanced enum declaration of a class describing planets, with a defined set of constant instances, namely the planets of our own solar system.
dart
```
/// Enum that enumerates the different planets in our solar system
/// and some of their properties.
enum Planet {
mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
// ···
uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);
/// A constant generating constructor
const Planet({
required this.planetType,
required this.moons,
required this.hasRings,
});
/// All instance variables are final
final PlanetType planetType;
final int moons;
final bool hasRings;
/// Enhanced enums support getters and other methods
bool get isGiant =>
planetType == PlanetType.gas || planetType == PlanetType.ice;
}
```
content\_copy
You might use the `Planet` enum like this:
dart
```
final yourPlanet = Planet.earth;
if (!yourPlanet.isGiant) {
print('Your planet is not a "giant planet".');
}
```
content\_copy
When the compiler can infer the enum type from the context, you can use the more concise dot-shorthand syntax to access enum values. Instead of writing the full `EnumName.value`, you can just write `.value`. This can make your code cleaner and easier to read.
For example, when declaring a variable with an explicit type of `Planet`, you can omit the enum name because the type of `Planet` is already established:
dart
```
// Instead of the full, explicit syntax:
Planet myPlanet = Planet.venus;
// You can use a dot shorthand:
Planet myPlanet = .venus;
```
content\_copy
Dot shorthands aren't limited to variable declarations. They can also be used in contexts like function arguments and switch cases where the enum type is clear to the compiler.
[Read more](https://dart.dev/language/enums) about enums in Dart, including enhanced enum requirements, automatically introduced properties, accessing enumerated value names, switch statement support, and much more. [Read more](https://dart.dev/language/dot-shorthands) about dot shorthand syntax.
## Inheritance
[\#](https://dart.dev/language#inheritance)
Dart has single inheritance.
dart
```
class Orbiter extends Spacecraft {
double altitude;
Orbiter(super.name, DateTime super.launchDate, this.altitude);
}
```
content\_copy
[Read more](https://dart.dev/language/extend) about extending classes, the optional `@override` annotation, and more.
## Mixins
[\#](https://dart.dev/language#mixins)
Mixins are a way of reusing code in multiple class hierarchies. The following is a mixin declaration:
dart
```
mixin Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}
```
content\_copy
To add a mixin's capabilities to a class, just extend the class with the mixin.
dart
```
class PilotedCraft extends Spacecraft with Piloted {
// ···
}
```
content\_copy
`PilotedCraft` now has the `astronauts` field as well as the `describeCrew()` method.
[Read more](https://dart.dev/language/mixins) about mixins.
## Interfaces and abstract classes
[\#](https://dart.dev/language#interfaces-and-abstract-classes)
All classes implicitly define an interface. Therefore, you can implement any class.
dart
```
class MockSpaceship implements Spacecraft {
// ···
}
```
content\_copy
Read more about [implicit interfaces](https://dart.dev/language/classes#implicit-interfaces), or about the explicit [`interface` keyword](https://dart.dev/language/class-modifiers#interface).
You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).
dart
```
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
```
content\_copy
Any class extending `Describable` has the `describeWithEmphasis()` method, which calls the extender's implementation of `describe()`.
[Read more](https://dart.dev/language/class-modifiers#abstract) about abstract classes and methods.
## Async
[\#](https://dart.dev/language#async)
Avoid callback hell and make your code much more readable by using `async` and `await`.
dart
```
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
```
content\_copy
The method above is equivalent to:
dart
```
Future<void> printWithDelay(String message) {
return Future.delayed(oneSecond).then((_) {
print(message);
});
}
```
content\_copy
As the next example shows, `async` and `await` help make asynchronous code easy to read.
dart
```
Future<void> createDescriptions(Iterable<String> objects) async {
for (final object in objects) {
try {
var file = File('$object.txt');
if (await file.exists()) {
var modified = await file.lastModified();
print(
'File for $object already exists. It was modified on $modified.',
);
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch (e) {
print('Cannot create description for $object: $e');
}
}
}
```
content\_copy
You can also use `async*`, which gives you a nice, readable way to build streams.
dart
```
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (final object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
```
content\_copy
[Read more](https://dart.dev/language/async) about asynchrony support, including `async` functions, `Future`, `Stream`, and the asynchronous loop (`await for`).
## Exceptions
[\#](https://dart.dev/language#exceptions)
To raise an exception, use `throw`:
dart
```
if (astronauts == 0) {
throw StateError('No astronauts.');
}
```
content\_copy
To catch an exception, use a `try` statement with `on` or `catch` (or both):
dart
```
Future<void> describeFlybyObjects(List<String> flybyObjects) async {
try {
for (final object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} onIOExceptioncatch(e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}
}
```
content\_copy
Note that the code above is asynchronous; `try` works for both synchronous and asynchronous code in an `async` function.
[Read more](https://dart.dev/language/error-handling#exceptions) about exceptions, including stack traces, `rethrow`, and the difference between `Error` and `Exception`.
## Important concepts
[\#](https://dart.dev/language#important-concepts)
As you continue to learn about the Dart language, keep these facts and concepts in mind:
- Everything you can place in a variable is an *object*, and every object is an instance of a *class*. Even numbers, functions, and `null` are objects. With the exception of `null` (if you enable [sound null safety](https://dart.dev/null-safety)), all objects inherit from the [`Object`](https://api.dart.dev/dart-core/Object-class.html) class.
merge\_typeVersion note
[Null safety](https://dart.dev/null-safety) was introduced in Dart 2.12. Using null safety requires a [language version](https://dart.dev/resources/language/evolution#language-versioning) of at least 2.12.
- Although Dart is strongly typed, type annotations are optional because Dart can infer types. In `var number = 101`, `number` is inferred to be of type `int`.
- Variables can't contain `null` unless you say they can. You can make a variable nullable by putting a question mark (`?`) at the end of its type. For example, a variable of type `int?` might be an integer, or it might be `null`. If you *know* that an expression never evaluates to `null` but Dart disagrees, you can add `!` to assert that it isn't null (and to throw an exception if it is). An example: `int x = nullableButNotNullInt!`
- When you want to explicitly say that any type is allowed, use the type `Object?` (if you've enabled null safety), `Object`, or—if you must defer type checking until runtime—the [special type `dynamic`](https://dart.dev/effective-dart/design#avoid-using-dynamic-unless-you-want-to-disable-static-checking).
- Dart supports generic types, like `List<int>` (a list of integers) or `List<Object>` (a list of objects of any type).
- Dart supports top-level functions (such as `main()`), as well as functions tied to a class or object (*static* and *instance methods*, respectively). You can also create functions within functions (*nested* or *local functions*).
- Similarly, Dart supports top-level *variables*, as well as variables tied to a class or object (static and instance variables). Instance variables are sometimes known as *fields* or *properties*.
- Unlike Java, Dart doesn't have the keywords `public`, `protected`, and `private`. If an identifier starts with an underscore (`_`), it's private to its library. For details, see [Libraries and imports](https://dart.dev/language/libraries).
- *Identifiers* can start with a letter or underscore (`_`), followed by any combination of those characters plus digits.
- Dart has both *expressions* (which have runtime values) and *statements* (which don't). For example, the [conditional expression](https://dart.dev/language/operators#conditional-expressions) `condition ? expr1 : expr2` has a value of `expr1` or `expr2`. Compare that to an [if-else statement](https://dart.dev/language/branches#if), which has no value. A statement often contains one or more expressions, but an expression can't directly contain a statement.
- Dart tools can report two kinds of problems: *warnings* and *errors*. Warnings are just indications that your code might not work, but they don't prevent your program from executing. Errors can be either compile-time or run-time. A compile-time error prevents the code from executing at all; a run-time error results in an [exception](https://dart.dev/language/error-handling#exceptions) being raised while the code executes.
## Additional resources
[\#](https://dart.dev/language#additional-resources)
You can find more documentation and code samples in the [core library documentation](https://dart.dev/libraries/dart-core) and the [Dart API reference](https://api.dart.dev/). This site's code follows the conventions in the [Dart style guide](https://dart.dev/effective-dart/style).
[Next Variables chevron\_right](https://dart.dev/language/variables)
Was this page's content helpful?
thumb\_up
thumb\_down
Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Page last updated on 2025-12-16. [View source](https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md) or [report an issue](https://github.com/dart-lang/site-www/issues/new?template=1_page_issue.yml&page-url=https://dart.dev/language&page-source=https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md "Report an issue with this page").
[](https://dart.dev/ "Dart")
Except as otherwise noted, this site is licensed under a [Creative Commons Attribution 4.0 International License,](https://creativecommons.org/licenses/by/4.0/) and code samples are licensed under the [3-Clause BSD License.](https://opensource.org/licenses/BSD-3-Clause)
- [Terms](https://dart.dev/terms "Terms of use")
- [Privacy](https://policies.google.com/privacy "Privacy policy")
- [Security](https://dart.dev/security "Security philosophy and practices") |
| Readable Markdown | 1. [Language](https://dart.dev/language)
A brief introduction to Dart programs and important concepts.
This page provides a brief introduction to the Dart language through samples of its main features.
To learn more about the Dart language, visit the in-depth, individual topic pages listed under **Language** in the left side menu.
For coverage of Dart's core libraries, check out the [core library documentation](https://dart.dev/libraries). You can also check out the [Dart cheatsheet](https://dart.dev/resources/dart-cheatsheet), for a more interactive introduction.
## Hello World
[\#](https://dart.dev/language#hello-world)
Every app requires the top-level `main()` function, where execution starts. Functions that don't explicitly return a value have the `void` return type. To display text on the console, you can use the top-level `print()` function:
dart
```
void main() {
print('Hello, World!');
}
```
Read more about [the `main()` function](https://dart.dev/language/functions#the-main-function) in Dart, including optional parameters for command-line arguments.
## Variables
[\#](https://dart.dev/language#variables)
Even in [type-safe](https://dart.dev/language/type-system) Dart code, you can declare most variables without explicitly specifying their type using `var`. Thanks to type inference, these variables' types are determined by their initial values:
dart
```
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg',
};
```
[Read more](https://dart.dev/language/variables) about variables in Dart, including default values, the `final` and `const` keywords, and static types.
## Control flow statements
[\#](https://dart.dev/language#control-flow-statements)
Dart supports the usual control flow statements:
dart
```
if (year >= 2001) {
print('21st century');
} else if (year >= 1901) {
print('20th century');
}
for (final object in flybyObjects) {
print(object);
}
for (int month = 1; month <= 12; month++) {
print(month);
}
while (year < 2016) {
year += 1;
}
```
Read more about control flow statements in Dart, including [`break` and `continue`](https://dart.dev/language/loops), [`switch` and `case`](https://dart.dev/language/branches), and [`assert`](https://dart.dev/language/error-handling#assert).
## Functions
[\#](https://dart.dev/language#functions)
[We recommend](https://dart.dev/effective-dart/design#types) specifying the types of each function's arguments and return value:
dart
```
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
```
A shorthand `=>` (*arrow*) syntax is handy for functions that contain a single statement. This syntax is especially useful when passing anonymous functions as arguments:
dart
```
flybyObjects.where((name) => name.contains('turn')).forEach(print);
```
Besides showing an anonymous function (the argument to `where()`), this code shows that you can use a function as an argument: the top-level `print()` function is an argument to `forEach()`.
[Read more](https://dart.dev/language/functions) about functions in Dart, including optional parameters, default parameter values, and lexical scope.
Dart comments usually start with `//`.
dart
```
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/* Comments like these are also supported. */
```
[Read more](https://dart.dev/language/comments) about comments in Dart, including how the documentation tooling works.
To access APIs defined in other libraries, use `import`.
dart
```
// Importing core libraries
import 'dart:math';
// Importing libraries from external packages
import 'package:test/test.dart';
// Importing files
import 'path/to/my_other_file.dart';
```
[Read more](https://dart.dev/language/libraries) about libraries and visibility in Dart, including library prefixes, `show` and `hide`, and lazy loading through the `deferred` keyword.
Here's an example of a class with three properties, two constructors, and a method. One of the properties can't be set directly, so it's defined using a getter method (instead of a variable). The method uses string interpolation to print variables' string equivalents inside of string literals.
dart
```
class Spacecraft {
String name;
DateTime? launchDate;
// Read-only non-final property
int? get launchYear => launchDate?.year;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
// Method.
void describe() {
print('Spacecraft: $name');
// Type promotion doesn't work on getters.
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
```
[Read more](https://dart.dev/language/built-in-types#strings) about strings, including string interpolation, literals, expressions, and the `toString()` method.
You might use the `Spacecraft` class like this:
dart
```
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();
var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();
```
[Read more](https://dart.dev/language/classes) about classes in Dart, including initializer lists, optional `new` and `const`, redirecting constructors, `factory` constructors, getters, setters, and much more.
Enums are a way of enumerating a predefined set of values or instances in a way which ensures that there cannot be any other instances of that type.
Here is an example of a simple `enum` that defines a simple list of predefined planet types:
dart
```
enum PlanetType { terrestrial, gas, ice }
```
Here is an example of an enhanced enum declaration of a class describing planets, with a defined set of constant instances, namely the planets of our own solar system.
dart
```
/// Enum that enumerates the different planets in our solar system
/// and some of their properties.
enum Planet {
mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
// ···
uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);
/// A constant generating constructor
const Planet({
required this.planetType,
required this.moons,
required this.hasRings,
});
/// All instance variables are final
final PlanetType planetType;
final int moons;
final bool hasRings;
/// Enhanced enums support getters and other methods
bool get isGiant =>
planetType == PlanetType.gas || planetType == PlanetType.ice;
}
```
You might use the `Planet` enum like this:
dart
```
final yourPlanet = Planet.earth;
if (!yourPlanet.isGiant) {
print('Your planet is not a "giant planet".');
}
```
When the compiler can infer the enum type from the context, you can use the more concise dot-shorthand syntax to access enum values. Instead of writing the full `EnumName.value`, you can just write `.value`. This can make your code cleaner and easier to read.
For example, when declaring a variable with an explicit type of `Planet`, you can omit the enum name because the type of `Planet` is already established:
dart
```
// Instead of the full, explicit syntax:
Planet myPlanet = Planet.venus;
// You can use a dot shorthand:
Planet myPlanet = .venus;
```
Dot shorthands aren't limited to variable declarations. They can also be used in contexts like function arguments and switch cases where the enum type is clear to the compiler.
[Read more](https://dart.dev/language/enums) about enums in Dart, including enhanced enum requirements, automatically introduced properties, accessing enumerated value names, switch statement support, and much more. [Read more](https://dart.dev/language/dot-shorthands) about dot shorthand syntax.
## Inheritance
[\#](https://dart.dev/language#inheritance)
Dart has single inheritance.
dart
```
class Orbiter extends Spacecraft {
double altitude;
Orbiter(super.name, DateTime super.launchDate, this.altitude);
}
```
[Read more](https://dart.dev/language/extend) about extending classes, the optional `@override` annotation, and more.
Mixins are a way of reusing code in multiple class hierarchies. The following is a mixin declaration:
dart
```
mixin Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}
```
To add a mixin's capabilities to a class, just extend the class with the mixin.
dart
```
class PilotedCraft extends Spacecraft with Piloted {
// ···
}
```
`PilotedCraft` now has the `astronauts` field as well as the `describeCrew()` method.
[Read more](https://dart.dev/language/mixins) about mixins.
## Interfaces and abstract classes
[\#](https://dart.dev/language#interfaces-and-abstract-classes)
All classes implicitly define an interface. Therefore, you can implement any class.
dart
```
class MockSpaceship implements Spacecraft {
// ···
}
```
Read more about [implicit interfaces](https://dart.dev/language/classes#implicit-interfaces), or about the explicit [`interface` keyword](https://dart.dev/language/class-modifiers#interface).
You can create an abstract class to be extended (or implemented) by a concrete class. Abstract classes can contain abstract methods (with empty bodies).
dart
```
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
```
Any class extending `Describable` has the `describeWithEmphasis()` method, which calls the extender's implementation of `describe()`.
[Read more](https://dart.dev/language/class-modifiers#abstract) about abstract classes and methods.
Avoid callback hell and make your code much more readable by using `async` and `await`.
dart
```
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
```
The method above is equivalent to:
dart
```
Future<void> printWithDelay(String message) {
return Future.delayed(oneSecond).then((_) {
print(message);
});
}
```
As the next example shows, `async` and `await` help make asynchronous code easy to read.
dart
```
Future<void> createDescriptions(Iterable<String> objects) async {
for (final object in objects) {
try {
var file = File('$object.txt');
if (await file.exists()) {
var modified = await file.lastModified();
print(
'File for $object already exists. It was modified on $modified.',
);
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch (e) {
print('Cannot create description for $object: $e');
}
}
}
```
You can also use `async*`, which gives you a nice, readable way to build streams.
dart
```
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (final object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
```
[Read more](https://dart.dev/language/async) about asynchrony support, including `async` functions, `Future`, `Stream`, and the asynchronous loop (`await for`).
## Exceptions
[\#](https://dart.dev/language#exceptions)
To raise an exception, use `throw`:
dart
```
if (astronauts == 0) {
throw StateError('No astronauts.');
}
```
To catch an exception, use a `try` statement with `on` or `catch` (or both):
dart
```
Future<void> describeFlybyObjects(List<String> flybyObjects) async {
try {
for (final object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} onIOExceptioncatch(e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}
}
```
Note that the code above is asynchronous; `try` works for both synchronous and asynchronous code in an `async` function.
[Read more](https://dart.dev/language/error-handling#exceptions) about exceptions, including stack traces, `rethrow`, and the difference between `Error` and `Exception`.
## Important concepts
[\#](https://dart.dev/language#important-concepts)
As you continue to learn about the Dart language, keep these facts and concepts in mind:
- Everything you can place in a variable is an *object*, and every object is an instance of a *class*. Even numbers, functions, and `null` are objects. With the exception of `null` (if you enable [sound null safety](https://dart.dev/null-safety)), all objects inherit from the [`Object`](https://api.dart.dev/dart-core/Object-class.html) class.
- Although Dart is strongly typed, type annotations are optional because Dart can infer types. In `var number = 101`, `number` is inferred to be of type `int`.
- Variables can't contain `null` unless you say they can. You can make a variable nullable by putting a question mark (`?`) at the end of its type. For example, a variable of type `int?` might be an integer, or it might be `null`. If you *know* that an expression never evaluates to `null` but Dart disagrees, you can add `!` to assert that it isn't null (and to throw an exception if it is). An example: `int x = nullableButNotNullInt!`
- When you want to explicitly say that any type is allowed, use the type `Object?` (if you've enabled null safety), `Object`, or—if you must defer type checking until runtime—the [special type `dynamic`](https://dart.dev/effective-dart/design#avoid-using-dynamic-unless-you-want-to-disable-static-checking).
- Dart supports generic types, like `List<int>` (a list of integers) or `List<Object>` (a list of objects of any type).
- Dart supports top-level functions (such as `main()`), as well as functions tied to a class or object (*static* and *instance methods*, respectively). You can also create functions within functions (*nested* or *local functions*).
- Similarly, Dart supports top-level *variables*, as well as variables tied to a class or object (static and instance variables). Instance variables are sometimes known as *fields* or *properties*.
- Unlike Java, Dart doesn't have the keywords `public`, `protected`, and `private`. If an identifier starts with an underscore (`_`), it's private to its library. For details, see [Libraries and imports](https://dart.dev/language/libraries).
- *Identifiers* can start with a letter or underscore (`_`), followed by any combination of those characters plus digits.
- Dart has both *expressions* (which have runtime values) and *statements* (which don't). For example, the [conditional expression](https://dart.dev/language/operators#conditional-expressions) `condition ? expr1 : expr2` has a value of `expr1` or `expr2`. Compare that to an [if-else statement](https://dart.dev/language/branches#if), which has no value. A statement often contains one or more expressions, but an expression can't directly contain a statement.
- Dart tools can report two kinds of problems: *warnings* and *errors*. Warnings are just indications that your code might not work, but they don't prevent your program from executing. Errors can be either compile-time or run-time. A compile-time error prevents the code from executing at all; a run-time error results in an [exception](https://dart.dev/language/error-handling#exceptions) being raised while the code executes.
## Additional resources
[\#](https://dart.dev/language#additional-resources)
You can find more documentation and code samples in the [core library documentation](https://dart.dev/libraries/dart-core) and the [Dart API reference](https://api.dart.dev/). This site's code follows the conventions in the [Dart style guide](https://dart.dev/effective-dart/style).
[Next Variables](https://dart.dev/language/variables)
Was this page's content helpful?
Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Page last updated on 2025-12-16. [View source](https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md) or [report an issue](https://github.com/dart-lang/site-www/issues/new?template=1_page_issue.yml&page-url=https://dart.dev/language&page-source=https://github.com/dart-lang/site-www/blob/main/src/content/language/index.md "Report an issue with this page"). |
| Shard | 167 (laksa) |
| Root Hash | 2534673344912997567 |
| Unparsed URL | dev,dart!/language s443 |