Flutter phone number input

Overview

phone_form_field

Flutter phone input integrated with flutter internationalization

Features

  • Totally cross platform, this is a dart only package / dependencies
  • Internationalization support, without bloated json with all translations.
  • Phone number validation
  • Extends Flutter's FormField
  • Uses dart phone_numbers_parser for parsing

Demo

Demo available at https://cedvdb.github.io/phone_form_field/

demo img

Usage

PhoneFormField(
  initialValue: phoneNumber,
  autofocus: true,
  decoration: InputDecoration(
    labelText: 'Phone',
    border: OutlineInputBorder(),
    // ...
  ),
  onChanged: (p) => setState(() => phoneNumber = p!),
  onSaved: (p) => setState(() => phoneNumber = p),
  phoneNumberType: null, // could be PhoneNumberType.mobile or phoneNumberType.fixed for more specific validation

),

Internationalization

Include the delegate

  return MaterialApp(
    localizationsDelegates: [
      ...GlobalMaterialLocalizations.delegates,
      PhoneFieldLocalization.delegate
    ],
    supportedLocales: [
      const Locale('en', ''),
      const Locale('es', ''),
      const Locale('fr', ''),
      const Locale('ru', ''),
      // ...
    ],

Tnat's it.

A bunch of languages are built-in:

- 'ar',
- 'de',
- 'en',
- 'es',
- 'fr',
- 'hin',
- 'it',
- 'nl',
- 'pt',
- 'ru',
- 'zh',

If one of the language you target is not supported you can submit a pull request with the translated file in assets/translation

Comments
  • feat(validator): allow to use custom validator

    feat(validator): allow to use custom validator

    PR Type

    New feature

    BC Break

    Yes, see CHANGELOG file

    Description

    Allow end user to define a custom validator

    Sample

    PhoneFormField(
      validator: (PhoneNumber? phoneNumber) {
        if (phoneNumber == null) {
          return null;
        }
        final PhoneParser parser = PhoneParser();
        if (!parser.validate(phoneNumber, PhoneNumberType.mobile)) {
          return 'not a mobile line';
        }
        if (!parser.validate(phoneNumber)) {
          return 'invalid format';
        }
      },
    );
    
    opened by emri99 41
  • Validate empty inputs and allow flag and dial code to be shown when field is empty

    Validate empty inputs and allow flag and dial code to be shown when field is empty

    Hey, love the package, best I've found for a phone input in Flutter.

    2 things:

    1. What's the recommended way to require the field? I'd like to validate empty inputs as errors (I can see there is some discussion of this in #16).
    2. Is it possible to always show the button with the flag and dial code in the input field, rather than only when it has focus or input?

    Thanks.

    opened by davidjaldred 19
  • feat(contry-selector): add favorites countries & few others props

    feat(contry-selector): add favorites countries & few others props

    • add properties :
      • favoriteCountries : list of isoCode to be displayed on top of the list
      • sortCountries : whether countries should be sorted by localised name
      • addFavoritesSeparator : whether a divider should be added between favorites and defaults countries
      • showCountryDialCode : whether the dial code should be displayed as ListTile subtitle
      • noResultMessage : the message displayed instead of the list when the search has no results
    • add proxy properties for above properties in selector navigator classes
    • add API docs on updated files
    • fix countryFinder mismatch order on cleaning search after performing a search

    Remaining things to do :

    • [ ] write tests
    • [ ] write translations for noResultMessage
    • [ ] write documentation
    • [ ] update example to handle favorites countries
    opened by emri99 14
  • Expose autofillHints

    Expose autofillHints

    Currently, the library exposes a flag withHint and inject AutofillHints.telephoneNumberNational if true. On iOS, I doesn't seem to work. I need to specify AutofillHints.telephoneNumber instead.

    Can we simply expose the whole Iterable<String>? autofillHints instead of the bool flag?

    opened by xvrh 12
  • [BUG] decoration input border overridden by theme

    [BUG] decoration input border overridden by theme

    The app theme input border is overriding the widgets input border as shown in the picture where the inner text field has a border even though it is using InputDecoration.collapsed which removes the border.

    phone field

    The solution I used is to wrap the widget with a Theme widget and reimplement the input decoration in the decoration parameter.

    Is there another way to override the App default theme? I Would love to contribute and implement a proposed solution.

    opened by Faaatman 9
  • [Feature request] Add favorites countries option for country selector

    [Feature request] Add favorites countries option for country selector

    I would like to define some favorites countries so that my application users can find the mostly used countries in top of the list. Already started to implements that on my own.

    Does this sound like a valuable feature for you ?

    opened by emri99 9
  • Add format as you type feature

    Add format as you type feature

    Do you plan to add a format as you type feature ?

    I would be pleased to help achieving this functionality however I don't find helpful data in your other metadata package to get easy information for this.

    opened by emri99 9
  • New customization properties to the `CountrySelectorNavigator`

    New customization properties to the `CountrySelectorNavigator`

    Hello,

    I have added some new customization properties to the CountrySelectorNavigator which are the following:

    • For the CountryList, properties to customize the titleStyle & subtitleStyle for all the CountrySelectorNavigators, not just the BottomSheetNavigator, and a property to customize the scrollPhysics of the list.
    • For the SearchBox, properties to customize the InputDecoration, TextStyle, and Search Icon Color`.

    I hope you like them.

    Thanks ❤ Moaz El-sawaf

    opened by moazelsawaf 8
  • Change from v4.6.0 to v5.0.0 causes flag icon alignment swap

    Change from v4.6.0 to v5.0.0 causes flag icon alignment swap

    First of all, thank you for this amazing Flutter/Dart package!

    There is an odd issue where for some reason, the flag icon and country code number is placed on the right side of the field, but the invisible dropdown button is still on the left side.

    v4.6.0 and below: Screenshot_1651179508

    v5.0.0 and greater: Screenshot_1651179568

    Note: the dropdown button looks grey only because I tabbed onto it - normally it is transparent.

    repro-required 
    opened by JDVila 8
  • StateError when reusing undisposed PhoneController

    StateError when reusing undisposed PhoneController

    Using the PhoneFormField in a bottomsheet with a PhoneController. When reopening the bottomsheet (using the same PhoneController), we get this error:

    // _StreamControllerLifeCycle interface
    
      StreamSubscription<T> _subscribe(void onData(T data)?, Function? onError,
          void onDone()?, bool cancelOnError) {
        if (!_isInitialState) {
          throw StateError("Stream has already been listened to.");
        }
    

    Specifically, the line throw StateError("Stream has already been listened to."); gets triggered. It looks like once a value is pulled once, the stream no longer emits values, even if the controlled has yet to be disposed. Is this issue known? What is the current workaround? Thank you for your help!

    opened by JDVila 8
  • TextField params pass through

    TextField params pass through

    Is there any specific reason to pass through so few arguments to the textfield? https://github.com/cedvdb/phone_form_field/blob/dev/lib/src/widgets/phone_field.dart#L150

    The TextField has much more arguments that user would like to pass

    4.3.0 
    opened by vasilich6107 8
  • How to clear the value from PhoneFormField?

    How to clear the value from PhoneFormField?

    I made a feature using suffix-icon that can clear the text from the field if the IconButton was clicked. But it seems PhoneFormField doesn't have a clear() method like TextFormField does. How can I clear the value from the input field?

    opened by AlphaByte-RedTeam 0
  • FlagSize does not work on ListTile leading

    FlagSize does not work on ListTile leading

    Hi there, I hope you are doing well.

    There is a bug with the flagSize of the country selector for draggableBottomSheet. when I try to set flagSize for the icon on doesn't work properly. It is getting the flag in a wrong shape.

    To reproduce it, just try to set a size for the flag into on country selector navigator and you will be able to see that the size does not change.

    image

    opened by danielesilvestre 1
  • Country iso2 resets itself when phone number is empty

    Country iso2 resets itself when phone number is empty

    Hey, There is a bug that occurs when the phone number itself is empty.

    The iso 2 always resets itself to the default country. So choosing the country doesn't affect the form field - it stays with the same default country.

    Only after typing some digits, and trying to change the country, then it works. But after removing all digits, it resets to default country.

    I think the best behaviour is to keep the chosen country no matter what happens. Only at the initialization of the form field, the default country should be used (after checking there is no initial form value).

    Thanks

    opened by naamapps 2
  • reset throw an error

    reset throw an error

    Hello I am using your package in a particular context. Because we use bloc pattern, we develop this packages that facilitate bloc integration with form . I want to integrate your package to build phone number field and it works fine except the reset functionnality. It throws an TypeErrorImpl, it is like null value is no longer accepted in the controller. But it seems to work fine in your example. So it is more an call for help than an issue. Capture d’écran du 2022-08-12 12-36-26 Capture d’écran du 2022-08-12 12-35-09 Capture d’écran du 2022-08-12 12-34-43 In the picture you can see the error throwed, and some other picture that works fine

    Here is the implementation

    ` import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_floc/flutter_floc.dart'; import 'package:phone_form_field/phone_form_field.dart';

    class PhoneFormFieldBlocBuilder extends StatefulWidget { /// Fieldname to map with a field of the parent FormBloc in the widget tree final String fieldName; final String? hint; final IsoCode? initialCountryCode; final InputDecoration decoration;

    PhoneFormFieldBlocBuilder({ Key? key, required this.fieldName, this.decoration = const InputDecoration(), this.hint, this.initialCountryCode, }) : super(key: key);

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

    class _PhoneFormFieldBlocBuilderState extends State { late PhoneController _controller;

    @override void initState() { super.initState(); _controller = PhoneController(null); _controller.addListener(() => setState(() {})); }

    void dispose() { super.dispose(); _controller.dispose(); }

    @override Widget build(BuildContext context) { return BlocConsumer<T, FormBlocState>( buildWhen: (previous, current) => previous.fields[widget.fieldName] != current.fields[widget.fieldName], builder: (context, state) { return PhoneFormField( controller: _controller, decoration: _buildDecoration(context), validator: PhoneValidator.none, countrySelectorNavigator: CountrySelectorNavigator.modalBottomSheet(), defaultCountry: widget.initialCountryCode != null ? widget.initialCountryCode! : IsoCode.FR, onChanged: (phone) { print(phone!.international); context.read().updateField(widget.fieldName, OurPhoneNumber(isoCode: phone!.isoCode, nsn: phone.nsn)); }, ); }, listener: (context, state) { if (context.read().state.status == FormStatus.pure) { print("pure");

          if (_controller.value == null) {
            print("null");
          } else {
            // _controller.value = PhoneNumber(
            //     isoCode: widget.initialCountryCode != null
            //         ? widget.initialCountryCode!
            //         : IsoCode.FR,
            //     nsn: '');
    
            _controller.reset();
          }
        }
      },
    );
    

    }

    InputDecoration _buildDecoration(BuildContext context) { return widget.decoration.copyWith( errorText: context.read().fieldError(widget.fieldName), ); } }

    `

    Hope we can found a solution =

    opened by Nekketsu-GIT 3
  • Always invalid when the text is set using the controller (PhoneController.value)

    Always invalid when the text is set using the controller (PhoneController.value)

    I can set the input through the controller e.g. phoneNumberController.value = PhoneNumber.fromRaw(123); But after this when I call the parent Form's validate() method then PhoneFormField() validator becomes active, if I edit the number a little e.g. erase the last digit and then type it again then the validate() method of the parent Form widget works as intended

    opened by NeatFastro 1
Owner
cedvdb
cedvdb
A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

A Flutter package provides some implementations of TextInputFormatter that format input with pre-defined patterns

HungHD 192 Dec 31, 2022
Flutter textfield validation lets you validate different textform fields in your Flutter app

Flutter textfield validation lets you validate different textform fields in your Flutter app

World-Package 2 Sep 15, 2022
A markdown renderer for Flutter.

Flutter Markdown A markdown renderer for Flutter. It supports the original format, but no inline HTML. Overview The flutter_markdown package renders M

Flutter 828 Aug 12, 2021
A masked text for Flutter.

flutter_masked_text Masked text input for flutter. Alert Hi guys! Unfortunately, I'm not developing mobile anymore. This repo will not receive updates

Ben-hur Santos Ott 264 Dec 21, 2022
Soft and gentle rich text editing for Flutter applications.

About Zefyr Soft and gentle rich text editing for Flutter applications. You are viewing early dev preview version of this package which is no longer a

Memspace 2.2k Jan 8, 2023
Flutter widget that automatically resizes text to fit perfectly within its bounds.

Flutter widget that automatically resizes text to fit perfectly within its bounds. Show some ❤️ and star the repo to support the project Resources: Do

Simon Leier 1.8k Jan 3, 2023
A Flutter package to parse text and make them into linkified text widget

?? Flutter Parsed text A Flutter package to parse text and extract parts using predefined types like url, phone and email and also supports Regex. Usa

Fayeed Pawaskar 213 Dec 27, 2022
A Flutter Package to render Mathematics, Physics and Chemistry Equations based on LaTeX

flutter_tex Contents About Demo Video Screenshots How to use? Android iOS Web Examples Quick Example TeXView Document TeXView Markdown TeXView Quiz Te

Shahzad Akram 219 Jan 5, 2023
flutter 中文排版,支持分页上下对齐 两端对齐 翻页动画

text_composition flutter 中文排版 分页 上下对齐 两端对齐 多栏布局 弃用richText,使用Canvas,精确定位绘图位置,消除字体对排版影响 视频与截图 demo https://github.com/mabDc/text_composition/releases/t

西红柿大芝麻 50 Nov 3, 2022
Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase

Flutter Tutorial - PDF Viewer - Asset, File, Network & Firebase Use the Flutter PDF Viewer to download PDF documents and display them within your Flut

Johannes Milke 36 Dec 9, 2022
Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Flutter Tutorial - AutoComplete TextField & AutoComplete Search Create an AutoComplete TextField to search JSON data based on suggestions in Flutter.

Johannes Milke 32 Oct 23, 2022
A simple Flutter package that makes turning a FAB into a text field easy.

flutter_text_field_fab A simple Flutter widget that makes turning a FAB into a text field easy.

Haefele Software 4 Jan 18, 2022
A low code editor with the full power of flutter.

flutter_blossom ?? Low code editor with the full power of flutter. Think in flutter, watch your ideas come to life, plan ahead and let your creativity

Flutter Blossom 0 Dec 2, 2021
Soft and gentle rich text editing for Flutter applications

Soft and gentle rich text editing for Flutter applications. Zefyrka is a fork of Zefyr package with the following improvements: support Flutter 2.0 op

null 85 Dec 21, 2022
Rich Text renderer that parses Contentful Rich Text JSON object and returns a renderable Flutter widget

Contentful Rich Text Renderer for Flutter Rich Text renderer that parses Contentful Rich Text field JSON output and produces a Flutter Widget tree tha

Kumanu 45 Nov 10, 2022
Flutter App for beginner

i_am_rich A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Trần Văn Nguyên 1 Nov 17, 2021
A powerful extended official text for Flutter, which supports Speical Text(Image,@somebody), Custom Background, Custom overFlow, Text Selection.

Extended official text to build special text like inline image or @somebody quickly,it also support custom background,custom over flow and custom selection toolbar and handles.

FlutterCandies 509 Jan 4, 2023
Rich coin project of flutter

rich_coin flutter实现RichCoin项目。 Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

null 0 Nov 27, 2021
Arc Text Widget for Flutter

Flutter Arc Text Renders text along the arc. See demo. The story behind the plugin is here. Basic usage class MyApp extends StatelessWidget

Kirill Bubochkin 15 Oct 18, 2021