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

Lesson 20: Performance & Debugging

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

💻 Programming — Lesson 20 Lesson 20: Performance & Debugging

Flutter & Dart: From Basics to Advanced

Part 6: Testing, CI/CD & Production

xdev.asia

1. Flutter DevTools

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

2. Optimize 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 for 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();
}

Next article: CI/CD & App Signing.