flutter packages etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
flutter packages etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

Using SharedPreferences in Flutter: Make Your Data Persistent

 


Hello everyone.

In Flutter apps, it is important to permanently store user settings or app data on the device. This is where SharedPreferences comes into play in Flutter. In this article, you will learn how to include the SharedPreferences package in your Flutter project, how to save and read data, and how to use it in full detail.

What is SharedPreferences in Flutter and what does it do?

SharedPreferences is a package used to permanently store small pieces of data from Flutter on the device, especially ideal for storing information such as user settings and app state. This way, data is not lost every time the app is launched, and previous data is preserved when the user logs into your app or restarts the app.

SharedPreferences is usually used for:

  • For storing small data such as username and password,
  • For storing settings such as user preferences (theme, language selection),
  • For keeping application status information.

How to Include the SharedPreferences Package in Flutter

To start using SharedPreferences in Flutter projects, we first need to include the package in the project. To do this, add the following line to the pubspec.yaml file:

Note: The most current version number at the time of writing is above. This number may have changed while you were uploading. If you want the version numbers to be automatically added to the file during upload, you can also upload with the command line below.

After that, we can now start using the SharedPreferences package!

Saving, Reading and Deleting Data with SharedPreferences

Saving Data

Saving data using SharedPreferences is quite simple. In the example below, we will save the username.

We get the SharedPreferences object with SharedPreferences.getInstance(). When the data type to be saved here is String, we save the username with setString. If you want to save other types of data, methods like setInt, setBool can also be used.

Reading Data

We can use the following code to read the data we saved:

Here, we read the username we saved with the getString method and print it to the screen. If no value is found, it will return null.

Updating Data

It is also quite easy to update the saved data. For example, we can change the username. We use the setString method again, but this time we add the new value.

Note: You may have thought of the following here: we also use the set method for update. How does the program know that it will update the existing one? What if it saves a second value?

At this point, the concept of ‘key’, which is the working logic of SharedPreference, comes into play.

SharedPreferences modifies the data corresponding to a specific key. If the same key has been saved before, it is replaced with a new value. If the same key has not been saved before, SharedPreferences adds new data. That is, instead of registering new data, it updates existing data.

For example, in the example above, it worked like this:

Saving New Data: If the key you specified earlier (e.g. ‘username’) does not exist in SharedPreferences, the value saved with setString was added as new data.

Update Existing Data: If the same key already exists in SharedPreferences, setString updated the existing value. This overwrote the old value with the new value.

So, SharedPreferences set methods always store only one value under only one key. Two different values cannot be stored for the same key. If a key has already been stored, the new data replaces the old data.

Deleting Data

We can use the remove method to delete data. In the example below, we delete the saved username:

Clearing All Data

If you want to delete all SharedPreferences data, you can use the clear method:

Saving User Settings with SharedPreferences

SharedPreferences is very useful for storing information, especially user settings. For example, when a user changes the theme, we can save this preference. Here, of course, the method we will write requires a bool parameter called isDarkMode.

We can then read it as follows:

Working with Data Types

SharedPreferences can store different data types, not only String. Here are some examples:

  • setInt: prefs.setInt(‘key’, 123);
  • setBool: prefs.setBool(‘key’, true);
  • setDouble: prefs.setDouble(‘key’, 3.14);
  • setStringList: prefs.setStringList(‘key’, [‘apple’, ‘banana’]);

Similarly, you can use methods like getInt, getBool, getDouble, and getStringList to read data.

Frequently Asked Questions

How Safe is Saving Data with SharedPreferences? SharedPreferences is suitable for small data storage operations. However, for large or sensitive data, more secure solutions should be preferred.
When is SharedPreferences Used in Flutter Applications? SharedPreferences is used to store user settings, theme preferences, session information and small data.
How many days can I store data in SharedPreferences? Data is stored permanently on the device and is only stored until the user manually deletes the data.

Conclusion

