每次添加新的 TextBlock 时如何生成新的 TextEditingController
How can I generate a new TextEditingController every time when I add a new TextBlock
所以,我有这个页面,我可以在其中添加多个表示文本块的 TextFormFiled。问题是,它是动态生成的,因此您永远不知道需要多少个文本编辑控制器。
void addTextBlock() {
state.blocks.add(
TextBlock(hint: 'Description', controler: state.descriptionController));
}
这是点击添加文本块时触发的代码,如您所见,它使用相同的控制器。
TextBlock 小工具:
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),
);
}
}
试试下面的代码:
List<TextEditingController> textEditingControllers = [];
void addTextBlock() {
TextEditingController textEditingController = TextEditingController();
textEditingControllers.add(textEditingController)
state.blocks.add(
TextBlock(hint: 'Description', controler: textEditingControllers[textEditingControllers.length-1]));
}
所以,我有这个页面,我可以在其中添加多个表示文本块的 TextFormFiled。问题是,它是动态生成的,因此您永远不知道需要多少个文本编辑控制器。
void addTextBlock() {
state.blocks.add(
TextBlock(hint: 'Description', controler: state.descriptionController));
}
这是点击添加文本块时触发的代码,如您所见,它使用相同的控制器。
TextBlock 小工具:
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),
);
}
}
试试下面的代码:
List<TextEditingController> textEditingControllers = [];
void addTextBlock() {
TextEditingController textEditingController = TextEditingController();
textEditingControllers.add(textEditingController)
state.blocks.add(
TextBlock(hint: 'Description', controler: textEditingControllers[textEditingControllers.length-1]));
}