10 C
New York
Monday, November 27, 2023

Live email validation in Flutter

In this article, we’ll build a small Flutter app to demonstrate how to validate email while the user is typing. Here’s what you’ll see when running the code at the end of this tutorial:

Let’s Write Code

1. Create a brand new Flutter projectAdvertisements

flutter create email_validation_app

2. Install the email_validator package

Run:

dart pub add email_validator

Then:

flutter pub get 

AdvertisementsNote: If you want to use a regular expression instead of a third-party plugin to validate email in Flutter, see this article.

3. Open your /lib/main.dart file, remove all of the default code and add the following:

import 'package:flutter/material.dart';

// import the email validator package
import 'package:email_validator/email_validator.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,

      title: 'Flutter Tutorial',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final emailController = TextEditingController();

  // This message will be displayed under the email input
  String message = '';

  void validateEmail(String enteredEmail) {
    if (EmailValidator.validate(enteredEmail)) {
      setState(() {
        message = 'Your email seems nice!';
      });
    } else {
      setState(() {
        message = 'Please enter a valid email address!';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Tutorial'),
        ),
        body: Container(
          padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 0),
          child: Column(children: [
            // Input email
            TextField(
              decoration: const InputDecoration(labelText: 'Your Email'),
              keyboardType: TextInputType.emailAddress,
              controller: emailController,
              onChanged: (enteredEmail) => validateEmail(enteredEmail),
            ),

            // Just add some space
            const SizedBox(height: 20),

            // Display the message
            Text(message)
          ]),
        ));
  }
}

4. Try it:

flutter run 

Conclusion

You’ve learned a simple and quick solution to validate emails in Flutter. If you’d like to explore more new and fascinating things about the awesome SDK, take a look at the following articles:

Advertisements

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles