How can I generate a new TextEditingController every time when I add a new TextBlock

Issue

So, am having this page, where I can add multiple TextFormFiled that represent a text block. The thing is, it’s generated dynamic so you never know how many Text Editing controllers you need.

Here is a visual representaion Of UI


    void addTextBlock() {
        state.blocks.add(
            TextBlock(hint: 'Description', controler: state.descriptionController));
  }


Here is the code that trigger when tapping Add Text Block, and as you can see it uses the same controller.

The TextBlock wiget :



    class TextBlock extends Block {
      TextBlock({required this.controler, required this.hint})
          : super(BlockType.TextBlock);
      final String hint;
      final TextEditingController controler;
      @override
      Widget toWidget() {
        return TextFormField(
          controller: controler,
          decoration: InputDecoration(
            filled: true,
            fillColor: AppColors.textFieldBackground,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(10.0),
              borderSide: BorderSide(color: AppColors.textFieldHintColor),
            ),
            contentPadding:
                const EdgeInsets.symmetric(vertical: 22.0, horizontal: 24.0),
            hintText: hint,
            hintStyle:
                AppTextStyles.normalRoboto(color: AppColors.textFieldHintColor),
          ),
          maxLines: null,
          keyboardType: TextInputType.multiline,
          style: AppTextStyles.normalRoboto(color: AppColors.textFieldHintColor),
        );
      }
    }



Solution

Try out below code:

List<TextEditingController> textEditingControllers = [];


void addTextBlock() {
        TextEditingController textEditingController = TextEditingController();
        textEditingControllers.add(textEditingController)
        state.blocks.add(
            TextBlock(hint: 'Description', controler: textEditingControllers[textEditingControllers.length-1]));
        
  }

Answered By – Jahidul Islam

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *