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.

Is it Possible to Stay Calm in 2-Year-Old Syndrome? Yes!

 

photo by chatGPT

Hello everyone. This time I came to you with the need to talk about something other than what I have written so far, because I have not been able to deal with software, which is my main focus, in depth for a while. I thought I should at least write about what I am going through, maybe it will inspire someone.

Let’s talk about the subject. I have a 2.5 year old son who never stands still, who makes his father and me “wrapped around his finger” but whose smile is worth the world. 🧿

As the age suggests, we are experiencing what is called “2 year old syndrome” to the bone. Today I will tell you what it is. Then I was enlightened by a book I read, and I will summarize what I learned from it. If there is a bored, overwhelmed parent somewhere, I hope it will reach them and I will be able to provide some relief.

Let’s start…

What is 2-Year-Old Syndrome?

“2 year old syndrome” is not actually a medical definition, but a colloquial expression. This period usually lasts between the ages of 18 months and 3.5 years and is a transition period when children start to express themselves, but still don’t know how to express themselves. (I know 3.5 years is too long, we still have 1 year to go 😭)

In this period, children try to say: “I am in!”.

They want to decide for themselves what to do. But since they are not competent enough to do this, both they and their parents have a lot of difficulty.

This leads to a lot of stubbornness, tantrums, behaviors such as “no!”, “I will do it!”, “I don’t want to!”.

For example, lying on the floor in the mall because they don’t get what they want, shouting at the top of their lungs, crying, wanting to throw salt into the boiling food on the stove, etc. How do I know? 😊

Why do they behave like this?

A sense of self develops: The child starts to search for an answer to the question “who am I?”. He/she feels that he/she is an individual, but does not know how to manage this individuality.

He does not recognize and cannot regulate his emotions: Happy, angry, sad, scared… All emotions are present, but their ability to recognize and control their emotions has not yet developed. Therefore, they can shout, cry, throw themselves on the floor.

Speech skills are limited: He cannot say everything he wants. Since words are not enough, he tries to express himself with movements such as shouting, crying, jumping. Ours speaks very well but the result is the same 😂🧿

Why do they always get stubborn?

Because they want to be the decision maker. Situations like “not eating”, “not sleeping”, “not getting dressed” are actually places where they try to show that they are in control.
So sometimes they refuse not because the food tastes bad, but because they want to be the decider. For a while, we had an attitude like “Let’s go whenever you want, you can eat whatever you want”. We realized that we couldn’t cope with it and there was no equivalent in real life, so we stopped. 😒

Too Active and Dangerous Behaviors?

2.5 years old is a period when movement is at its peak. Muscles are developing, energy is high, curiosity never ends.

But there is no perception of danger. That’s why he jumps, climbs, falls, hurts… And when these behaviors cannot be stopped, it exhausts the parents too. It is not even possible to direct them to something else, let alone stop them. I can hear you saying, “Let’s get through this period without injuring ourselves.” 😂

Why is the Parenting Relationship Difficult?

This is a time when not only the child’s patience is tested, but also that of the parents. Constant conflict, lack of sleep, food fights, social pressure, it is normal to wear out as a couple.

While it is difficult to raise a child even when everything is fine, in such a period, spouses may blame each other, defend different methods, and even communication may break down.

I read somewhere that if you don’t divorce your spouse during your child’s 2 year old syndrome, you will never divorce again. Of course, this is a bit of an exaggerated description, but really, relationships, peace at home, etc. are shelved for a while.

So What Can We Do?

What I have written in this section is what we groped and tried before we met the miraculous book I am about to talk about, and after reading the book, we realized that there is still a lot more to do, although we have made some progress.

1. Offer options instead of saying no

For example, when we used to say “We need to go to the market, let’s get dressed”, we would get the answer “Nooooo, I’m not going, I’m staying at home” and we would try to convince them. At this stage, the market we were going to was closed and we couldn’t even make it. Then we changed our question to:

“Do you want to walk to the grocery store, or should we drive to the one further away?”

Or we started giving choices about food:

“Do you want to eat with yogurt or plain?”

The child who initially shouted “I don’t want to eat” started to say “With yogurt, of course” and sat down at the table.

This method both reduces stubbornness and gives the child the feeling of “I chose, so what I say goes”.

2. Establish routines

We have started to plan our day in certain ways: breakfast followed by play and free time in the morning, then lunch, then a flexible routine that includes a stubborn and flexible routine for sleep, then a light snack, games, dinner. Although the times sometimes deviate, we make sure that the order is generally the same. Even though this may seem like a compulsion to stay at home especially during the day, I personally prefer a peaceful child at home rather than a screaming child outside. 😌 Because habits such as eating, sleeping and playing at the same time give the child confidence.

3. Try to stay calm when you get stubborn

This part is so hard. But it gets worse when you yell. I’ve experienced it many times. He doesn’t calm down because you yell. When you stay calm, after a while he has to calm down, because it’s like you didn’t give him what he wanted, and his anger dies down. Unfortunately this is the way it is.

4. Direct to prevent dangerous movements

“It’s dangerous to jump from here, but let’s make a jumping area out of pillows.” But I have to admit that this method doesn’t always work either. “No, it doesn’t make a sound when I jump on the pillows, I want it to make a sound”, at least that’s how it is with us. 😔

5. Name your feelings

“You are very angry right now because what you wanted didn’t happen. I understand that.”

I’ve noticed that whenever I say this sentence when she is crying, even if she doesn’t stop completely, her tempo drops and she goes into listening mode. Especially “I understand” is like a magic word.
It helps him to recognize his feelings over time.

6. Talk openly with your partner

Who can tolerate what and how much, what kind of language do you use, do you make decisions about the child together… It helps a lot to talk about these things honestly, without judgment. Sometimes we do something like a division of labor. Whoever has more patience and tolerance that day says “okay, I have today”. And I believe this works very well.

Ready Made Sentences to Use in Difficult Times

In this section, I have written ready-made sentences that I found from different sources. Some of them I have changed a little, some of them I use verbatim. Some of them have worked and some of them have not. But it is always worth a try.

Temper Tantrum:
🗨️ “I realize you’re very angry right now, I’ll stay with you if you want, we can hug when you’re ready.”
🗨️ “You can yell, but without hurting anyone. You can yell at the pillow if you want.”

When you don’t want to eat:
🗨️ “You may not want to eat right now, that’s normal. I’ll leave you your plate in a moment if you feel like it.”
🗨️ “You can choose one of these three things. You don’t have to eat them all.”

Behaviors such as jumping and jumping:
🗨️ “It is dangerous to jump from here. But look, here is a jumping place we made out of cushions.”
🗨️ “If you want to jump, we can make a safe game with you.”

When he doesn’t want to sleep:
🗨️ “Even though you are not sleepy right now, your body needs rest. Let’s read a book and lie down for a while, and if you feel sleepy, we’ll close your eyes.”

Now let’s talk about the famous book. The title of the book is: Boundaries, No Boundaries. Author: Assoc. Prof. Dr. Saniye Bencik Kangal. Also known as academiciananne. I cannot recommend the book because I cannot find the English edition of the book, but I will provide a brief summary below.

When my son was 5–6 months old, I read the author’s Korkma! You are a Good Mother, and that was a period when we were struggling a lot with my son’s sleep problems and we were tired, it was very good. Afterwards, I never thought about whether she had other books or if I could benefit from them. I regret it.

I came across this book by chance when I was looking for another book and maybe it is very meaningful that it coincided with a period when we have been struggling with my son for a while and decided to change something, I don’t know.

I finished the book in 2 days because I was very interested in it and I found a lot of things from my own life and applicable. Now I will share with you the additional information I learned from the book.

Small but Powerful Changes I’ve Made in My Life from the Book

  • Instead of “Don’t shout!” → “I can see you are angry, do you want to shout into the pillow?”
  • Instead of “Don’t!” → “I can’t let you do that, but we can find another way.”
  • Instead of “You’re going to sleep right now!” → “Now it’s time to rest, choose your book if you want.”

These small changes have softened big conflicts.
And best of all, I learned to recognize my own emotions while making space for my child’s.

What I Remember from the Book

  • Try to understand the child’s feelings, not their behavior.
  • Setting limits does not reduce love. On the contrary, the child feels safe.
  • Instead of saying “no”, offer alternatives: “We can’t do this now, but we can do that later.”
  • Patience is difficult, but children are learning.
  • Without regulating our own inner voice, it is difficult to hear the child’s voice.

Favorite Sentences from the Book

“In order to prevent the wounds of your unseen emotions as a child from opening in your child, you need to clean those wounds one by one with oxygenated water. I know it is difficult, but every emotion you reject, every unresolved issue can deeply affect your parenting attitudes. The way to raise a happy and fulfilled child is to be such a parent.”

“Children follow the rules, unfortunately it is the adults who cannot enforce them consistently.”

“A child needs most of all to feel understood by his/her parents and most of all to know that he/she is valued in the family. A child who cannot find this in his/her family looks for this value in the eyes and words of others throughout his/her life. Because they have not realized their self-worth.”

“There is no need to have duck with orange on the table, the only thing needed at the table is conversation.”

Finally, don’t forget!

  • You’re not a bad mother.
  • You’re not a bad father.
  • This phase is temporary.
  • Sometimes just a hug can make everything better.
  • Getting support is not weakness, it is strength. (Expert support can be sought if necessary.)

I hope I have reduced someone’s fatigue and exhaustion a little bit and created a small idea.

Thank you for reading.

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

Can’s mom.

Selin.