Dart Generics, Exceptions and Libraries
Generics: One Class, Many Types
Generics let you write code that works with different types and still keeps type safety. You already saw them: List<String>, Future<int> and Map<String, dynamic>.
dart
class Box<T> {
final T value;
const Box(this.value);
}
var a = Box<int>(42);
var b = Box<String>('hello');
print(a.value + 1); // OK: Dart knows it is an int
// A generic function
T firstOr<T>(List<T> list, T fallback) => list.isEmpty ? fallback : list.first;
print(firstOr<String>([], 'none'));
dart
// Limit the type with extends
class Repository<T extends Object> {
final List<T> _items = [];
void add(T item) => _items.add(item);
List<T> all() => List.unmodifiable(_items);
}
Exceptions
Things go wrong: no internet, bad data, missing files. Dart uses try, catch and throw.
dart
int parseAge(String text) {
try {
final age = int.parse(text);
if (age < 0) throw ArgumentError('Age cannot be negative');
return age;
} on FormatException {
print('That is not a number');
return 0;
} on ArgumentError catch (e) {
print('Invalid: ${e.message}');
return 0;
} catch (e, stackTrace) {
print('Unexpected: $e');
print(stackTrace);
rethrow; // pass the error to the caller
} finally {
print('Done parsing'); // always runs
}
}
| Keyword | Meaning |
|---|---|
try | Code that might fail |
on Type | Handle one kind of error |
catch (e) | Handle any error and get its object |
finally | Always runs, good for cleanup |
throw | Raise an error |
rethrow | Throw the same error again |
Custom Exceptions
dart
class ApiException implements Exception {
final int statusCode;
final String message;
const ApiException(this.statusCode, this.message);
@override
String toString() => 'ApiException($statusCode): $message';
}
Future<void> load() async {
throw const ApiException(404, 'Not found');
}
Exception or Error?
Exception describes problems you can expect and handle (network failure). Error describes bugs in your program (such as a wrong argument). Do not catch Error to hide bugs.
Libraries and Imports
Every Dart file is a library. You import what you need.
dart
import 'dart:math'; // built-in library
import 'package:flutter/material.dart'; // package
import 'package:http/http.dart' as http; // with a prefix to avoid name clashes
import 'models/user.dart'; // your own file (relative path)
import 'utils/helpers.dart' show formatDate; // import only one thing
import 'utils/legacy.dart' hide oldFunction; // import all but one
Organizing a Flutter Project
text
lib/
main.dart
models/ data classes
services/ API and database code
state/ providers, notifiers or blocs
pages/ full screens
widgets/ reusable widgets
utils/ helpers and constants
- Keep one main class per file, named after the file (
user_card.darthasUserCard) - Names starting with
_are private to the file - Use lowercase_with_underscores for file names
Tip: Start small and move code into new files when a file grows beyond a few hundred lines. Smaller files are easier to read and test.
Conclusion
Generics keep your code flexible and safe, exceptions keep your app from crashing and files and imports keep your project tidy.
Quick Summary: Generics use type parameters, try, on, catch and finally handle errors, and imports connect files and packages.

