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

Here is What I Learned About Form Validation While Building My Flutter App

 


Hi Flutter Developers 👊 Today I want to talk about something I experienced while developing an application with Flutter. While working on my own Flutter project, I quickly realized that validating user input was essential. Without it, users could enter anything into the fields — causing errors and potentially crashing the app. I wanted to ensure my app handled input safely, so I dug into Flutter’s validation tools. Here’s what I learned along the way, and a few practical tips to help you set up form validation easily.

Starting with a Basic Form Setup

To begin, I created a simple form layout in Flutter using the Form widget. This widget was super handy because it wraps around all the input fields and lets you validate them together. Here’s the setup I used:

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

Scaffold(
backgroundColor: Colors.blueAccent[100],
body: Padding(
padding: EdgeInsets.all(12.0),
child: Form(
key: _formKey, // a unique key for the form
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true, // hides the password for privacy
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
),
),
),



The Form widget required a GlobalKey to track its state, which ended up being super helpful for checking if everything was filled out correctly before moving forward. I used _formKey to manage this, and it allowed me to handle all validations from one place.

Adding Validation Rules: Email and Password

Next, I needed validation rules, especially for the email and password fields. To make sure these fields contained valid information, I added a validatorfunction to each TextFormField.

Here’s what I did for the email and password:

TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Enter a valid email';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
} else if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
),

I found that having clear error messages made a big difference. Instead of vague errors, I wrote messages that actually guided users on what to fix — like “Enter a valid email” or “Password must be at least 6 characters.”

Submitting the Form and Checking Validity

I wanted to make sure that when the user clicked the submit button, it would check all the validations at once. I used the _formKey.currentState!.validate() function for this. It goes through each field, runs the validator, and only lets the form submit if all fields are valid.

Here’s how I structured my submit function:

void _submitForm() {
if (_formKey.currentState!.validate()) {
print('Form is valid');
// Process data or navigate to the next screen
} else {
print('Form is not valid');
}
}

And here’s the result:


Using validate() turned out to be simple yet powerful; if any field is invalid, it prevents the form from submitting. Plus, it highlights the fields that need attention, which is super helpful for users.

Some Tips

  • Friendly error messages go a long way! When I tested the form, I noticed users responded better to specific, clear instructions.
  • For email validation, I used a regular expression to check if the user’s entry was formatted correctly. Flutter has great support for Regex, and I recommend it for fields like email, phone numbers, or anything with a specific format.
  • I noticed that some apps validate as you type, which gives immediate feedback to users. Flutter makes this possible by using a TextEditingController, although I decided to keep my form simple for now.
  • For forms with more fields or complex rules, packages like flutter_form_builder can save time. I didn’t need it for this project, but it’s worth exploring if you’re working on larger forms.

As a result learning to set up validation in Flutter was a game-changer for my project. It made my app more reliable and user-friendly, and I got a better handle on managing forms in Flutter. If you’re starting with validation, stick to the basics, and don’t be afraid to customize error messages for a smoother user experience.

Validation might seem tricky at first, but it’s a crucial skill that’s totally worth mastering. Let me know if you have questions or need help with your own Flutter forms!

Thanks for reading.

Selin.

Flutter’da Form Doğrulamayı Öğrenirken Neler Keşfettim?

 


Merhaba Flutter Geliştiricileri 👊 Bugün Flutter ile bir uygulama geliştirirken yaşadığım bir şeyden bahsetmek istiyorum. Kendi Flutter projemi geliştirirken, kullanıcı girişlerini doğrulamanın ne kadar önemli olduğunu fark ettim. Doğrulama olmadan kullanıcılar her türlü veriyi girebiliyor ve bu da hatalara, hatta uygulamanın çökmesine sebep olabiliyor. Uygulamamın güvenli bir şekilde çalışması için Flutter’ın doğrulama araçlarını araştırdım. İşte bu süreçte öğrendiklerim ve form doğrulamayı kolayca kurmanız için birkaç pratik ipucu!

Basit Bir Form Oluşturma

