Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not having a complete phone number with country code #37

Open
1 task done
Mark1944 opened this issue May 25, 2023 · 8 comments
Open
1 task done

Not having a complete phone number with country code #37

Mark1944 opened this issue May 25, 2023 · 8 comments
Labels
bug Something isn't working

Comments

@Mark1944
Copy link

Is there an existing issue for this?

  • I have searched the existing issues

Package/Plugin version

2.0.1

Flutter doctor

Flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.10.1, on macOS 13.3 22E252 darwin-arm64, locale en-KE)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.3)
[✓] VS Code (version 1.78.2)
[✓] Connected device (3 available)
[✓] Network resources

• No issues found!
mark@Marks-MacBook-Air f

Minimal code example

Code sample
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_phone_field/form_builder_phone_field.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      // Locale config required by form_builder_validators
      // https://github.com/danvick/flutter_form_builder/blob/master/packages/form_builder_validators/example/lib/main.dart
      supportedLocales: const [...FormBuilderLocalizations.supportedLocales],
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        FormBuilderLocalizations.delegate,
      ],
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final _formKey = GlobalKey<FormBuilderState>();

  MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("FormBuilderPhoneField")),
      body: FormBuilder(
        key: _formKey,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FormBuilderPhoneField(
                name: 'phone_number',
                decoration: const InputDecoration(
                  labelText: 'Phone Number',
                  hintText: 'Hint',
                ),
                // onChanged: _onChanged,
                priorityListByIsoCode: const ['KE'],
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.numeric(),
                  FormBuilderValidators.required(),
                ]),
              ),
              const SizedBox(height: 15),
              FormBuilderPhoneField(
                name: 'phone_number_cupertino',
                isCupertinoPicker: true,
                decoration: const InputDecoration(
                  labelText: 'Phone Number',
                  hintText: 'Hint',
                ),
                // onChanged: _onChanged,
                priorityListByIsoCode: const ['US'],
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.numeric(),
                  FormBuilderValidators.required(),
                ]),
              ),
              const SizedBox(height: 15),
              Wrap(
                spacing: 16,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      if (_formKey.currentState!.saveAndValidate()) {
                        debugPrint(_formKey.currentState!.value.toString());
                      }
                    },
                    child: const Text("Submit"),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      _formKey.currentState?.reset();
                      debugPrint(
                          _formKey.currentState!.instantValue.toString());
                    },
                    child: const Text("Reset"),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Current Behavior

flutter: {phone_number: 743234567, phone_number_cupertino: 743234567}
The phone numbers are not complete with the country codes either after selecting or the initial country selected

Expected Behavior

The phone numbers inputed should have a country code
flutter: {phone_number: +254743234567, phone_number_cupertino: +254743234567,}

Steps To Reproduce

Using the example here and run it

Aditional information

Screenshot 2023-05-25 at 11 12 33
@Mark1944 Mark1944 added the bug Something isn't working label May 25, 2023
@Mark1944 Mark1944 changed the title [Field name or General]: <title> Not having a compolete phone number with country code May 25, 2023
@Shiba-Kar
Copy link

Facing the same issue.

@Aladinndevolpment
Copy link

Any solution for this

@PhilipHayes
Copy link

I'm having this issue. I cannot access .fullNumber either to get around it.

@MarkKuzmycz
Copy link

If the user enters the number first and then selects the country then the country code is included. But, if they select the country first then enter the number the country code is not returned .

@deandreamatias deandreamatias changed the title Not having a compolete phone number with country code Not having a complete phone number with country code Aug 8, 2023
@commtel-dev
Copy link

commtel-dev commented Aug 10, 2023

I have the same issue since updating to the latest version and updating to Dart 3. Here's my code:

FormBuilderPhoneField( backgroundColor: Colors.white, name: 'phone_number', enabled: phoneNumberEnabled, controller: phoneController, decoration: const InputDecoration( filled: true, fillColor: Colors.white, border: OutlineInputBorder(), hintText: 'Enter your number', isDense: true, ), defaultSelectedCountryIsoCode: 'GB', priorityListByIsoCode: const ['GB', 'IE', 'AU', 'NZ', 'US'], validator: FormBuilderValidators.compose( [ FormBuilderValidators.required(), FormBuilderValidators.numeric(), ], ), onSaved: (val) { phoneNumber = val!; }, ),

