Asynchronous Programming

This example fetches data from a mock API using asynchronous programming.

import 'dart:async';

class User {
  final String name;
  final String email;

  User(this.name, this.email);

  @override
  String toString() => 'Name: $name, Email: $email';
}

Future<List<User>> fetchUsers() async {
  // Simulating network delay
  await Future.delayed(Duration(seconds: 2));

  return [
    User('Alice', '[email protected]'),
    User('Bob', '[email protected]'),
    User('Charlie', '[email protected]'),
  ];
}

void main() async {
  print('Fetching users...');
  List<User> users = await fetchUsers();

  print('Users fetched:');
  for (var user in users) {
    print(user);
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *