Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Null Safety


Share

Dart Null Safety

null is a special value that means "no value".

In many languages, any variable can be null, and the program crashes when you use it by mistake.

Dart has null safety, which means that a normal variable can never be null.

If you try to put null in a String variable, the program does not run:

Example

void main() {
  String name = null;
  print(name);
}
Try it Yourself »

Result:

main.dart:2:17: Error: A value of type 'Null' can't be assigned to a variable of type 'String'.
  String name = null;
                ^

Dart also checks that a variable has a value before you use it:

Example

void main() {
  int score;
  print(score);
}
Try it Yourself »

Result:

main.dart:3:9: Error: Non-nullable variable 'score' must be assigned before it can be used.
  print(score);
        ^^^^^

Dart finds these mistakes before the program runs, so they cannot crash your program later.


Nullable Types

Sometimes a variable must be allowed to have no value.

Add a question mark ? after the type to make a nullable type.

A String? can hold a string or null:

Example

void main() {
  String? nickname;
  print(nickname);

  nickname = 'Bobby';
  print(nickname);
}
Try it Yourself »

Result:

null
Bobby

A nullable variable that has not been given a value is null.

You can use ? with any type, like int?, double? and bool?.



Why the Compiler Stops You

The compiler is the part of Dart that checks your code before it runs.

It does not let you use a nullable value as if it was a normal value.

In this example, int.tryParse() returns an int?, because the text might not be a number:

Example

void main() {
  int? age = int.tryParse('25');
  print(age + 1);
}
Try it Yourself »

Result:

main.dart:3:13: Error: Operator '+' cannot be called on 'int?' because it is potentially null.
  print(age + 1);
            ^

Dart does not know if age is a number or null, so it does not allow age + 1.


Null Checks and Type Promotion

The safe way is to check for null first, with != null.

Inside the if block, Dart knows that the value is not null:

Example

void main() {
  int? age = int.tryParse('25');

  if (age != null) {
    print(age + 1);
  } else {
    print('Not a number');
  }
}
Try it Yourself »

Result:

26

This is called type promotion.

After the check, Dart treats age as an int, not an int?.

The same code also works when the text is not a number:

Example

void main() {
  int? age = int.tryParse('hello');

  if (age != null) {
    print(age + 1);
  } else {
    print('Not a number');
  }
}
Try it Yourself »

Result:

Not a number

You will learn more about if and else in the If...Else chapter.


The ! Operator

If you are sure that a value is not null, you can add ! after it.

This is called the null assertion operator, and it turns an int? into an int:

Example

void main() {
  int? age = int.tryParse('25');
  print(age! + 1);
}
Try it Yourself »

Result:

26

But if the value is null, the program stops with an error when it runs:

Example

void main() {
  int? age = int.tryParse('hello');
  print(age! + 1);
}
Try it Yourself »

Result:

Unhandled exception:
Null check operator used on a null value

Note: The compiler cannot protect you when you use !.

Use a null check instead whenever you can.


Default Values with ??

The ?? operator gives a default value when a value is null:

Example

void main() {
  String? name;
  String guest = name ?? 'Guest';
  print('Hello, $guest');
}
Try it Yourself »

Result:

Hello, Guest

Dart has more operators for nullable values.

You can read about all of them in the Null-aware Operators chapter.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.