0

What i am trying is to replicate "setText" in flutter without TextEditingController. Since I'm using FutureBuilder, i cannot go with manually updating state, thereby removing the choice of TextEditingController.

Bellow is the code for better understanding.

class DynamicFormBuilder {
  GlobalKey<FormBuilderState> dynamicFormKey = GlobalKey<FormBuilderState>();

  String getVariableData(String variable) {
    return dynamicFormKey.currentState.fields[variable].currentState.value;
  }

  void setVariableData(String variable, String value) {
    dynamicFormKey.currentState.fields[variable].currentState.didChange(value);
  }

  Widget workOnWidget(DynamicFormResponse widget) {
    switch (widget.widget) {
      case "text":
        return Text(
          widget.displayText,
          style: TextStyle(
              fontWeight: widget.style.fontWeight == "bold"
                  ? FontWeight.bold
                  : FontWeight.normal,
              fontSize: double.parse(widget.style.fontSize)),
        );
      case "editable":
        return FormBuilderTextField(
          attribute: widget.variable,
          decoration: InputDecoration(labelText: widget.displayText),
          onChanged: (val) {
            if (widget.onChanged != null) {
              onChangedFunctionMapper[widget.variable](val);
            }
          },
        );
      case "datepicker":
        return FormBuilderDateTimePicker(
          attribute: widget.variable,
          inputType: InputType.date,
          format: DateFormat("dd/MM/yyyy"),
          decoration: InputDecoration(labelText: widget.displayText),
          validators: [
            FormBuilderValidators.required(),
          ],
        );
      case "divider":
        return Container(
          margin: EdgeInsets.fromLTRB(5, 10, 5, 10),
          width: double.infinity,
          height: 10,
          color: accentColor,
        );
      case "dropdown":
        return FormBuilderDropdown(
          attribute: widget.variable,
          items: convertDropdown(widget.options),
          hint: Text(widget.hint),
          decoration: InputDecoration(labelText: widget.displayText),
        );
      case "radioButton":
        return FormBuilderRadioButton(
          displayText: widget.displayText,
          attribute: widget.variable,
          isHorizontal: widget.isHorizontal,
          onChanged: (val) {
            if (val == "yes") {
              visibilityMap["age"] = true;
            } else {
              visibilityMap["age"] = false;
            }
          },
          options: widget.options
              .map((lang) => FormBuilderFieldOption(value: lang))
              .toList(growable: false),
        );
      default:
        return Text("lol");
    }
  }

  Widget buildForms(BuildContext context, Future<dynamic> fetchJSON) {
    jsonData = new List();
    dynamicFormKey = GlobalKey<FormBuilderState>();
    accentColor = Theme.of(context).accentColor;
    return FutureBuilder(
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.none &&
            snapshot.hasData == null) {
          return Container(
            child: Text("No Data got loaded"),
          );
        } else if (snapshot.connectionState == ConnectionState.done) {
          for (int i = 0; i < snapshot.data.length; i++) {
            jsonData.add(DynamicFormResponse.fromJson(snapshot.data[i]));
          }
          return ListView(
            padding: EdgeInsets.all(10),
            children: <Widget>[
              FormBuilder(
                key: dynamicFormKey,
                autovalidate: false,
                child: Card(
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: jsonData.map<Widget>((widget) {
                        print(widget.widget);
                        return workOnWidget(widget);
                      }).toList(),
                    ),
                  ),
                ),
              ),
            ],
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
      future: fetchJSON,
    );
  }
}

So here when i do updates using setVariableData(variable, data), the variable in state is getting updated, but the same is not getting reflected in TextFields.

2
  • 1
    _key.currentState.fields['name'].currentState.didChange(value) This will work in sliders, dropdowns and radio buttons, but it is not working in textfields. Oct 4, 2019 at 15:18
  • @Eugene have updated the post. Oct 4, 2019 at 16:43

1 Answer 1

2

First of all, your question is quite confusing. However, I guess, you are looking for something to set the value to some xyz variable when you submit the data, right?

You can do this by two ways, these are:

  1. Using onSubmitted Property: This gives the value when the user is done editing the value in the textfield
  2. Using TextEditingController: Controls the text being edited.

Code using TextEditingController:

TextEditingController _controller = new TextEditingController();

TextField(
  controller: _controller 
)

//suppose you have a button which will print the data of the textfield for on onPressed
RaisedButton(
 onPressed: () {
    //this will print the value you've entered into the textfield
    print(this._controller.text)
    //change the value using setState here
    setState((){
        value_to_be_changed_variable = this._controller.text
    })
 },
 child: const Text('Submit', style: TextStyle(fontSize: 20))
)

Code using onSubmitted Property:

TextField(
  onSubmitted: (value) {
     //do the operation here with the help of setState()
     setState((){
        variable_value_to_be_changed = value
     })
  }
)

I hope that'd suffice your needs. For more info read about Textfield Flutter Class thoroughly. It will help in you in many ways

1
  • 1
    sorry for not properly framing the questions, have updated. kindly check. Oct 4, 2019 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.