Dart Advanced

Master advanced Dart programming concepts

🚀 Advanced Dart Programming

Advanced Dart features include generics, mixins, async programming, and streams. These powerful concepts help you write efficient, scalable, and maintainable code for complex applications.


// Advanced Dart example with generics and async
Future<List<T>> fetchData<T>() async {
  await Future.delayed(Duration(seconds: 1));
  return <T>[];
}
                                    

Advanced Dart Features

🔧

Generics

Type-safe collections and functions

List<String> names = ['Alice', 'Bob'];
🎭

Mixins

Reuse code across multiple classes

mixin Flyable {
  void fly() => print('Flying!');
}
âš¡

Async/Await

Handle asynchronous operations

Future<String> getData() async {
  return await fetchFromAPI();
}
🌊

Streams

Handle continuous data flow

Stream<int> countStream() async* {
  for (int i = 1; i <= 5; i++) {
    yield i;
  }
}

🔹 Generics in Action

Generics allow you to write type-safe, reusable code:

// Generic class
class Box<T> {
  T value;
  Box(this.value);
  
  T getValue() => value;
}

// Usage
void main() {
  var stringBox = Box<String>('Hello');
  var intBox = Box<int>(42);
  
  print(stringBox.getValue()); // Hello
  print(intBox.getValue());    // 42
}

Output:

Hello

42

🔹 Mixins for Code Reuse

Mixins let you share code between classes:

mixin Swimmer {
  void swim() => print('Swimming!');
}

mixin Flyer {
  void fly() => print('Flying!');
}

class Duck with Swimmer, Flyer {
  void quack() => print('Quack!');
}

void main() {
  var duck = Duck();
  duck.swim();  // Swimming!
  duck.fly();   // Flying!
  duck.quack(); // Quack!
}

Output:

Swimming!

Flying!

Quack!

🔹 Async Programming

Handle time-consuming operations without blocking:

Future<String> fetchUserData(int userId) async {
  // Simulate network delay
  await Future.delayed(Duration(seconds: 2));
  return 'User data for ID: $userId';
}

void main() async {
  print('Fetching user data...');
  String userData = await fetchUserData(123);
  print(userData);
  print('Done!');
}

Output:

Fetching user data...

User data for ID: 123

Done!

🔹 Working with Streams

Streams provide continuous data flow:

Stream<int> numberStream() async* {
  for (int i = 1; i <= 3; i++) {
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

void main() async {
  await for (int number in numberStream()) {
    print('Received: $number');
  }
  print('Stream completed!');
}

Output:

Received: 1

Received: 2

Received: 3

Stream completed!

🧠 Test Your Knowledge

What keyword is used to define a mixin in Dart?