DEV Community

Amr Azzam
Amr Azzam

Posted on

5

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! 💬👇

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay