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

Time:12-21

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),
        );
      }
    }



CodePudding user response:

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]));
        
  }
  • Related