Flutter and Performance Optimisation

 

Flutter - Performance Optimisation

Hello everyone. In this blog post, I would like to talk about some basic techniques and tips that we can use to make our Flutter apps faster and smoother. I am about to publish my second app on GooglePlay and in this process, I realised that I have to think about performance more than I think about visuals, design, UI elements. Because no matter how stylish your app looks, it is not possible for the user experience to be positive if there are performance problems. That’s why I researched this topic and listed below what I found.

1. Render Performance: Avoid Unnecessary Redraws
In a Flutter application, every change can cause the screen to redraw. This often creates a big problem in terms of performance. You can optimise your application by avoiding unnecessary redraws.

  • const Keyword: Widgets defined with const are immutable and are not redrawn unnecessarily. Using const, especially when creating static structures, can provide a great improvement in performance.
const Text(
'Hello World!',
style: TextStyle(fontSize: 24),
);

The widget defined in this way will not be redrawn unless it changes.

  • ‘shouldRebuild’ Control: Within some widgets, you can use the shouldRebuild function to make the widget redraw only when certain conditions are met.
@override
bool shouldRebuild(covariant CustomWidget oldWidget) {
return oldWidget.value != value;
}

2. List Performance: Optimising Large Lists
Working with large datasets can cause performance issues, especially when displaying long lists. Flutter offers several optimisation tools for such situations.

  • ListView.builder: In a fixed length or large list, it is more performant to use ListView.builder, which loads only the items in the view, rather than loading all items at once.
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
);
  • ReorderableListView: When creating sortable lists, this widget can be used to maintain performance. Likewise, it renders only the widgets that are needed and improves performance.

3. Asynchronous Coding: Manage Transactions without Locking the UI
Time-consuming operations, such as network requests or long-running processes, can freeze the UI. Flutter has several tools for managing asynchronous operations.

  • FutureBuilder: FutureBuilder allows you to show a pending state in the UI while waiting for an asynchronous operation to complete. In this way, your application provides a seamless experience to users.
FutureBuilder(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Data: ${snapshot.data}');
}
},
);
  • async and await: These keywords allow operations to be performed asynchronously. await waits for the operation to finish, while async indicates the completion of the operation. It is important to use these constructs correctly to prevent the UI from freezing.
Future<void> fetchData() async {
final response = await http.get('https://api.example.com/data');
// Operations need to be carried out here
}

4. Get rid of unnecessary packages: Lighten Your Code Base
Adding packages to your Flutter application can speed up the development process. However, unnecessary or excess packages can bloat your application and negatively impact performance.

  • Dependency Management: Regularly review the dependencies in your pubspec.yaml file. Remove unused packages and measure their impact on performance.
dependencies:
flutter:
sdk: flutter
# Remove unused packages
  • Minimal Package Usage: If possible, only add packages that are really necessary. Prefer lighter packages and consider alternatives.

5. Flutter DevTools: Performance Analysis and Debugging
Flutter offers Flutter DevTools, a powerful tool for monitoring and solving performance issues. With this tool you can analyse your application’s CPU and memory usage, detect UI lags and make performance improvements.

  • CPU Profile: Monitoring the CPU usage of your application allows you to understand which processes consume excess resources.
  • Timeline: You can use the timeline tool to see where the UI is lagging. This tool shows which processes take the most time.
  • Memory Profile: You can detect memory leaks and make optimisation. You can identify processes that consume too much memory and make improvements in memory usage.

Conclusion: Performance Optimisation is a Process
Performance optimisation, unfortunately, is not a one-time operation. As you develop the application and add new features, performance issues can arise again and again, and I’ve seen it happen many times. A simple change to a button’s performance analysis is therefore necessary to make improvements on a regular basis.

I hope that the techniques I have discussed here will help you make your Flutter application more performant, but of course every application is different and we should not forget to optimise it according to its specific requirements.

Happy coding to everyone!

Selin.

Flutter ve Performans Optimizasyonu

 

Flutter - Performans Optimizasyonu

Herkese merhaba. Bu blog yazısında sizlere Flutter uygulamalarımızı daha hızlı ve sorunsuz hale getirmek için kullanabileceğimiz bazı temel teknikler ve ipuçlarından bahsetmek istiyorum. GooglePlay’de ikinci uygulamamı yayınlamak üzereyim ve bu süreçte görseli, tasarımı, UI elementleri üzerine düşündüğümden daha fazlasını performans konusu için düşünmek zorunda olduğumu fark ettim. Çünkü uygulamanız ne kadar şık görünürse görünsün, performans sorunları varsa kullanıcı deneyiminin olumlu olması mümkün değil. Bu yüzden bu konuyu araştırdım ve bulduklarımı aşağıda sıraladım.

1. Render Performansı: Gereksiz Yeniden Çizimleri Engelleyin

Bir Flutter uygulamasında, her değişiklik ekranın yeniden çizilmesine neden olabilir. Bu, performans açısından çoğu zaman büyük bir sorun yaratır. Gereksiz yeniden çizimlerden kaçınarak uygulamanızı optimize edebilirsiniz.

  • const Anahtar Kelimesi: const ile tanımlanan widget'lar değişmezdir ve gereksiz yere yeniden çizilmezler. Özellikle statik yapılar oluştururken const kullanmak, performans üzerinde büyük bir iyileştirme sağlayabilir.
