Last updated: October 26, 2026

Bahasa Indonesia | English

Learning objectives

After completing this codelab, you will be able to:

Preparation

1. Why Performance Optimization Matters

Modern mobile apps must be responsive, battery-efficient, and smooth across device specifications. Poor performance leads to:

2. Flutter Rendering Pipeline

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)

3. Main Optimization Categories

CategoryFocusTools
CPU/BuildWidget rebuild, excessive layout, heavy computationDevTools Performance, Timeline
MemoryLeaks, large images, unbounded listsDevTools Memory, Heap Snapshot
NetworkRepeated requests, large payloads, no cacheDevTools Network, Dio Interceptor
ImagesWrong resolution, inefficient formatDevTools Memory, cached_network_image

1. Opening DevTools

# 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.

2. Performance Tab (CPU Profiling)

3. Memory Tab (Memory Profiling)

4. Profiling Workflow

  1. Run the app with flutter run --profile
  2. Open DevTools → Performance tab
  3. Click Record → use the app normally (scroll, navigate, load data)
  4. Click Stop → analyze red/yellow frames
  5. Click a problematic frame → view Flame Chart → identify the top slow function
  6. Fix the code → repeat profiling to verify

1. Causes of Excessive Rebuilds

2. Optimization Techniques

A. Use const 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(),
    ],
  );
}

B. Extract Widgets to Separate Classes

// 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');
}

C. Use RepaintBoundary for Paint Isolation

// Only this area repaints when changed
RepaintBoundary(
  child: ExpensiveWidget(),
)

D. Riverpod: 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');
  },
)

E. Avoid Anonymous Functions in Build

// Bad: new closure every build
onPressed: () => doSomething()

// Good: method reference or tear-off
onPressed: doSomething

// Or use a pre-defined callback
onPressed: _handlePress

1. Lazy Loading with ListView.builder

ListView.builder only builds visible items (viewport). Ensure:

2. Pagination (Infinite Scroll)

class 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]);
      },
    );
  }
}

3. Image Optimization

TechniqueDescriptionPackage
Server-side resizeRequest appropriate size (thumbnail), not full-resBackend/CDN
Modern formatsWebP, AVIF smaller than JPEG/PNGServer/CDN
Local cachingStore images on disk, avoid re-downloadcached_network_image
PlaceholdersShow blur/low-res first, then swapfade_in_image, cached_network_image
PrecacheLoad images before needed (e.g., next page)precacheImage
Memcache limitsLimit memory cache sizePaintingBinding.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),
)

1. Caching Strategies

StrategyBest ForImplementation
Cache-FirstRarely changing data (config, master data)Read cache → if empty, fetch API → store cache
Network-FirstCritical real-time data (chat, prices, stock)Fetch API → store cache → fallback to cache on failure
Stale-While-RevalidateSemi-real-time data (feed, lists)Show cache → fetch background → update UI
Cache-Only (Offline)Full offline modeOnly read from local DB (Hive/SQLite/Drift)

2. Repository Implementation with Cache (Stale-While-Revalidate)

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
    }
  }
}

3. Dio Interceptor for Logging and Retry

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,
));

4. Compression and Small Payloads

Step 1: Baseline Profiling

  1. Open your Week 7–10 project (for example, campus_notify)
  2. Run flutter run --profile
  3. Open DevTools → Performance tab → click Record
  4. Perform scenarios: open list, fast scroll, open detail, back, pull-to-refresh
  5. Click Stop → note: red/yellow frame count, average frame time, top functions in Flame Chart
  6. Save Flame Chart screenshot as screenshots/before-profile.png

Step 2: Identify Issues

Based on profiling, identify at least 3 issues:

Document findings in docs/performance-findings.md

Step 3: Apply Optimizations

Select and apply at least 3 optimizations:

  1. Const constructors: Add const to static widgets
  2. Extract widgets: Break large widgets into small const widgets
  3. RepaintBoundary: Wrap frequently repainting areas (charts, animations)
  4. Riverpod select: Replace ref.watch(provider) with ref.watch(provider.select(...))
  5. ListView.builder: Ensure all lists use builder
  6. CachedNetworkImage: Replace Image.network with CachedNetworkImage + memCacheWidth/Height
  7. Pagination: Add infinite scroll to long lists
  8. Repository cache: Add stale-while-revalidate to repository

Step 4: Verify with Profiling

  1. Run flutter run --profile again
  2. Record the same scenarios
  3. Compare: fewer red/yellow frames, lower average frame time
  4. Save screenshot as screenshots/after-profile.png

Step 5: Memory Profiling

  1. Open Memory tab in DevTools
  2. Take a Heap Snapshot on the list page
  3. Navigate to detail → back → repeat 5 times
  4. Take another snapshot → compare: any accumulating objects?
  5. If a leak is found: find unreleased references (controllers, listeners, stream subscriptions)
  6. Fix with proper dispose()

Mini project / Industry Challenge

  1. Optimize your Week 7–10 project performance with at least 3 techniques from this codelab.
  2. Document in docs/performance-report.md:
    • Baseline metrics (frame time, jank count, memory usage)
    • Profiling findings (Flame Chart before/after screenshots)
    • Applied optimizations + rationale
    • Verification results (metrics after)
  3. Include clean flutter analyze + flutter test in README.
  4. Push to 11-week-11-performance-optimization/ with lib/, docs/, README.md, screenshots/.

Reflection

Supporting references