İlk olarak Flutter’da Form widget'ını kullanarak basit bir form düzeni oluşturdum. Bu widget tüm giriş alanlarını bir araya getiriyor ve bunları tek seferde doğrulamama olanak tanıyor. İşte benim kullandığım düzen:

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

Scaffold(
backgroundColor: Colors.blueAccent[100],
body: Padding(
padding: EdgeInsets.all(12.0),
child: Form(
key: _formKey, // forma özel bir anahtar
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true, // Şifreyi gizlemek için
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
),
),
),


Form widget'ı, formun durumunu izlemek için bir GlobalKey gerektiriyor. validate() gibi fonksiyonları kullanarak her şeyin doğru şekilde doldurulup doldurulmadığını bu anahtar sayesinde kontrol edebiliyorum.

Doğrulama Kuralları Ekleme: E-posta ve Şifre

Sırada, özellikle e-posta ve şifre alanları için doğrulama kuralları tanımlamak var. Bu alanların geçerli bilgi içerdiğinden emin olmak için her TextFormField'e bir validator fonksiyonu ekledim.

İşte e-posta ve şifre için doğrulama kurallarım:

TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Enter a valid email';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
} else if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
),

Açık ve anlaşılır hata mesajlarının büyük fark yarattığını gördüm. Belirsiz uyarılar yerine, kullanıcılara neyi düzeltmeleri gerektiğini net bir şekilde anlatmak işlerini kolaylaştırdı.

Formu Gönderme ve Geçerlilik Kontrolü

Kullanıcı gönder düğmesine tıkladığında, tüm doğrulamaların aynı anda kontrol edilmesini istedim. Bunun için _formKey.currentState!.validate()fonksiyonunu kullandım. Bu fonksiyon her alanı kontrol eder, validator’ları çalıştırır ve yalnızca tüm alanlar geçerliyse formu gönderir.

Gönderme fonksiyonumu şöyle yazdım:

void _submitForm() {
if (_formKey.currentState!.validate()) {
print('Form is valid');
// Process data or navigate to the next screen
} else {
print('Form is not valid');
}
}

Ve sonuç şu şekilde:


validate() fonksiyonunu kullanmak oldukça pratik; eğer herhangi bir alan geçersizse formu göndermeyi engelliyor. Ayrıca, dikkat edilmesi gereken alanları da vurguluyor ki bu kullanıcılar için oldukça yararlı.

Birkaç ipucu:

  • Samimi hata mesajları çok etkili! Test ettiğimde, kullanıcıların daha net talimatlar aldıklarında daha iyi yanıt verdiğini fark ettim.
  • E-posta doğrulaması için kullanıcı girişinin doğru formatta olup olmadığını anlamak için bir regular expression (Regex) kullandım. E-posta, telefon numarası gibi belirli bir format gerektiren alanlarda Regex öneririm.
  • Bazı uygulamalar kullanıcı yazarken doğrulama yapar, bu da kullanıcıya anında geri bildirim verir. Bu projede TextEditingControllerkullanmadım, ama bu özelliği büyük formlar için düşünebilirim.
  • Daha fazla alan veya karmaşık kuralları olan formlar için flutter_form_builder gibi paketler zaman kazandırabilir. Bu projede gerek duymadım ama daha büyük formlar üzerinde çalışırken keşfetmeye değer.

Flutter’da doğrulama ayarlamayı öğrenmek projem için bir dönüm noktası oldu. Uygulamamı daha güvenilir ve kullanıcı dostu hale getirdi, ayrıca formları nasıl yönetebileceğimi anlamama yardımcı oldu. Doğrulamaya yeni başlıyorsanız, temel konularla başlayın ve kullanıcı deneyimini iyileştirmek için hata mesajlarını özelleştirmekten çekinmeyin.

Doğrulama ilk başta zor gibi görünebilir, ancak güvenilir bir uygulama oluşturmak için öğrenmeye kesinlikle değer. Kendi Flutter formlarınızda başarılar dilerim!

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

Selin.