Making your data persistent on the device using SharedPreferences in Flutter is very simple and effective. You can use this method to store user information, preferences and app statuses. It is also very easy to read and update SharedPreferences data. In this way, you have learned how to store persistent data in your application using SharedPreferences!

Thank you for reading this far.

Don’t forget to press clap if you like this article and subscribe to be informed about my other content.

Thank you very much.

Selin.

Flutter’da SharedPreferences Kullanımı: Verilerinizi Kalıcı Hale Getirin

 


Herkese merhaba.

Flutter uygulamalarında, kullanıcı ayarlarını veya uygulama verilerini cihazda kalıcı olarak saklamak önemlidir. İşte tam da bu noktada, Flutter’da SharedPreferences devreye girer. Bu yazıda, SharedPreferences paketini Flutter projenize nasıl dahil edebileceğinizi, verileri nasıl kaydedip okuyabileceğinizi ve tüm detaylarıyla nasıl kullanabileceğinizi öğreneceksiniz.

Flutter’da SharedPreferences Nedir ve Ne İşe Yarar?

SharedPreferences, Flutter’daki küçük veri parçalarını cihazda kalıcı olarak saklamak için kullanılan bir paket olup, özellikle kullanıcı ayarları ve uygulama durumu gibi bilgileri saklamak için idealdir. Bu sayede uygulamanın her açılışında veriler kaybolmaz, kullanıcı uygulamanızda oturum açtığında veya uygulamayı yeniden başlattığında önceki veriler korunur.

SharedPreferences genellikle:

  • Kullanıcı adı ve şifre gibi küçük verilerin saklanmasında,
  • Kullanıcı tercihleri (tema, dil seçimi) gibi ayarların saklanmasında,
  • Uygulama durumu bilgilerini tutmak için kullanılır.

SharedPreferences Paketini Flutter’a Nasıl Dahil Edersiniz?

Flutter projelerinde SharedPreferences’ı kullanmaya başlamak için, önce paketi projeye dahil etmemiz gerekiyor. Bunun için pubspec.yaml dosyasına şu satırı ekleyin:

dependencies:
shared_preferences: ^2.5.3

Not: Yazıyı yazdığım tarihteki en güncel versiyon numarası yukarıda yer almaktadır. Siz yükleme yaparken bu numara değişmiş olabilir. Versiyon numaralarının yükleme sırasında otomatik olarak dosyaya eklenmesini istiyorsanız, aşağıdaki komut satırı ile de yükleme yapabilirsiniz.

$ flutter pub add shared_preferences

Bu işlemden sonra, artık SharedPreferences paketini kullanmaya başlayabiliriz!

SharedPreferences ile Verileri Kaydetme, Okuma ve Silme

Veriyi Kaydetme

SharedPreferences kullanarak verileri kaydetmek oldukça basittir. Aşağıdaki örnekte, kullanıcı adını kaydedeceğiz.

import 'package:shared_preferences/shared_preferences.dart';

void saveUsername() async {
final prefs = await SharedPreferences.getInstance();

await prefs.setString('username', 'flutter_dev');
print("Kullanıcı adı kaydedildi!");
}

SharedPreferences.getInstance() ile SharedPreferences nesnesini alıyoru. Burada kaydedeceğimiz veri türü String olduğunda kullanıcı adını setStringile kaydediyoruz. Eğer başka türde veri kaydetmek isterseniz, setIntsetBool gibi metodlar da kullanılabilir.

Veriyi Okumak

Kaydettiğimiz veriyi okumak için şu kodu kullanabiliriz:

void getUsername() async {
final prefs = await SharedPreferences.getInstance();

String? username = prefs.getString('username');

if (username != null) {
print("Kullanıcı adı: $username");
} else {
print("Kullanıcı adı bulunamadı!");
}
}

Burada, getString metodu ile kaydettiğimiz kullanıcı adını okuyup ekrana yazdırıyoruz. Eğer değer bulunmazsa, null dönecektir.

Veriyi Güncellemek

Kaydedilen veriyi güncellemek de oldukça kolaydır. Örneğin, kullanıcı adını değiştirebiliriz. Bunun için yine setString metodunu kullanıyoruz ancak bu defa yeni değeri ekliyoruz.

