Open In App

Flutter – Phone Number Validator

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, Validating phone numbers is a crucial step to ensure data accuracy and enhance user experience. Flutter, provides a powerful package for handling phone number input and validation with the intl_phone_number_input package. In this article, we’ll explore how to streamline phone number validation in Flutter using the intl_phone_number_input package. This package offers a beautiful user interface for entering international phone numbers, with built-in validation mechanisms, making it a better choice for developers looking to enhance their applications with robust input functionality. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Adding the Dependencies

Here we have to add the the following dependencies to our pubspec.yaml file.

dependencies:
intl_phone_number_input: ^0.7.4

Or, Simply you can run the below command in your VS code Terminal.

flutter pub add intl_phone_number_input

Step 3: Import the Package

First of all import material.dart package and the intl_phone_number_input package.

import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';

Step 4: Execute the main Method

Here the execution of our app starts.

Dart




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


Step 5: Create MyApp Class

In this class we are going to implement the MaterialApp, here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          primarySwatch: Colors.green, // Set the app's primary theme color
        ),
        debugShowCheckedModeBanner: false,
        home: MyForm());
  }
}


Step 6: Create MyForm Class

The MyForm class in Flutter serves as a stateful widget, it enables users to input and validate international phone numbers. The essential components include a global key for form identification, a variable to store the selected phone number and ISO code, and a widget tree structure composed of an InternationalPhoneNumberInput for number input, and an ElevatedButton to trigger form validation and submission. Callbacks such as onInputChanged and onInputValidated handle dynamic changes and additional validation logic. Upon valid form submission, the class prints the phone number and ISO code to the console. Comments are added for better understandings.

// InternationalPhoneNumberInput widget for phone number input
InternationalPhoneNumberInput(
// Callback for when the input changes
onInputChanged: (PhoneNumber number) {
_phoneNumber = number;
},
// Callback for when the input is validated
onInputValidated: (bool value) {
// You can perform additional validation here if needed
},
// Configuration for the country selector
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.DIALOG,
),
// Ignore blank input
ignoreBlank: false,
// Auto-validation mode
autoValidateMode: AutovalidateMode.onUserInteraction,
// Style for the country selector
selectorTextStyle: TextStyle(color: Colors.black),
// Initial value for the phone number input
initialValue: _phoneNumber,
// Controller for the text field
textFieldController: TextEditingController(),
// Decoration for the input field
inputDecoration: InputDecoration(
labelText: 'Phone Number',
border: OutlineInputBorder(),
),
// Format input (e.g., adding spaces between digits)
formatInput: false,
),

Dart




class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}
  
class _MyFormState extends State<MyForm> {
  // Key to uniquely identify the form
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  
  // Store the selected phone number and ISO code
  PhoneNumber _phoneNumber = PhoneNumber(isoCode: 'IN');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Phone Number Validation'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // InternationalPhoneNumberInput widget
              // for phone number input
              InternationalPhoneNumberInput(
                // Callback for when the input changes
                onInputChanged: (PhoneNumber number) {
                  _phoneNumber = number;
                },
                // Callback for when the input is validated
                onInputValidated: (bool value) {
                  // You can perform additional validation here if needed
                },
                // Configuration for the country selector
                selectorConfig: SelectorConfig(
                  selectorType: PhoneInputSelectorType.DIALOG,
                ),
                // Ignore blank input
                ignoreBlank: false,
                // Auto-validation mode
                autoValidateMode: AutovalidateMode.onUserInteraction,
                // Style for the country selector
                selectorTextStyle: TextStyle(color: Colors.black),
                // Initial value for the phone number input
                initialValue: _phoneNumber,
                // Controller for the text field
                textFieldController: TextEditingController(),
                // Decoration for the input field
                inputDecoration: InputDecoration(
                  labelText: 'Phone Number',
                  border: OutlineInputBorder(),
                ),
                // Format input (e.g., adding spaces between digits)
                formatInput: false,
              ),
              SizedBox(height: 20),
              // Submit button
              ElevatedButton(
                onPressed: () {
                  // Validate the form
                  if (_formKey.currentState?.validate() ?? false) {
                    // Form is valid, perform your actions here
                    print('Form is valid');
                    print('Phone number: ${_phoneNumber.phoneNumber}');
                    print('ISO code: ${_phoneNumber.isoCode}');
                  } else {
                    // Form is invalid
                    print('Form is invalid');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          primarySwatch: Colors.green, // Set the app's primary theme color
        ),
        debugShowCheckedModeBanner: false,
        home: MyForm());
  }
}
  
class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}
  
class _MyFormState extends State<MyForm> {
  // Key to uniquely identify the form
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  
  // Store the selected phone number and ISO code
  PhoneNumber _phoneNumber = PhoneNumber(isoCode: 'IN');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Phone Number Validation'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // InternationalPhoneNumberInput widget for phone number input
              InternationalPhoneNumberInput(
                // Callback for when the input changes
                onInputChanged: (PhoneNumber number) {
                  _phoneNumber = number;
                },
                // Callback for when the input is validated
                onInputValidated: (bool value) {
                  // You can perform additional validation here if needed
                },
                // Configuration for the country selector
                selectorConfig: SelectorConfig(
                  selectorType: PhoneInputSelectorType.DIALOG,
                ),
                // Ignore blank input
                ignoreBlank: false,
                // Auto-validation mode
                autoValidateMode: AutovalidateMode.onUserInteraction,
                // Style for the country selector
                selectorTextStyle: TextStyle(color: Colors.black),
                // Initial value for the phone number input
                initialValue: _phoneNumber,
                // Controller for the text field
                textFieldController: TextEditingController(),
                // Decoration for the input field
                inputDecoration: InputDecoration(
                  labelText: 'Phone Number',
                  border: OutlineInputBorder(),
                ),
                // Format input (e.g., adding spaces between digits)
                formatInput: false,
              ),
              SizedBox(height: 20),
              // Submit button
              ElevatedButton(
                onPressed: () {
                  // Validate the form
                  if (_formKey.currentState?.validate() ?? false) {
                    // Form is valid, perform your actions here
                    print('Form is valid');
                    print('Phone number: ${_phoneNumber.phoneNumber}');
                    print('ISO code: ${_phoneNumber.isoCode}');
                  } else {
                    // Form is invalid
                    print('Form is invalid');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads