简体   繁体   中英

Flutter - Pre populating TextFormField with value using GetX

This is the controller and it contains the method to populate the textformfield

class FieldOwnerController extends GetxController {
 static FieldOwnerController instance = Get.find();
 var fieldAddress = "".obs;

 ...

//method to populate text field
assignAddress() {
  dynamic argumentData = Get.arguments;
  fieldAddress.value = argumentData["address"];
}

UI

      @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance!
        .addPostFrameCallback((_) => fieldOwnerController.assignAddress());
  ...

              Obx(
            () => MultiLineTextField(
              textEditingController: fieldOwnerController.addressCtrlr,
              hintText: "",
              icon: null,
              initialValue: fieldOwnerController.fieldAddress.value,
            ),
          ),

    class MultiLineTextField extends StatelessWidget {
  const MultiLineTextField({
    Key? key,
    required this.textEditingController,
    this.hintText,
    this.icon,
    this.initialValue,
  }) : super(key: key);

  final TextEditingController textEditingController;
  final String? hintText;
  final Icon? icon;
  final String? initialValue;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: SizeConfig.screenWidth / 1.2,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(kBorderRadiusMin),
            color: kTextFieldFillColor,
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            child: TextFormField(
          /// the new value is assigned correctly here 
              initialValue: initialValue,
              minLines: 2,
              maxLines: 5,
              //controller: textEditingController,
              decoration: InputDecoration(
                icon: icon,
                border: InputBorder.none,
                hintText: hintText,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

I get the value alright, but it doesn't show up in the textfield. I mean first, the UI is rendered(textfield is empty). Then the fieldAddress value changes, the UI gets rebuilt, but the textfield doesn't show the value.

What is wrong with this approach?

我认为您将需要使用分配给您的字段的TextEditingController并使用 GetxController 中的变量值设置text属性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM