error handling etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
error handling etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

The 10 Most Common Errors and Solutions in Flutter: Simple Explanation for Beginners

In the first days when I started to learn Flutter, the error messages I received gave me a lot of trouble. There were moments when I didn’t know how to   deal with the warnings that appeared on the screen and where to start. Each new project brought a brand new error and solution process. Looking back now, these mistakes were actually the most valuable lessons I learnt. In this article, I would like to share the most common errors and their solutions while developing with Flutter, inspired by my own development processes.    If you are a newbie to Flutter like me, I hope this guide will make your work much easier.


1. “A RenderFlex overflowed by XX pixels”

When you see this error message, visualise a scene like this: You have filled the application screen with so many things that it has now overflowed and ‘overflowed’ off the edge of the screen! The size of the screen is not enough. This can happen, for example, when you put too many elements in a Row or Column widget. Think of it as if you filled a small box with too much stuff.

Solution: One of the things you can do in such cases is to make the page scrollable using SingleChildScrollView. So where the screen is not enough, the page can be scrolled up and down. Or you can wrap that multi-item area with Expanded or Flexible and let the widgets adjust themselves according to the size of the screen. In a way, this means ‘Spread out as much as there is space on the screen, don’t overflow’!

2. “setState() or markNeedsBuild() called during build”

Although this error seems a bit more technical, it is actually very simple: During the widget’s build process, you tell it ‘Let’s update again’ (you call setState). But you shouldn’t do this while the build is in progress, because Flutter hasn’t finished building the widget yet. If you update it then, it will throw an error saying ‘How can I update what I haven’t built yet?’.

Solution: You should call setState after the build is finished. So you need to be a little patient! It’s like saying ‘Let’s paint again’ before the child has finished a painting.

3. “Null check operator used on a null value”

This is a very common error and you will often encounter it in Flutter. You can think of it like this: You have an empty (null) glass in your hand, but you are trying to drink water from it. Flutter tells you, ‘This glass is empty, there is nothing to drink!’ In other words, you are trying to operate on a variable when there is no data in it.

Solution: To avoid this error, you should check whether the glass (variable) is empty. If it is empty, you should add something and continue. For example, you can give an alternative value with the ?? operator by saying ‘If empty, use this’. This way, when the glass is empty, you can take another glass and drink water.

4. “Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold”

This can get a little confusing. Let’s say you use a Scaffold on the page. This is the basic structure of application pages, it has AppBar, Body and so on. But you are trying to reach it from somewhere outside this Scaffold structure. For example, you want to open a snackbar, but you call it from the wrong place. Flutter says ‘Look, there is no structure inside this page, you can’t reach it’.

Solution: In this case, you should either call Scaffold from the right context or you can perform the operation using ScaffoldMessenger. In short, you need to knock on the right door!

5. “NoSuchMethodError: The method ‘X’ was called on null”

In this mistake, Flutter says to you: ‘You are trying to do something to something that doesn’t exist.’ For example, you call a method on an object (say a car object), but there is no object! You want to start the car, but the car doesn’t exist so it can start.

Solution: You need to check if it is null. If there is no car, call the car first, then do the operation. If you think it might be null at that moment, use a safe check (?..).

6. “type ‘Future<dynamic>’ is not a subtype of type ‘Widget’”

Now this error is a bit more related to async operations. You have written a function and the result of this function will come in the future (Future), but you want to show this result on the screen immediately. But that result is not ready yet! Flutter says, ‘Look, you were supposed to give me a widget, but you returned Future.’

Solution: In this case, you need to use FutureBuilder to show the result when it is ready. So, you shouldn’t try to open an envelope until the postman brings a letter!

7. “setState() called after dispose()”

This error occurs when you tell a widget ‘Let’s update’ when it has finished its work and has been disposed of. But it is no longer there! You call setState, but the widget is not there.

Solution: What you need to do is to check if the widget still exists. You should be careful not to take action on a widget that has finished its work. It’s like asking for a report from a finished employee, it’s gone!

8. “RenderBox was not laid out”

This error occurs when a widget cannot calculate the screen size. It’s as if you were going to place a piece of furniture in your room, but you didn’t measure the dimensions of the room first! Then you get an error because you can’t place the furniture.

Solution: You should not place furniture (widget) without knowing the dimensions of the room (screen). To solve this, you can use LayoutBuilder or MediaQuery to find out the screen size and arrange your widgets accordingly. Thus, everything will fit in its place.

9. “Expected a value of type ‘X’, but got one of type ‘Y’”

This error is actually very simple: someone at work asked you for a red file, but you gave him a blue file! In other words, Flutter was expecting one type (e.g. int), but you gave it another type (e.g. String).

Solution: You need to make sure you are using types correctly. If a function expects int, you should give it int. You have to be careful not to give the wrong file.

10. “Too many positional arguments”

This is a case where Flutter says ‘You’ve given me too much, I can’t handle this much’. You get this error when you send too many parameters to a function or widget. For example, someone says ‘Give me an apple’ and you give them five apples!

Solution: Send as many parameters as the function or widget needs. So, you can solve the error by checking ‘What was asked of me, what did I give?’.

Although these mistakes were a bit frustrating at first, I realised how much I progressed in my projects as I solved each one. Remember, making mistakes is part of learning, and each mistake actually makes you a better developer. If you encounter the mistakes in this article, don’t panic! Understanding and solving them will make you even more proficient in Flutter. I hope this guide, inspired by my own development process, will help you. Good luck and remember, every mistake is a step forward!

Thanks for reading.

Selin.

Flutter’da En Sık Karşılaşılan 10 Hata ve Çözümleri: Yeni Başlayanlar İçin Basit Anlatım

Flutter öğrenmeye başladığım ilk günlerde, aldığım hata mesajları beni bir hayli zorladı. Ekranda beliren uyarılarla nasıl başa çıkacağımı, nereden başlayacağımı bilemediğim anlar oldu. Her yeni proje, yepyeni bir hata ve çözüm süreci getirdi. Şimdi geriye dönüp baktığımda, bu hatalar aslında öğrendiğim en değerli derslerdi. Bu yazıda, Flutter ile geliştirme yaparken en sık karşılaşılan hataları ve çözümlerini, bizzat kendi geliştirme süreçlerimden de esinlenerek paylaşmak istiyorum. Eğer sen de benim gibi Flutter’a yeni başlıyorsan, bu rehberin işini oldukça kolaylaştıracağını umuyorum.


1. “A RenderFlex overflowed by XX pixels”

Bu hata mesajını gördüğünde gözünde şöyle bir sahne canlandır: Uygulama ekranını o kadar çok şeyle doldurmuşsun ki, artık ekranın dışına taşmış ve ekranın kenarından dışarıya doğru “overflow” olmuş! Ekranın boyutu yetmiyor yani. Bu durum, mesela bir Row veya Column widget'ı içine çok fazla eleman koyduğunda olabilir. Sanki küçük bir kutuya fazla eşya doldurmuşsun gibi düşün.

Çözüm? Bu tür durumlarda yapabileceğin şeylerden biri SingleChildScrollView kullanarak sayfayı kaydırılabilir yapmak. Yani ekranın yetmediği yerde, sayfa yukarı aşağı kaydırılabilir olsun. Ya da o çok eşyalı alanı Expanded veya Flexible ile sarmalayarak, eşyanın (widget'ların) kendini ekranın boyutuna göre ayarlamasını sağlayabilirsin. Bir nevi "Ekranda ne kadar yer varsa o kadar yayıl, taşma" demek bu!

2. “setState() or markNeedsBuild() called during build”

Bu hata biraz daha teknik gibi gözükse de aslında çok basit: Widget’ın çizim işlemi (build) sırasında, ona “Hadi bakalım tekrar güncellen” diyorsun (setState çağırıyorsun). Ama build işlemi devam ederken bunu yapmaman lazım, çünkü Flutter daha widget'ı oluşturmayı bitirmedi. O sırada güncelle dersen, "Daha yapmadığım şeyi nasıl güncelleyeyim?" diye bir hata verir.

Çözüm? setState çağrını, build bittikten sonra yapmalısın. Yani biraz sabırlı olman gerekiyor! Çocuk bir resmi tamamlamadan, "Hadi yeniden boya" demek gibi bir şey bu.

3. “Null check operator used on a null value”

Bu çok yaygın bir hatadır ve Flutter’da sık sık karşılaşırsın. Kısaca şöyle düşünebilirsin: Elinde boş (null) bir bardak var ama sen bu bardaktan su içmeye çalışıyorsun. Flutter da sana diyor ki, “Bu bardak boş, içecek bir şey yok!” Yani bir değişkenin içinde hiç veri yokken, o veriyle işlem yapmaya çalışıyorsun.

Çözüm? Bu hatayı almamak için bardağın (değişkenin) boş olup olmadığını kontrol etmelisin. Eğer boşsa, bir şeyler ekleyip öyle devam etmelisin. Mesela ?? operatörüyle "Eğer boşsa şunu kullan" diyerek alternatif bir değer verebilirsin. Bu sayede, bardak boş olduğunda eline başka bir bardak alıp su içersin.

4. “Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold”

Bu biraz kafayı karıştırabilir. Diyelim ki sayfada bir Scaffold kullanıyorsun. Bu, uygulama sayfalarının temel yapısıdır, içinde AppBar, Body falan olur. Ama sen bu Scaffold yapısının dışında bir yerden ona ulaşmaya çalışıyorsun. Mesela snackbar açmak istiyorsun ama yanlış yerden çağırıyorsun. Flutter da "Bak, bu sayfanın içinde o yapı yok, ona ulaşamazsın" diyor.

Çözüm? Bu durumda ya Scaffold'u doğru context'ten çağırmalısın ya da ScaffoldMessenger kullanarak işlemi gerçekleştirebilirsin. Kısacası, doğru kapıyı çalmak lazım!

5. “NoSuchMethodError: The method ‘X’ was called on null”

Bu hatada Flutter sana şöyle diyor: “Sen, olmayan bir şeye bir şey yapmaya çalışıyorsun.” Örneğin, bir objeye (mesela bir araba objesi) bir metod çağırıyorsun ama ortada o obje yok! Arabayı çalıştırmak istiyorsun ama aslında araba ortada yok ki çalışsın.

Çözüm? null olup olmadığını kontrol etmelisin. Araba yoksa, önce arabayı çağır, sonra işlemi yap. Eğer o an nullolabilir diyorsan, güvenli kontrolle (?.) işini garantiye al.

6. “type ‘Future<dynamic>’ is not a subtype of type ‘Widget’”

Şimdi bu hata biraz daha async işlemlerle ilgili. Bir fonksiyon yazmışsın ve bu fonksiyonun sonucu ileride gelecek (Future), ama sen bu sonucu hemen ekranda göstermek istiyorsun. Ama o sonuç daha hazır değil! Flutter da diyor ki, “Bak, sen bana bir widget vermen gerekiyordu ama Future döndürdün.”

Çözüm? Bu durumda FutureBuilder kullanarak, sonucu hazır olduğunda göster demen gerekiyor. Yani, gelecek bir mektubu postacı getirene kadar boşuna zarfı açmaya çalışmamak lazım!

7. “setState() called after dispose()”

Bu hata, bir widget artık işini bitirmiş ve bellekten temizlenmişken (disposeolmuşken), ona "Hadi güncellen" dediğinde çıkar. Ama o artık yok! Sen setState çağırıyorsun ama o widget orada değil.

Çözüm? Yapman gereken şey, widget halen var mı diye kontrol etmek. İşini bitirmiş bir widget üzerinde işlem yapmamaya dikkat etmelisin. Yani, işi bitmiş bir çalışandan rapor istemek gibi, artık o gitmiş!

8. “RenderBox was not laid out”

Bu hata, bir widget’ın ekran boyutunu hesaplayamadığı zaman karşına çıkar. Sanki bir mobilyayı odana yerleştireceksin ama önce odanın boyutlarını ölçmemişsin! Sonra mobilyayı yerleştiremediğin için hata alıyorsun.

Çözüm? Odanın (ekranın) boyutlarını bilmeden mobilya (widget) yerleştirmemelisin. Bunu çözmek için LayoutBuilderya da MediaQuerykullanarak ekran boyutunu öğrenip, ona göre widget'larını düzenleyebilirsin. Böylece her şey yerli yerine oturur.

9. “Expected a value of type ‘X’, but got one of type ‘Y’”

Bu hata aslında çok basit: Bir iş yerinde biri senden kırmızı dosya istemiş ama sen gidip mavi dosya vermişsin! Yani, Flutter bir tür bekliyor (mesela int), ama sen ona başka bir tür (mesela String) vermişsin.

Çözüm? Türleri doğru şekilde kullandığından emin olman lazım. Eğer bir fonksiyon int bekliyorsa, ona int vermelisin. Yanlış dosyayı vermemek için dikkatli olmak gerek.

10. “Too many positional arguments”

Bu da Flutter’ın “Çok fazla şey verdin, ben bu kadarını kaldıramam” dediği bir durum. Bir fonksiyona veya widget’a gereğinden fazla parametre gönderdiğinde bu hatayı alırsın. Mesela biri sana “Bir elma ver” diyor, sen ona beş elma veriyorsun!

Çözüm? Fonksiyonun veya widget’ın ihtiyaç duyduğu kadar parametre gönder. Yani, “Benden ne istendi, ne verdim?” diye bir kontrol yaparak hatayı çözebilirsin.

Flutter öğrenme süreci boyunca karşıma çıkan bu hatalar, başlarda biraz moral bozucu olsa da her birini çözdükçe projelerimde ne kadar ilerlediğimi fark ettim. Unutma, hata yapmak öğrenmenin bir parçası ve her hata aslında seni daha iyi bir geliştirici yapıyor. Eğer sen de bu yazıdaki hatalarla karşılaşırsan, panik yapma! Hataları anlamak ve çözmek, seni Flutter’da daha da yetkin hale getirecek. Kendi geliştirme sürecimden esinlenerek yazdığım bu rehberin sana yardımcı olmasını umuyorum. Başarılar ve unutma, her hata bir adım daha ileriye gitmen demek!

Okuduğun için teşekkürler.

Selin.