Haftanın Flutter Paketi: image_picker

 

Merhaba, haftanın paketi serimizin ikinci yazısı projelerimizde resim dosyalarını ele almak ile ilgili. Ve paketimiz image_picker. Bu paket, uygulama geliştirenlerin en sık kullandığı araçlardan biri, çünkü bir uygulamada kullanıcıların cihazlarından fotoğraf ya da video seçmesi çok yaygın bir ihtiyaç.

Ne işe yarıyor?

Image Picker cihazın galerisinden ya da direkt kameradan medya dosyaları almanı sağlıyor yani aslında kullanıcıların fotoğraf ya da video seçmesini kolaylaştırıyor. Diyelim ki bir profil fotoğrafı ekleme ekranı yapıyorsun, kullanıcının galeriden bir resim seçmesine ya da anında fotoğraf çekmesine izin vermek istersin. İşte bu paket sayesinde, o iş birkaç satır kodla hallediliyor.

Nasıl kullanılır?

Önce her zamanki gibi aşağıdaki komutu kullanarak paketin pubspec.yamldosyana eklenmesini sağlıyorsun:

flutter pub add image_picker
dependencies:
image_picker: ^1.1.2 //versiyon numarası değişkenlik gösterebilir

Sonrasında paketi kullanacağın dart dosyasına aşağıdaki satır ile import etmen gerekiyor:

import 'package:image_picker/image_picker.dart';

İzinlere bakacak olursak,

Sürüm 0.8.1'den itibaren Android uygulaması Android 4.3 veya üzeri sürümlerde (birden fazla) görüntü seçmeyi desteklemektedir. Dolayısıyla yapılandırma gerekmez — eklenti kutudan çıkar çıkmaz çalışmalıdır.

Ama iOS’ta Info.plist dosyasına aşağıdaki satırları eklemelisin:

<key>NSCameraUsageDescription</key>
<string>We need access to your camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select photos.</string>

Şimdi işin eğlenceli kısmı geliyor. Paketin sunduğu ImagePicker sınıfı sayesinde galeri veya kameradan kolayca resim seçebiliyorsun. İşte nasıl kullanacağına dair basit bir örnek:

final ImagePicker _picker = ImagePicker();

// Galeriden resim seçmek
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

// Kameradan resim çekmek
final XFile? photo = await _picker.pickImage(source: ImageSource.camera);

Yukarıdaki kodda, kullanıcı galeriden bir resim seçerse image değişkenine dosya yolu atanıyor. Aynı şekilde, kamerayı kullanmak istersen ImageSource.camera parametresiyle kameradan çekim yapabilirsin.

Aynı yöntemle video seçmek de mümkün:

final XFile? video = await _picker.pickVideo(source: ImageSource.gallery);

Ayrıca, bu paket hem fotoğrafları hem de videoları küçültme (compression) seçenekleri sunuyor. Bu, özellikle büyük dosya boyutlarını optimize etmek için harika bir özellik!

Şimdi bu paketi kullanarak ne gibi özelleştirmeler yapabiliriz, bir de ona bakalım.

Image Picker’da ayrıca çözünürlük ayarları yaparak kullanıcıların yükleyeceği medya dosyalarının boyutunu ve kalitesini kontrol edebilirsin. Örneğin, kamera kullanılırken düşük çözünürlüklü bir fotoğraf çekmek istersen imageQualityparametresini ayarlayabilirsin.

final XFile? compressedPhoto = await _picker.pickImage(
source: ImageSource.camera,
imageQuality: 50, // %50 kalite
);

Bu sayede, uygulamanın performansını da koruyabilirsin. Özellikle internet üzerinden medya dosyaları yükleyeceksen, düşük boyutlu resimler daha hızlı yüklenir.

Ayrıca maxWidth, maxHeight ile resimlerin boyutunu ve preferredCameraDevice parametresi ile ön ya da arka kamera tercihini de belirleyebilirsin.

Aşağıda tüm kodları ile bu paket kullanılarak yapılmış proje örneğini paylaşıyorum.

!!! Projeyi iOS Simulator kullanarak oluşturduğum ve sanal cihazda kamera bulunmadığından Camera butonunda Error görünüyor ancak gerçek cihazda sorunsuz çalışır.

final ImagePicker _picker = ImagePicker();
Future pickImageFromGallery() async {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
}

