Skip to content

Flutter-Basic-To-Advanace/Null-Safety

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

🛡️ Dart Null Safety

Null Safety in Dart ensures your variables can never be null unless you explicitly allow it.
This helps you avoid the dreaded Null Reference Error at runtime by catching issues at compile time.

In this tutorial, we’ll explore:

  • Non-nullable variables
  • Nullable variables
  • Null-aware operators
  • Null assertion
  • Default values for null

📜 Code Example

void main() {
  // 1️⃣ Null Safety (Non-nullable by default)
  String name = "Kuluni";
  print(name.length);

  // 2️⃣ Nullable vs Non-nullable Variables
  // Non-nullable
  String country = "Sri Lanka";
  print(country);

  // Nullable
  String? nickname;
  nickname = null;
  print(nickname);

  // 3️⃣ Nullable Variables
  String? username = null;
  print(username);

  // 4️⃣ Null-aware Access (?.)
  String? text;
  print(text?.length);

  // 5️⃣ Null-coalescing (??)
  String? names;
  print(name ?? "Guest");

  // 6️⃣ Null Assertion (!)
  String? city = "colombo";
  print(city.length);

  // 7️⃣ Assign if Null (??=)
  String? language;
  language ??= "Dart";
  print(language);
}

--

🖥️ Output

6
Sri Lanka
null
null
null
Kuluni
7
Dart

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages