考虑以下代码
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetBuilder<HomeController>(
init: HomeController(),
builder: (controller) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
phoneWidget(),
TextFormField(
controller: controller.formController,
),
ElevatedButton(onPressed: ()=> controller.clearForm(), child: const Text('Clear'))
],
),
),
);
});
}
Widget phoneWidget() {
final HomeController _controller = Get.find();
return Container(
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(20)
),
child: IntlPhoneField( // the widget in question
controller:_controller.secondController ,
showCountryFlag: false,
iconPosition: IconPosition.trailing,
autoValidate: false,
initialValue: _controller.initialPhoneNumber,
initialCountryCode: _controller.initialCountryCode,
),
);
}
}
在上面我有一个小部件。我在控制器上的init处设置初始值。
class HomeController extends GetxController{
final _intialCountryCode = ''.obs;
String get initialCountryCode => _intialCountryCode.value;
final _initialPhoneNumber = ''.obs;
String get initialPhoneNumber => _initialPhoneNumber.value;
final formController = TextEditingController();
final secondController = TextEditingController();
@override
void onInit() {
super.onInit();
_intialCountryCode('IN');
_initialPhoneNumber('123457788');
formController.text = "TEST";
secondController.text = '1234944627';
}
clearForm(){
formController.clear();
secondController.clear();
secondController.text = '123349526';
}
}
我的应用程序正在使用Getx。我在init上为这个小部件赋值。我所期望的是小部件在加载屏幕时显示初始值。无论如何,这些更改都不会反映在小部件上,相反,如果我热重新加载,这些更改会在小部件中更新。我已经尝试过用Obx包装小部件。但是结果是相同的。只有在热重新加载后才能进行更改。是什么原因造成的?为什么小部件只在热重新加载后更新?如何正确解决
class HomeController extends GetxController{
final _intialCountryCode = ''.obs;
String get initialCountryCode => _intialCountryCode.value;
final _initialPhoneNumber = ''.obs;
String get initialPhoneNumber => _initialPhoneNumber.value;
final formController = TextEditingController().obs;
final secondController = TextEditingController().obs;
@override
void onInit() {
super.onInit();
_intialCountryCode('IN');
_initialPhoneNumber('123457788');
formController.text = "TEST";
secondController.text = '1234944627';
}
clearForm(){
formController.clear();
secondController.clear();
secondController.text = '1234944627';
}
}
GetX<HomeController>(
init: HomeController(),
builder: (controller) {
尝试添加这些更改,看看它是否适用于