const Text(
'Merhaba Dünya!',
style: TextStyle(fontSize: 24),
);

Bu şekilde tanımlanan widget, değişmediği sürece yeniden çizilmeyecektir.

  • 'shouldRebuild' Kontrolü: Bazı widget'lar içinde shouldRebuild işlevini kullanarak, yalnızca belirli koşullar sağlandığında widget'ın yeniden çizilmesini sağlayabilirsiniz.
@override
bool shouldRebuild(covariant CustomWidget oldWidget) {
return oldWidget.value != value;
}

2. Liste Performansı: Büyük Listeleri Optimize Etme

Büyük veri kümeleriyle çalışmak, özellikle uzun listeler görüntülenirken performans sorunlarına neden olabilir. Flutter, bu tür durumlar için çeşitli optimizasyon araçları sunar.

  • ListView.builder: Sabit bir uzunluktaki veya büyük bir listede, tüm öğeleri aynı anda yüklemek yerine, yalnızca görünümdeki öğeleri yükleyen ListView.builder kullanmak daha performanslıdır.
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
);
  • ReorderableListView: Sıralanabilir listeler oluştururken, performansı korumak için bu widget kullanılabilir. Aynı şekilde, yalnızca gerekli olan widget'ları oluşturur ve performansı artırır.

3. Asenkron Kodlama: UI’yi Kilitlemeden İşlemleri Yönetin

Ağ istekleri veya uzun süren işlemler gibi zaman alan işlemler, UI’yi dondurabilir. Flutter’da asenkron işlemleri yönetmek için birkaç araç bulunuyor.

  • FutureBuilder: FutureBuilder, bir asenkron işlemin tamamlanmasını beklerken, UI'de bekleme durumu göstermenizi sağlar. Bu sayede, uygulamanız kullanıcılara sorunsuz bir deneyim sunar.
FutureBuilder(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Hata: ${snapshot.error}');
} else {
return Text('Veri: ${snapshot.data}');
}
},
);
  • async ve await: Bu anahtar kelimeler, işlemlerin asenkron şekilde yapılmasını sağlar. await, işlemin bitmesini beklerken, async işlemin tamamlanmasını belirtir. UI'nin donmasını engellemek için bu yapıları doğru kullanmak önemlidir.
Future<void> fetchData() async {
final response = await http.get('https://api.example.com/data');
// İşlemlerin burada yapılması gerekir
}

4. Gereksiz Paketlerden Kurtulma: Kod Tabanınızı Hafifletin

Flutter uygulamanıza paket eklemek, geliştirme sürecini hızlandırabilir. Ancak, gereksiz veya fazla paketler uygulamanızı şişirebilir ve performansı olumsuz etkileyebilir.

  • Bağımlılık Yönetimi: pubspec.yaml dosyanızdaki bağımlılıkları düzenli olarak gözden geçirin. Kullanılmayan paketleri kaldırın ve performans üzerindeki etkilerini ölçün.
dependencies:
flutter:
sdk: flutter
# Kullanılmayan paketleri kaldırın
  • Minimal Paket Kullanımı: Mümkünse, yalnızca gerçekten gerekli olan paketleri ekleyin. Daha hafif paketler tercih edin ve alternatifleri değerlendirin.

5. Flutter DevTools: Performans Analizi ve Hata Ayıklama

Flutter, performans sorunlarını izlemek ve çözmek için güçlü bir araç olan Flutter DevTools’u sunar. Bu araç ile uygulamanızın CPU ve bellek kullanımını analiz edebilir, UI gecikmelerini tespit edebilir ve performans iyileştirmeleri yapabilirsiniz.

  • CPU Profili: Uygulamanızın CPU kullanımını izlemek, hangi işlemlerin fazla kaynak tükettiğini anlamanızı sağlar.
  • Timeline (Zaman Çizelgesi): UI’nin nerede geciktiğini görmek için zaman çizelgesi aracını kullanabilirsiniz. Bu araç, hangi işlemlerin en fazla süreyi aldığını gösterir.
  • Hafıza Profili: Hafıza sızıntılarını tespit edebilir ve optimizasyon yapabilirsiniz. Fazla bellek tüketen işlemleri belirleyip, bellek kullanımı konusunda iyileştirmeler yapabilirsiniz.

Sonuç: Performans Optimizasyonu Bir Süreçtir

Performans optimizasyonu, ne yazık ki, bir seferlik bir işlem değil. Uygulamayı geliştirdikçe ve yeni özellikler ekledikçe, performans sorunları tekrar tekrar ortaya çıkabiliyor, bunu çok yaşadım. Basit bir değişiklik bir butonun Bu nedenle, düzenli olarak performans analizi iyileştirmeler yapmak gerekiyor.

Araştırmalarım sonucu burada ele aldığım tekniklerin, Flutter uygulamanızı daha performanslı hale getirmenize yardımcı olacağını umuyorum. Ancak tabi ki her uygulama farklıdır ve kendi özel gereksinimlerine göre optimize etmeyi unutmamalıyız.

Herkese iyi kodlamalar!

Selin.