void updateUsername() async {
final prefs = await SharedPreferences.getInstance();

await prefs.setString('username', 'new_flutter_dev');
print("Kullanıcı adı güncellendi!");
}

Not: Burada aklınıza şu gelmiş olabilir: update işlemi için de set methodunu kullanıyoruz. Bunu yaparken program var olanı güncelleyeceğini nereden biliyor? Ya ikinci bir değer kaydederse?

Bu noktada devreye SharedPreference’ın çalışma mantığı olan ‘key’ kavramı devreye giriyor.

SharedPreferences, belirli bir anahtara (key) karşılık gelen veriyi değiştirir. Eğer aynı anahtar daha önce kaydedilmişse, yeni bir değerle değiştirilir. Eğer aynı anahtar daha önce kaydedilmemişse, SharedPreferences yeni bir veri ekler. Yani, yeni bir veri kaydetme yerine, mevcut veriyi günceller.

Örneğin yukarıdaki örnekte şu şekilde çalıştı:

Yeni Veri Kaydetme: Eğer daha önce belirttiğiniz anahtar (örneğin 'username') SharedPreferences'ta yoksa, setString ile kaydedilen değer bir yeni veri olarak eklendi.

Var Olan Veriyi Güncelleme: Eğer aynı anahtar zaten SharedPreferences’ta varsa, setString mevcut değeri güncelledi. Bu, eski değerin üzerine yeni değeri yazdı.

Yani, SharedPreferences set metodları her zaman yalnızca bir anahtar altında tek bir değer saklar. Aynı anahtar için iki farklı değer kaydedilemez. Eğer bir anahtar daha önce kaydedilmişse, yeni veri eski verinin yerine geçer.

Veriyi Silmek

Bir veriyi silmek için remove metodunu kullanabiliriz. Aşağıdaki örnekte, kaydedilen kullanıcı adını siliyoruz:

void deleteUsername() async {
final prefs = await SharedPreferences.getInstance();

await prefs.remove('username');
print("Kullanıcı adı silindi!");
}

Tüm Verileri Temizlemek

Eğer tüm SharedPreferences verilerini silmek isterseniz, clear metodunu kullanabilirsiniz:

void clearAllData() async {
final prefs = await SharedPreferences.getInstance();

await prefs.clear();
print("Tüm veriler temizlendi!");
}

SharedPreferences ile Kullanıcı Ayarlarını Kaydetme

SharedPreferences, özellikle kullanıcı ayarları gibi bilgileri saklamak için çok faydalıdır. Örneğin, bir kullanıcı temayı değiştirdiğinde bu tercihi kaydedebiliriz. Burada tabiki yazacağımız method isDarkMode adında bool bir parametre istiyor.

void saveThemePreference(bool isDarkMode) async {
final prefs = await SharedPreferences.getInstance();

await prefs.setBool('isDarkMode', isDarkMode);
print("Tema tercihi kaydedildi!");
}

Bunu daha sonra şu şekilde okuyabiliriz:

void getThemePreference() async {
final prefs = await SharedPreferences.getInstance();

bool isDarkMode = prefs.getBool('isDarkMode') ?? false;
print("Dark mode: $isDarkMode");
}

Veri Türleriyle Çalışmak

SharedPreferences, yalnızca String değil, farklı veri türlerini de saklayabilir. İşte bazı örnekler:

  • setIntprefs.setInt('key', 123);
  • setBoolprefs.setBool('key', true);
  • setDoubleprefs.setDouble('key', 3.14);
  • setStringListprefs.setStringList('key', ['apple', 'banana']);

Aynı şekilde, verileri okumak için de getIntgetBoolgetDouble, ve getStringList gibi metotlar kullanabilirsiniz.

Sık Sorulan Sorular

SharedPreferences ile Veri Kaydetmek Ne Kadar Güvenlidir?SharedPreferences, küçük veri saklama işlemleri için uygundur. Ancak, büyük veya hassas veriler için daha güvenli çözümler tercih edilmelidir.

