vanshg395 / intl_phone_field

A customised Flutter TextFormField to input international phone number along with country code.
https://pub.dev/packages/intl_phone_field
MIT License
177 stars 507 forks source link

initialCountryCode not changing with future data ! #267

Closed Mohamed-Reda1010 closed 1 year ago

Mohamed-Reda1010 commented 1 year ago

when i get the user data from the db and use the setstate , initialCountryCode not changing !!

Directionality buildPhoneFormField() { return Directionality( textDirection: TextDirection.ltr, child: IntlPhoneField( keyboardType: TextInputType.phone, pickerDialogStyle: PickerDialogStyle( searchFieldInputDecoration: const InputDecoration.collapsed( hintText: sSearchFieldhintText)), invalidNumberMessage: sinvalidNumberMessage, initialCountryCode: phoneCountryCode, //?? "EG", THIS IS THE PROBLEM ^ _ ^ controller: phoneController, onSaved: (newValue) { phone = newValue?.completeNumber.toString(); phoneCountryCode = newValue?.countryCode; phoneWithoutCountryCode = newValue?.number; },

      onChanged: (value) {
        if (value.number.isNotEmpty) {
          removeError(error: kPhoneNumberNullError);
        } else if (value.number.length >= minPhoneLength) {
          removeError(error: kPhoneNumberShortError);
        }

        phone = value.completeNumber.toString();
        phoneCountryCode = value.countryCode;
        phoneWithoutCountryCode = value.number;
      },
      validator: (value) {
        if (value!.number.isEmpty) {
          addError(error: kPhoneNumberNullError);
          return "";
        } else if (value.number.length < minPhoneLength) {
          addError(error: kPhoneNumberShortError);
          return "";
        }
        return null;
      },
      decoration: const InputDecoration(
        hintText: sPhoneHint,
        floatingLabelBehavior: FloatingLabelBehavior.always,
      ),
    ));

}

// This is my full Code

class EditProfileForm extends StatefulWidget { const EditProfileForm({super.key});

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

Database db = Database(); String userID = ''; var loading = Loading();

class _EditProfileFormState extends State { String? name, email, phone, phoneCountryCode, oldEmail, oldPhone, phoneWithoutCountryCode; final emailController = TextEditingController(); final nameController = TextEditingController(); final phoneController = TextEditingController();

var loading = Loading();

@override void initState() { super.initState();

init();

}

Future init() async { loading.startLoading(msg: loadingMessageDefault);

final sID = await UserSecureStorage.getId() ?? '';

final Map<String, dynamic>? userData =
    await db.getUserDataByIdAsMap(userID: sID);

setState(() {
  userID = sID;
  name = userData![fName];
  email = userData[fEmail];
  oldEmail = userData[fEmail];
  phone = userData[fPhone];
  oldPhone = userData[fPhone];
  phoneCountryCode = userData[fPhoneCountryCode];
  phoneWithoutCountryCode = userData[fPhoneWithoutCountryCode];
  nameController.text = name!;
  phoneController.text = phoneWithoutCountryCode!;
  emailController.text = email!;
});
loading.endLoading();

}

final _formKey = GlobalKey();

final List<String?> errors = [];

void addError({String? error}) { if (!errors.contains(error)) { setState(() { errors.add(error); }); } }

void removeError({String? error}) { if (errors.contains(error)) { setState(() { errors.remove(error); }); } }

@override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( children: [ buildNameFormField(), SizedBox(height: getProportionateScreenHeight(30)), buildPhoneFormField(), SizedBox(height: getProportionateScreenHeight(30)), buildEmailFormField(), SizedBox(height: getProportionateScreenHeight(30)), FormError(errors: errors), SizedBox(height: getProportionateScreenHeight(20)), ElevatedButton( style: btnStyle, child: Text( 'حفظ البيانات', style: btntxtStyle, ), onPressed: () async { loading.startLoading(msg: loadingMessageDefault); Database db = Database(); bool saved = false; removeError(error: 'all'); // clear the errors setState(() {}); bool result = await InternetConnectionChecker().hasConnection; if (result == true) { bool emailExists = await db.emailExistsWhenEdit( uNewEmail: email!, uOldEmail: oldEmail!); bool phoneExists = await db.phoneExistsWhenEdit( uOldPhone: oldPhone!, uNewPhone: phone!);

            if (emailExists) {
              errors.add(sEmailAlreadyRegisteredError);
            } else if (phoneExists) {
              errors.add(sPhoneAlreadyRegisteredError);
            } else {
              db.updateUserDataWithoutPassword(
                  id: userID,
                  name: name,
                  email: email,
                  phoneCode: phoneCountryCode,
                  phone: phone,
                  phoneWithoutCountryCode: phoneWithoutCountryCode);
              saved = true;
            }
          } else {
            connectionErrorMessage();
          }

          // ignore: use_build_context_synchronously
          KeyboardUtil.hideKeyboard(context);
          // Navigator.pushNamed(context, CompleteProfileScreen.routeName);

          if (saved == true) {
            if (oldEmail != email) {
              UserSecureStorage.setEmail(email!);
            }

            // ignore: use_build_context_synchronously
            Navigator.pushReplacementNamed(
                context, ProfileDataScreen.routeName);
            //Navigator.pushNamed(context, MainScreen.routeName);
          }

          setState(() {
            errors;
          });
          loading.endLoading();
        },
      ),
    ],
  ),
);

}

