Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Variables and Data Types

Dart Variables and Data Types

Variables are the basic units for storing data in a program, and data types determine what values a variable can store.

This chapter introduces variable declaration in Dart, basic data types, and the important null safety mechanism.


Ways to declare variables: var, final, const

Dart provides three keywords for declaring variables, each suited to different scenarios.

Understanding their differences is the first step to learning Dart well.

var--type-inferred variable

A variable declared with var has its type automatically inferred from the initial value, and once the type is determined it cannot be changed.

Example

void

main

(

)

{

 

// type inference: the type of name is inferred as String

 

var

name

=

'RUNOOB'

;

 

// type inference: the type of age is inferred as int

 

var

age

=

10

;

  print

(

'$name has been $age years'

)

;

 

// the following will cause an error--once the type is determined, values of other types cannot be assigned

 

// name = 123; // error: cannot assign an int to a String

}



RUNOOB 已经 10 年了

var is not "untyped" or "dynamically typed"; its type is fixed the moment it is assigned. This is completely different from JavaScript's var.

final--runtime constant

A variable declared with final can only be assigned once, but the assignment can be deferred until runtime.

Example

void

main

(

)

{

 

// final variable: once assigned, it cannot be modified

 

final

currentTime

=

DateTime.

now

(

)

;

  print

(

'Current time: $currentTime'

)

;

 

// deferred assignment is also allowed

 

final

String greeting

;

  greeting

=

'Hello, RUNOOB!'

;

 

// first assignment OK

 

// greeting = 'Hello again'; // error: a final variable cannot be assigned again

  print

(

greeting

)

;

}



当前时间: 2026-06-12 10:30:00.000

Hello, RUNOOB!

const--compile-time constant

const is stricter than final: its value must be determinable at compile time.

Example

void

main

(

)

{

 

// const must have a value determinable at compile time

 

const

siteName

=

'RUNOOB'

;

 

const

maxUsers

=

100

;

  print

(

'Site: $siteName, max users: $maxUsers'

)

;

 

// the following will cause an error--DateTime.now() is a value only determinable at runtime

 

// const currentTime = DateTime.now(); // error!

}



站点: RUNOOB, 最大用户数: 100

Summary comparison of the three

The keyword Modifiable Assignment timing Typical scenario
var You can Any Ordinary variables whose value changes
final Not modifiable Determined at runtime Configuration fetched from an API, current time
const Not modifiable Determined at compile time Mathematical constants, fixed configuration, color values

A practical tip: use final by default. When you find you need to modify it, change it to var. This habit makes code safer and reduces bugs caused by accidental modification.


Numeric types: int and double

Dart's numeric types are divided into two: int (integers) and double (floating-point numbers).

Their common superclass is num.

Example

void

main

(

)

{

 

// int: integer, range is -2^63 to 2^63-1

 

int

viewCount

=

10000

;

 

int

negativeNumber

=

42

;

 

// double: double-precision floating-point number

 

double

price

=

9.99

;

 

double

pi

=

3.1415926

;

 

// num can accept both int and double

 

num

someNumber

=

10

;

  someNumber

=

10.5

;

 

// valid

  print

(

'View count: $viewCount'

)

;

  print

(

'Price: ¥$price'

)

;

  print

(

'Pi: $pi'

)

;

}



浏览次数: 10000

价格: ¥9.99

圆周率: 3.1415926

Common numeric methods

Example

import

'dart:math'

;

 

// import the math library

void

main

(

)

{

 

int

a

=

10

;

 

double

b

=

3.7

;

 

// absolute value

  print

(

'absolute value of a: ${a.abs()}'

)

;

 

// 10

 

// round to nearest integer

  print

(

'b rounded: ${b.round()}'

)

;

 

// 4

 

// floor

  print

(

'b floor: ${b.floor()}'

)

;

 

// 3

 

// ceil

  print

(

'b ceil: ${b.ceil()}'

)

;

 

// 4

 

// string to number

 

int

parsed

=

int

.

parse

(

'42'

)

;

 

double

parsedDouble

=

double

.

parse

(

'3.14'

)

;

  print

(

'Parsing result: $parsed, $parsedDouble'

)

;

 

// generate a random number (requires import 'dart:math')

 

var

random

=

Random

(

)

.

nextInt

(

100

)

;

  print

(

'Random number (0-99): $random'

)

;

}



a 的绝对值: 10

b 四舍五入: 4

b 向下取整: 3

b 向上取整: 4

解析结果: 42, 3.14

随机数(0-99): 67


Strings: String and interpolation syntax

String is used to represent text, and Dart's strings support both single and double quotes.

String interpolation is one of Dart's most convenient features.

Example

void

main

(

)

{

 

// strings can use single or double quotes

  String singleQuoted

=

'Hello'

;

  String doubleQuoted

=

"World"

;

 

// multi-line strings: use triple quotes

  String multiLine

=

''

'
  This is the first line
  This is the second line
  This is the third line - RUNOOB
  '

''

;

 

// string interpolation: use $variable or ${expression}

  String site

=

'RUNOOB'

;

 

int

years

=

10

;

 

// $variable: reference a variable directly

  print

(

'Welcome to $site'

)

;

 

// ${expression}: embed a complex expression

  print

(

'$site has been with us for ${years + 1} years'

)

;

 

// escape characters

  print

(

'Newline character: first line\nsecond line'

)

;

  print

(

'Tab character: column1\tcolumn2'

)

;

}



欢迎来到 RUNOOB

RUNOOB 已经陪伴我们 11 年了

换行符: 第一行

第二行

制表符: 列1    列2

Common string methods

Example

void

main

(

)