Future pickImageFromCamera() async {
final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
}

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
padding: const EdgeInsets.all(16.0),
),
child: const Text("Pick Image from Gallery",
style: TextStyle(
color: Colors.white70, fontWeight: FontWeight.bold)),
onPressed: () {
pickImageFromGallery();
},
),
const SizedBox(
height: 22.0,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
padding: const EdgeInsets.all(16.0),
),
child: const Text("Pick Image from Camera",
style: TextStyle(
color: Colors.white70, fontWeight: FontWeight.bold)),
onPressed: () {
pickImageFromCamera();
},
),
],
),
),

Avantajları ve dezavantajlarından da bahsederek yazımı tamamlıyorum.

ImagePicker paketinin en büyük avantajı kullanıcıların galeriden ya da kameradan medya dosyalarını seçmesinin sadece birkaç satır kodla halledilebiliyor olması. Ayrıca dosya boyutu ve kalitesini de kontrol edebiliyorsun.

Dezavantajına gelince, büyük medya dosyalarıyla çalışırken performans yönetimini iyi yapman gerekebilir. Ve bir de platformlara özgü izinlerin manuel olarak ayarlanması biraz zahmetli olabilir.

Özetle, Image Picker, Flutter projelerinde kullanıcıların medya seçmesini veya kamera kullanmasını isteyen herkesin başvurduğu en popüler paketlerden biri. Eğer uygulamanda profil fotoğrafı, galeri seçimi ya da video yükleme gibi özellikler varsa, bu paket seni epey rahatlatacak! Hem basit, hem de çok yönlü bir çözüm sunuyor.

Umarım faydalı olmuştur.

İyi kodlamalar.

Selin.

Flutter Widget of the Week: CarouselView


Hello everyone! With this article, I would like to announce that I’m starting a “Flutter Widget of the Week” series that I think will be useful when developing Flutter projects. The first week’s widget is the CarouselView widget, which was introduced with the latest version of Flutter. I first tried to do this in my own project by adding animations to Containers. While researching, I saw that there were packages for this and I did it using a package. Now, if you have Flutter version 3.24, you can do this as a classic widget, which I think is a great convenience. Now let’s examine it in detail.

What is CarouselView?

CarouselView is a kind of slider component. That is, you can scroll and switch multiple elements (usually images or cards) horizontally or vertically. This is a very common feature in mobile apps because it allows users to easily switch between content.

How does it work?

The CarouselView widget contains a series of pages. These pages may often have a similar layout to each other, but each one offers different content. Users can switch between these pages by swiping left or right with their fingers.

Example:

Let’s say you have a news app and you want to show the most important news of the day. Each news can be a page and users can easily switch between them. This is where CarouselView comes in!

How to use?

We can think of CarouselView as a typical ListView, but it would be more accurate to describe it as working in a horizontal structure. With a few simple parameters we can start using it right away.

When we run the code, we get a screen like below:

Notes:

  • By placing the CarouselView in ConstrainedBox, we set a limit for its height.
  • With itemExtent we set the size of the widgets in the Carousel on the main axis. In our example, since scrollDirection is horizontal, it means that the main axis is horizontal. The 400 value we give here represents the width of the Containers. If we set this value to 200, the Containers will start to look like a narrow long column.
  • itemSnapping is a setting for scrolling to preserve the original layout. By default it defaults to false, which means that widgets that don’t fit on the first screen from the items to be scrolled appear to be absent but become visible when scrolled. If we change this parameter to true, according to this example, a part of the blue Container is visible on the first screen if its size is appropriate.
  • I didn’t use it here, but the reverse parameter also allows you to sort the items to be scrolled in reverse order.
  • The shrinkExtent parameter, which is not present in this example, expresses the minimum extent allowed on the main axis for widgets during scrolling. For example, let’s say we set itemExtent to 400 and shrinkExtent to 150. The Container, which is 400 wide before the scrolling starts, shrinks to a maximum of 150 units until it disappears from the screen when scrolling starts and scrolls on the screen until it disappears. By default, the value 0 is given, if no value is set, Containers can be scrolled as in the screen recording above without losing any size.

I hope you found this article useful! If you appreciate the information provided, you have the option to support me by Buying Me A Coffee! Your gesture would be greatly appreciated!


In this article, I wanted to tell you about CarouselWidget, which is presented as a novelty. I hope I was able to write clearly and understandably enough.

Good coding to everyone.

Selin.