TextFormField buildNameFormField() { return TextFormField( keyboardType: TextInputType.text, maxLength: maxNameLength, controller: nameController, onSaved: (newValue) => name = newValue, onChanged: (value) { if (value.isNotEmpty) { removeError(error: kNamelNullError); } else if (value.length >= minNameLength) { removeError(error: kNamelShortError); } else if (nameValidator(text: value) == true) { removeError(error: kNamelRegExError); } name = value; }, validator: (value) { if (value!.isEmpty) { addError(error: kNamelNullError); return ""; } else if (value.length < minNameLength) { addError(error: kNamelShortError); return ""; } else if (nameValidator(text: value) == false) { addError(error: kNamelRegExError); } return null; }, decoration: const InputDecoration( labelText: regUsername, floatingLabelBehavior: FloatingLabelBehavior.always, suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"), ), ); }

Directionality buildPhoneFormField() { setState(() {}); return Directionality( textDirection: TextDirection.ltr, child: IntlPhoneField( keyboardType: TextInputType.phone, pickerDialogStyle: PickerDialogStyle( searchFieldInputDecoration: const InputDecoration.collapsed( hintText: sSearchFieldhintText)), invalidNumberMessage: sinvalidNumberMessage, initialCountryCode: phoneCountryCode, //?? "EG", controller: phoneController, onSaved: (newValue) { phone = newValue?.completeNumber.toString(); phoneCountryCode = newValue?.countryCode; phoneWithoutCountryCode = newValue?.number; },

      onChanged: (value) {
        if (value.number.isNotEmpty) {
          removeError(error: kPhoneNumberNullError);
        } else if (value.number.length >= minPhoneLength) {
          removeError(error: kPhoneNumberShortError);
        }

        phone = value.completeNumber.toString();
        phoneCountryCode = value.countryCode;
        phoneWithoutCountryCode = value.number;
      },
      validator: (value) {
        if (value!.number.isEmpty) {
          addError(error: kPhoneNumberNullError);
          return "";
        } else if (value.number.length < minPhoneLength) {
          addError(error: kPhoneNumberShortError);
          return "";
        }
        return null;
      },
      decoration: const InputDecoration(
        hintText: sPhoneHint,
        floatingLabelBehavior: FloatingLabelBehavior.always,

      ),
    ));

}

TextFormField buildEmailFormField() { return TextFormField( keyboardType: TextInputType.emailAddress, maxLength: maxEmailLength, controller: emailController, onSaved: (newValue) => email = newValue, onChanged: (value) { if (value.isNotEmpty) { removeError(error: kEmailNullError); } else if (emailValidatorRegExp.hasMatch(value)) { removeError(error: kInvalidEmailError); } email = value; }, validator: (value) { if (value!.isEmpty) { addError(error: kEmailNullError); return ""; } else if (!emailValidatorRegExp.hasMatch(value)) { addError(error: kInvalidEmailError); return ""; } return null; }, decoration: const InputDecoration( labelText: regEmail, hintText: regEmailHint, floatingLabelBehavior: FloatingLabelBehavior.always, suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Mail.svg"), ), ); }

}

Mohamed-Reda1010 commented 1 year ago

dead plugin thank you , i removed it

debovitch commented 10 months ago

You can add a key: UniqueKey() to your IntlPhoneField widget, it will force to pass in the initState again.