who-aditya-nawandar
who-aditya-nawandar

Reputation: 1344

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?

Upvotes: 1

Views: 773

Answers (1)

I think you will need to use a TextEditingController assigned to your field and set the text property with the value of your variable from the GetxController

Upvotes: 1

Related Questions