{

  String text

=

'  Hello, RUNOOB!  '

;

 

// remove leading and trailing spaces

  print

(

'trim: [${text.trim()}]'

)

;

 

// convert to uppercase / lowercase

  print

(

'Uppercase: ${text.toUpperCase()}'

)

;

  print

(

'Lowercase: ${text.toLowerCase()}'

)

;

 

// whether it contains a certain substring

  print

(

'Contains RUNOOB? ${text.contains('

RUNOOB

')}'

)

;

 

// whether it starts/ends with a certain string

  print

(

'Starts with a space? ${text.startsWith('

')}'

)

;

  print

(

'Ends with !? ${text.trim().endsWith('

!

')}'

)

;

 

// string replacement

  print

(

'Replace: ${text.replaceAll('

RUNOOB

', '

DART

')}'

)

;

 

// string splitting

  String csv

=

'Dart,Flutter,Google'

;

  List

<

String

items

=

csv.

split

(

','

)

;

  print

(

'Split result: $items'

)

;

 

// string concatenation

  print

(

'Concatenation: '

'Hello'

', '

'World'

)

;

}



trim: [Hello, RUNOOB!]

大写:   HELLO, RUNOOB!

小写:   hello, runoob!

包含 RUNOOB? true

以空格开头? true

以!结尾? true

替换:   Hello, DART!

分割结果: [Dart, Flutter, Google]

拼接: Hello, World


Boolean bool

bool has only two values: true and false.

It is mainly used for conditional judgment together with if statements.

Example

void

main

(

)

{

 

bool

isLoggedIn

=

true

;

 

bool

hasPermission

=

false

;

 

// boolean expression

 

bool

canAccess

=

isLoggedIn

&&

hasPermission

;

 

// AND: both are true

 

bool

isGuest

=

!

isLoggedIn

;

                   

// NOT: negation

  print

(

'Can access: $canAccess'

)

;

  print

(

'Is a guest: $isGuest'

)

;

 

// comparison operations produce a bool value

 

int

age

=

20

;

 

bool

isAdult

=

age

=

18

;

  print

(

'Is an adult: $isAdult'

)

;

 

// used directly for conditional judgment

 

if

(

isAdult

)

{

    print

(

'Welcome to RUNOOB'

)

;

 

}

}



可以访问: false

是访客: false

是否成年: true

欢迎访问 RUNOOB

Dart is a strongly typed language; conditional judgments accept only the bool type. This differs from JavaScript--in Dart, writing if(0) or if('') will directly cause an error.


Null Safety

Null safety is the most important feature introduced in Dart 2.12.

Its core idea is: by default, all variables cannot be null unless you explicitly declare them as such.

Nullable and non-nullable types

Adding a ? after the type means the variable can be null.

Example

void

main

(

)

{

 

// non-nullable type: cannot be assigned null

  String name

=

'RUNOOB'

;

 

// name = null; // error! name cannot be null

 

// nullable type: allows null

  String

?

nickname

;

  nickname

=

null

;

 

// OK

  nickname

=

'R'

;

 

// also OK

  print

(

'Nickname: $nickname'

)

;

 

// int? is also nullable

 

int

?

score

;

  print

(

'Score: $score'

)

;

 

// outputs null

}



昵称: R

分数: null

Null-handling operators

Operator Description Example
?? If the left side is null, use the right side value name ?? 'default name'
??= If the variable is null, assign the right side value name ??= 'default name'
?. Safe access: skip the call when the object is null user?.name
! Assert non-null (use with caution) name!

Example

void

main

(

)

{

  String

?

username

;

 

// ?? operator: if username is null, use the default value

  String displayName

=

username

??

'RUNOOB visitor'

;

  print

(

displayName

)

;

 

// RUNOOB visitor

 

// ??= operator: assign if null

  username

??

=

'New user'

;

  print

(

username

)

;

 

// New user

 

// ?. safe access: only call when non-null

  String

?

maybeNull

;

  print

(

maybeNull

?

.

length

)

;

 

// null (no error)

  maybeNull

=

'Hello'

;

  print

(

maybeNull

?

.

length

)

;

 

// 5

 

// ! assertion: I'm sure it's not null (throws when null)

  String definitelyNotNull

=

'RUNOOB'

;

  print

(

definitelyNotNull

!

.

length

)

;

 

// 6

}



RUNOOB 访客

新用户

null

5

6

Try to avoid using the ! assertion operator. If you use ! frequently, it indicates your type design may have a problem. Prefer ??, ??= and ?. to handle null values safely.


Type Conversion

In Dart, values of different types can be converted to each other.

Example

void

main

(

)

{

 

// number -> string

 

int

count

=

42

;

  String countStr

=

count.

toString

(

)

;

  print

(

'Number to string: $countStr (type: ${countStr.runtimeType})'

)

;

 

// string -> number

  String priceStr

=

'19.99'

;

 

double

price

=

double

.

parse

(

priceStr

)

;

  print

(

'String to number: ¥$price'

)

;

 

// int ↔ double

 

int

integer

=

10

;

 

double

decimal

=

integer.

toDouble

(

)

;

  print

(

'int to double: $decimal'

)

;

 

double

pi

=

3.14

;

 

int

piInt

=

pi.

toInt

(

)

;

 

// truncate the decimal part

  print

(

'double to int (truncated): $piInt'

)

;

 

// any value -> string

 

bool

flag

=

true

;

  print

(

'bool to string: ${flag.toString()}'

)

;

 

// string -> bool (requires manual judgment)

  String boolStr

=

'true'

;

 

bool

parsed

=

boolStr

==

'true'

;

  print

(

'String to bool: $parsed'

)

;

}



数字转字符串: 42 (类型: String)

字符串转数字: ¥19.99

int 转 double: 10.0

double 转 int (截断): 3

bool 转字符串: true

字符串转 bool: true