This previously worked fine but now the country code is not being added to the value. For example, using phone number +447700900123, If you write the number (7700900123), then reselect the country (+44) it works. If you select the country (+44), then add the number (7700900123) it doesn't get included and login fails.

Previously you could just write the number and leave the country as the preselected one with no issues.

Versions being used:
flutter_form_builder: ^9.1.0
form_builder_phone_field: ^2.0.1
form_builder_validators: ^9.0.0

@PollyGlot
Copy link

Any solution found ? Because I strugle with this bug also.

@dannycortesv
Copy link

Facing the same issue....

@SantiagoSchez
Copy link

SantiagoSchez commented Dec 21, 2023

As is right now, this package is broken.

In the end I have migrated to the intl_phone_field package. For those who want to integrate it with flutter_form_builder, I leave here the widget that adapts it. The validator for making the field required and the styles work perfectly. The only thing not supported is all the others validators from flutter_form_builder, but I don't see it problematic at all, since validation is handled by intl_phone_field internally. All yours:

import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:intl_phone_field/countries.dart';
import 'package:intl_phone_field/helpers.dart';
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:intl_phone_field/phone_number.dart';

class FormBuilderIntlPhoneField extends StatefulWidget {
  final String name;
  final InputDecoration? decoration;
  final String? initialCountryCode;
  final List<Country>? countries;
  final String? invalidNumberMessage;
  final bool isRequired;
  // Expose here more fields from IntlPhoneField as needed

  const FormBuilderIntlPhoneField({
    super.key,
    required this.name,
    this.decoration,
    this.initialCountryCode,
    this.countries,
    this.invalidNumberMessage,
    this.isRequired = false,
  });

  @override
  State<FormBuilderIntlPhoneField> createState() => _FormBuilderIntlPhoneFieldState();
}

class _FormBuilderIntlPhoneFieldState extends State<FormBuilderIntlPhoneField> {
  String? _error;
  final _fieldKey = GlobalKey<FormBuilderFieldState>();

  _isValidIsRequired(PhoneNumber? phoneNumber) {
    if (!widget.isRequired) {
      return true;
    }

    return !(phoneNumber == null || phoneNumber.number.isEmpty || !isNumeric(phoneNumber.number));
  }

  @override
  Widget build(BuildContext context) {
    return FormBuilderField<PhoneNumber>(
      key: _fieldKey,
      name: widget.name,
      validator: (phoneNumber) {
        if (!_isValidIsRequired(phoneNumber)) {
          return 'required'; // This message is not displayed at all in the UI
        }

        return null;
      },
      builder: (FormFieldState field) {
        return IntlPhoneField(
          decoration: InputDecoration(
            labelText: widget.decoration?.labelText ?? 'Phone number',
            suffixIcon: widget.decoration?.suffixIcon ?? const Icon(Icons.phone),
            border: widget.decoration?.border ?? const UnderlineInputBorder(),
            errorText: _error,
          ),
          initialCountryCode: widget.initialCountryCode ?? 'US',
          countries: widget.countries,
          onChanged: (phoneNumber) => field.didChange(phoneNumber),
          onSaved: (phoneNumber) {
            field.didChange(phoneNumber);

            if (!_isValidIsRequired(phoneNumber)) {
              setState(() => _error = FormBuilderLocalizations.of(context).requiredErrorText);
            } else {
              setState(() => _error = null);
            }
          },
          invalidNumberMessage: widget.invalidNumberMessage,
          validator: (phoneNumber) {
            if (!_isValidIsRequired(phoneNumber)) {
              setState(() => _error = FormBuilderLocalizations.of(context).requiredErrorText);
            } else {
              setState(() => _error = null);
            }

            return null;
          },
        );
      },
    );
  }
}

Then you can use it in your form like:

...
FormBuilderIntlPhoneField(
  name: 'mobileNumber',
  initialCountryCode: 'ES',
  invalidNumberMessage: 'Número inválido',
  isRequired: true,
  decoration: InputDecoration(
    labelText: 'Teléfono',
    suffixIcon: const Icon(Icons.phone),
    border: const OutlineInputBorder(),
  ),
),
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

9 participants