Chuyển đến nội dung chính

Bài 20: Performance & Debugging

DevTools: Timeline, Memory, Network. Widget rebuild optimization. const constructors, RepaintBoundary. Image caching, lazy loading. Isolates cho heavy computation. Tree shaking, deferred loading.

💻 Lập trình — Bài 20 Bài 20: Performance & Debugging

Flutter & Dart: Từ Cơ bản đến Nâng cao

Phần 6: Testing, CI/CD & Production

xdev.asia

1. Flutter DevTools

# Mở DevTools
flutter run --profile
# Hoặc từ IDE: Open Flutter DevTools
TabChức năng
Widget InspectorXem widget tree, properties
TimelineFrame rendering, jank detection
MemoryMemory leaks, allocation tracking
NetworkHTTP requests monitoring
PerformanceCPU profiling, flame chart

2. Tối ưu Widget Rebuild

// ✅ Dùng const constructor
const SizedBox(height: 16);
const Text('Static text');

// ✅ RepaintBoundary cho phần tử animate nặng
RepaintBoundary(
  child: AnimatedWidget(...),
);

// ✅ Tách widget nhỏ thay vì build method lớn
class ProductPrice extends StatelessWidget {
  final double price;
  const ProductPrice({super.key, required this.price});

  @override
  Widget build(BuildContext context) {
    return Text('\$${price.toStringAsFixed(2)}',
      style: Theme.of(context).textTheme.titleLarge);
  }
}

// ✅ Sử dụng selector để giảm rebuild
ref.watch(cartProvider.select((cart) => cart.length)); // Chỉ rebuild khi length thay đổi

// ✅ ListView.builder thay vì Column + map
ListView.builder(
  itemCount: items.length,
  itemBuilder: (_, i) => ItemWidget(item: items[i]),
);

3. Isolates cho Heavy Computation

// compute() — simple isolate
Future<List<Product>> parseProducts(String jsonString) async {
  return compute(_parseJson, jsonString);
}

List<Product> _parseJson(String json) {
  final data = jsonDecode(json) as List;
  return data.map((e) => Product.fromJson(e)).toList();
}

// Isolate.run — Dart 2.19+
final result = await Isolate.run(() {
  // Heavy computation
  return processLargeData(data);
});

4. Image Optimization

// CachedNetworkImage
CachedNetworkImage(
  imageUrl: product.imageUrl,
  placeholder: (_, __) => const Shimmer(),
  errorWidget: (_, __, ___) => const Icon(Icons.error),
  memCacheWidth: 300, // Resize in memory
);

// Precache images
Future<void> precacheImages(BuildContext context) async {
  for (final url in imageUrls) {
    await precacheImage(CachedNetworkImageProvider(url), context);
  }
}

// Deferred loading — chia code thành chunks
import 'package:my_app/heavy_feature.dart' deferred as heavy;

Future<void> loadFeature() async {
  await heavy.loadLibrary();
  heavy.showHeavyWidget();
}

Bài tiếp theo: CI/CD & App Signing.