Last updated: October 26, 2026
After completing this codelab, you will be able to:
campus_notify or the Clean Architecture refactor). This codelab focuses on optimizing the performance of an existing project.Modern mobile apps must be responsive, battery-efficient, and smooth across device specifications. Poor performance leads to:
UI Thread (Dart) Raster Thread (GPU)
+------------------+ +------------------+
| Build Widget | | |
| Layout | ---> | Composite |
| Paint | | Rasterize |
+------------------+ +------------------+
| |
v v
Frame Budget: 16.67 ms (60 FPS) / 8.33 ms (120 FPS)
| Category | Focus | Tools |
|---|---|---|
| CPU/Build | Widget rebuild, excessive layout, heavy computation | DevTools Performance, Timeline |
| Memory | Leaks, large images, unbounded lists | DevTools Memory, Heap Snapshot |
| Network | Repeated requests, large payloads, no cache | DevTools Network, Dio Interceptor |
| Images | Wrong resolution, inefficient format | DevTools Memory, cached_network_image |
# From project terminal
flutter run --profile
# Or
flutter run -d --profile
# Open DevTools in browser (auto-opens or)
# http://127.0.0.1:9100
Note: Use --profile mode (not --debug or --release) for accurate profiling. Debug mode has significant overhead.
build, layout, paintrasterize, image decodeflutter run --profilesetState on a large root widgetListView.builder without const itemsconst Constructors// Before: rebuilds every parent rebuild
Widget build(BuildContext context) {
return Column(
children: [
Text('Title'), // not const
Icon(Icons.star), // not const
MyCustomWidget(), // not const
],
);
}
// After: only rebuilds if parameters change
Widget build(BuildContext context) {
return const Column(
children: [
Text('Title'),
Icon(Icons.star'),
MyCustomWidget(),
],
);
}
// Before: everything in one build method
class MyPage extends StatelessWidget {
Widget build(BuildContext context) {
return Column(
children: List.generate(100, (i) => Text('Item $i')), // rebuilds all
);
}
}
// After: items separate, can be const
class MyPage extends StatelessWidget {
Widget build(BuildContext context) {
return Column(
children: List.generate(100, (i) => const MyItem()), // only MyItem rebuilds
);
}
}
class MyItem extends StatelessWidget {
const MyItem();
Widget build(BuildContext context) => const Text('Item');
}
RepaintBoundary for Paint Isolation// Only this area repaints when changed
RepaintBoundary(
child: ExpensiveWidget(),
)
select and ProviderScope Override// Only rebuilds when value.count changes, not the entire state
final count = ref.watch(counterProvider.select((s) => s.count));
// Or use Consumer with a specific builder
Consumer(
builder: (context, ref, child) {
final value = ref.watch(provider);
return Text('$value');
},
)
// Bad: new closure every build
onPressed: () => doSomething()
// Good: method reference or tear-off
onPressed: doSomething
// Or use a pre-defined callback
onPressed: _handlePress
ListView.builderListView.builder only builds visible items (viewport). Ensure:
ListView.builder not ListView(children: [...])`const constructorExpanded or Flexible inside items unless neededclass PaginatedList extends ConsumerStatefulWidget {
const PaginatedList();
@override
ConsumerState createState() => _PaginatedListState();
}
class _PaginatedListState extends ConsumerState {
final _scrollController = ScrollController();
final _items = - [];
var _page = 1;
var _isLoading = false;
var _hasMore = true;
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
_loadPage();
}
void _onScroll() {
if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent - 200) {
_loadPage();
}
}
Future
_loadPage() async {
if (_isLoading || !_hasMore) return;
_isLoading = true;
try {
final newItems = await ref.read(itemRepositoryProvider).fetchPage(_page);
if (newItems.isEmpty) {
_hasMore = false;
} else {
_items.addAll(newItems);
_page++;
}
} finally {
_isLoading = false;
if (mounted) setState(() {});
}
}
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: _scrollController,
itemCount: _items.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index == _items.length) {
return const Center(child: CircularProgressIndicator());
}
return ItemTile(item: _items[index]);
},
);
}
}
| Technique | Description | Package |
|---|---|---|
| Server-side resize | Request appropriate size (thumbnail), not full-res | Backend/CDN |
| Modern formats | WebP, AVIF smaller than JPEG/PNG | Server/CDN |
| Local caching | Store images on disk, avoid re-download | cached_network_image |
| Placeholders | Show blur/low-res first, then swap | fade_in_image, cached_network_image |
| Precache | Load images before needed (e.g., next page) | precacheImage |
| Memcache limits | Limit memory cache size | PaintingBinding.instance.imageCache |
// Example cached_network_image
CachedNetworkImage(
imageUrl: item.imageUrl,
placeholder: (context, url) => Shimmer.fromColors(
baseColor: Colors.grey[300]!,
highlightColor: Colors.grey[100]!,
child: Container(color: Colors.white),
),
errorWidget: (context, url, error) => const Icon(Icons.error),
memCacheWidth: 300, // decode at display size, not full-res
memCacheHeight: 200,
fadeInDuration: const Duration(milliseconds: 200),
)
| Strategy | Best For | Implementation |
|---|---|---|
| Cache-First | Rarely changing data (config, master data) | Read cache → if empty, fetch API → store cache |
| Network-First | Critical real-time data (chat, prices, stock) | Fetch API → store cache → fallback to cache on failure |
| Stale-While-Revalidate | Semi-real-time data (feed, lists) | Show cache → fetch background → update UI |
| Cache-Only (Offline) | Full offline mode | Only read from local DB (Hive/SQLite/Drift) |
class ItemRepository {
final Dio _dio;
final Box- _localBox; // Hive
ItemRepository(this._dio, this._localBox);
Future
> getItems() async {
// 1. Show cache immediately (if exists)
final cached = _localBox.values.toList();
if (cached.isNotEmpty) {
_emitCached(cached);
}
// 2. Fetch fresh data in background
try {
final response = await _dio.get('/items');
final fresh = (response.data as List)
.map((e) => Item.fromJson(e))
.toList();
// 3. Update local cache
await _localBox.clear();
await _localBox.addAll(fresh);
// 4. Emit fresh data
_emitFresh(fresh);
return fresh;
} catch (e) {
// If error and no cache, throw error
if (cached.isEmpty) rethrow;
return cached; // Return cache as fallback
}
}
}
final dio = Dio(BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 15),
));
// Retry interceptor
dio.interceptors.add(RetryInterceptor(
dio: dio,
logPrint: print,
retries: 3,
retryDelays: [
const Duration(seconds: 1),
const Duration(seconds: 2),
const Duration(seconds: 5),
],
));
// Cache interceptor (custom)
dio.interceptors.add(CacheInterceptor(
storage: CacheStorage(),
policy: CachePolicy.staleWhileRevalidate,
));
gzip / brotli on server (header Accept-Encoding)?fields=id,name,thumb)campus_notify)flutter run --profilescreenshots/before-profile.pngBased on profiling, identify at least 3 issues:
build in Flame Chart)image decode in Raster Thread)HTTP events)Layout during scroll)Document findings in docs/performance-findings.md
Select and apply at least 3 optimizations:
const to static widgetsconst widgetsref.watch(provider) with ref.watch(provider.select(...))Image.network with CachedNetworkImage + memCacheWidth/Heightflutter run --profile againscreenshots/after-profile.pngdispose()docs/performance-report.md:
flutter analyze + flutter test in README.11-week-11-performance-optimization/ with lib/, docs/, README.md, screenshots/.