DEV Community

Amr Azzam
Amr Azzam

Posted on

4

Mastering Dart Operators!

When working with Dart in Flutter, operators make our code cleaner, more efficient, and expressive!
Let's explore some of the most useful ones with examples.

1️⃣ Null-aware operators (??, ??=, ?.)
Dart makes handling null values easy:

String? name;
print(name ?? 'Guest'); // ➡️ 'Guest' (uses default if null)

name ??= 'John'; // Assigns 'John' only if name is null
print(name); // ➡️ 'John'

int? length = name?.length; // Safe null access
print(length); // ➡️ 4
Enter fullscreen mode Exit fullscreen mode

2️⃣ Spread (...) and Null-aware Spread (...?)
Great for working with collections:

List<int> numbers = [1, 2, 3];
List<int>? nullableList;

List<int> allNumbers = [0, ...numbers, 4, ...?nullableList];
print(allNumbers); // ➡️ [0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

3️⃣ Cascade (..) Operator
Used for chaining method calls:

final controller = TextEditingController()
  ..text = "Hello, Flutter!"
  ..selection = TextSelection.collapsed(offset: 5);
Enter fullscreen mode Exit fullscreen mode

4️⃣ Ternary (? :) & Null-aware Conditional (??)
Simplifies conditional expressions:

int age = 18;
String status = age >= 18 ? 'Adult' : 'Minor';
print(status); // ➡️ 'Adult'
Enter fullscreen mode Exit fullscreen mode

5️⃣ Null Check (!) Operator
Used when you're sure a value isn’t null:

String? nullableString = "Dart";
String nonNullable = nullableString!;
print(nonNullable.length); // ➡️ 4
Enter fullscreen mode Exit fullscreen mode

Operators make Dart code cleaner, safer, and more readable—a must for any Flutter Developer! 🚀

Which operator is your favorite? Drop your thoughts in the comments! 💬👇

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

🌶️ Newest Episode of Leet Heat: A Game Show For Developers!

Contestants face rapid-fire full stack web dev questions. Wrong answers? The spice level goes up. Can they keep cool while eating progressively hotter sauces?

View Episode Post

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️