SharedPreferences, Flutter Uygulamalarında Hangi Durumlarda Kullanılır?SharedPreferences, kullanıcı ayarları, tema tercihleri, oturum bilgileri ve küçük verilerin saklanmasında kullanılır.

Verileri SharedPreferences’ta Kaç Gün Saklayabilirim? Veriler, cihazda kalıcı olarak saklanır ve sadece kullanıcı veriyi manuel olarak silene kadar saklanır.

Sonuç

Flutter’da SharedPreferences kullanarak verilerinizi cihazda kalıcı hale getirmek çok basit ve etkilidir. Kullanıcı bilgilerini, tercihleri ve uygulama durumlarını saklamak için bu yöntemi kullanabilirsiniz. Ayrıca, SharedPreferences verilerini okuyup güncellemek de oldukça kolaydır. Bu sayede, SharedPreferences kullanarak uygulamanızda kalıcı veri saklamayı öğrenmiş oldunuz!

Buraya kadar okuduğunuz için teşekkür ederim.

Yazımı beğendiyseniz clap tuşuna basmayı ve diğer içeriklerimden haberdar olabilmek için abone olmayı unutmayın.

Teşekkürler.

Selin.

Flutter Package of the Week: image_picker

 

Hello, the second post in our package of the week series is about handling image files in our projects. And our package is image_picker. This package is one of the most common tools used by application developers, because it is a very common need for an application to select photos or videos from users’ devices.

What’s it for?

Image Picker lets you grab media files from the device’s gallery or directly from the camera, essentially making it easier for users to select photos or videos. Let’s say you’re making a profile photo add screen, you want to allow the user to select an image from the gallery or take a photo on the fly. With this package, that can be done with a few lines of code.

How to Use?

First you add the package to your pubspec.yaml file using the command below as usual:

flutter pub add image_picker
dependencies:
image_picker: ^1.1.2 //version number may vary

Then you need to import the package to the dart file you will use with the following line:

import 'package:image_picker/image_picker.dart';

As far as permits are concerned,

As of version 0.8.1 the Android app supports selecting (multiple) images on Android 4.3 or higher. So no configuration is required — the plugin should work out of the box.

But on iOS you need to add the following lines to the Info.plist file:

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

Now comes the fun part. The package provides an ImagePicker class that allows you to easily pick images from the gallery or camera. Here’s a simple example of how to use it:

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

In the code above, if the user selects an image from the gallery, the file path is assigned to the image variable. Likewise, if you want to use the camera, you can take a shot from the camera with the ImageSource.camera parameter.

It is also possible to select a video in the same way:

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

Furthermore, this package offers options to compress both photos and videos. This is a great feature, especially for optimizing large file sizes!

Now let’s see what customizations we can make using this package.

In Image Picker, you can also set resolution settings to control the size and quality of the media files that users upload. For example, if you want to take a low-resolution photo when using the camera, you can set the imageQuality parameter.

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

This way, you can also preserve the performance of the application. Low-sized images will load faster, especially if you are uploading media files over the internet.

You can also specify the size of the images with maxWidth, maxHeight and the preferredCameraDevice parameter for front or rear camera preference.

Below I am sharing an example of a project made using this package with all the codes.

!!! Since I created the project using iOS Simulator and there is no camera on the virtual device, the Camera button shows Error, but it works fine on the real device.

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

I will conclude this article by talking about its advantages and disadvantages.

The biggest advantage of the ImagePicker package is that users can select media files from the gallery or camera with just a few lines of code. You can also control file size and quality.

On the downside, you may need to manage performance when working with large media files. And setting platform-specific permissions manually can be a bit cumbersome.

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 a nutshell, Image Picker is one of the most popular packages for anyone who wants users to select media or use a camera in Flutter projects. If your app has features like profile photo, gallery selection, or video uploading, this package will give you a lot of peace of mind! It’s a simple and versatile solution.

I hope this was useful.

Happy coding.

Selin.