text

Understanding Future in Flutter and Dart

A Future in Dart represents a value that will be available later — it’s how you handle asynchronous operations like API calls or file reads.

Steps

1. Understand what a Future is

A Future is like a promise that something will complete later — successfully with a value, or with an error.
Example: fetching data from the internet or reading a file.

Future<String> fetchData() async {
  return 'Hello from the future!';
}

2. Use async and await

async makes a function return a Future.
await pauses the function until the Future completes.

Future<void> main() async {
  final message = await fetchData();
  print(message);
}

3. Handle errors with try/catch

If the Future fails, you can catch the exception just like in synchronous code.

Future<String> fetchData() async {
  throw Exception('Something went wrong');
}

Future<void> main() async {
  try {
    final message = await fetchData();
    print(message);
  } catch (e) {
    print('Error: $e');
  }
}

4. Use .then() for callbacks

You can also handle Futures using the .then() method — this is common when you can’t use async/await.

fetchData().then((data) {
  print(data);
}).catchError((error) {
  print('Error: $error');
});

5. Combine multiple Futures

Use Future.wait() to run several async operations in parallel.

Future<void> loadData() async {
  final results = await Future.wait([
    fetchUser(),
    fetchPosts(),
  ]);
  print(results);
}

Verify It Works

Run the example — you should see printed text after a short delay, proving the Future completed asynchronously.

Troubleshooting

  • Error: “Unhandled exception: Bad state: Future already completed.”
    Fix: Don’t complete the same Completer twice.
  • Error: “Await expressions can only be used in async functions.”
    Fix: Add async to your function.
  • Nothing prints:
    Fix: Make sure main() is marked async and you await your Futures.

Variations / Alternatives

  • Use Stream for multiple async values over time.
  • Use Future.microtask() for quick deferred tasks.
  • Combine with Timer for delayed execution.

Performance & Pitfalls

  • Don’t block the main thread — always await long-running tasks.
  • Avoid mixing .then() and await in the same function.
  • Prefer async/await for cleaner code.

References



Leave a Reply

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