I’m using a widget for collecting user phone contact. The behavior I am expecting is that if there are values for phone numbers, it should be displayed in that widget. On init I’m retrieving the data that needs to be shown in that widget.
void onInit() async {
super.onInit();
getCountryFromCode(user?.countryCode ?? ' 91');
_initialPhoneNumber(
user?.mobileNumber == "null" ? '' : user?.mobileNumber ?? '');
}
I’m using Obx to show these changes inside this widget. However, the value is received and the widget is not updating it. But when I change the page and come back the value is updating. The state only changes when I return to this page.
Here's how I tried to update the widget (I’m using intl_phone_field for phone field)
Widget mobileField(BuildContext context) {
final ProfileController _controller = Get.find();
return Obx(
() => Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
child: IntlPhoneField(
enabled: true,
decoration: const InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(),
),
hintText: 'Mobile number',
counterText: "",
),
initialValue: _controller.initialPhoneNumber,
initialCountryCode: _controller.userCountryCode,
autoValidate: false,
showCountryFlag: false,
iconPosition: IconPosition.trailing,
onChanged: (phone) {
_controller.onSelectedPhoneNumber(phone);
},
onCountryChanged: (phone) {
_controller.onSelectedPhoneNumber(phone);
},
),
),
);
}
What is the proper way to display these changes? How can I solve this?
CodePudding user response:
You need to declare. Obs variable and use it in the UI screen. Just try the below code
void onInit() async {
super.onInit();
void onInit() async {
super.onInit();
getCountryFromCode(user?.countryCode ?? ' 91');
var mobilenNo = "".obs;
mobileNo.value = (user?.mobileNumber == "null" ? '' : user?.mobileNumber ?? '');
}
In the UI screen, just use it like:
Controller.mobileNo;
Make sure the widget wraps with the Obs() widget.
Check this link.
CodePudding user response:
you can use update() function after changes in controller
example;
void onInit() async {
super.onInit();
getCountryFromCode(user?.countryCode ?? ' 91');
_initialPhoneNumber(
user?.mobileNumber == "null" ? '' : user?.mobileNumber ?? '');
update(); //actually you should use in _initalPhoneNumber function
}