I want to show image as part of TextFormField
in flutter. Like how it is shown in ChatGPT. I should be able to delete that image by pressing backspace. I don’t want to add the image to the prefix or suffix as suggested in many cases. I want it to be a part of the chat.
I came across rich text editors like flutter quill but I am not sure how good it will be. Is there any other way to achieve the same?
UPDATE:
I am looking for something like the below image . But instead of close icon using backspace to clear the image would be better.
2
Answers
You can display an image in the TextField like this.
buildTextSpan
.text
value inTextEditingController
matches theTextSpan
children. Since you want to add images, a solution is to add a placeholder character in thetext
string where the image is. Eg your text might be "check out this photo:" and display an image, so we add a character such as "ʉ" : "check out this photo:ʉ".Now whenever the method
insertImage
is called, the character ‘ʉ’ will be inserted at the cursor position. But it will be displayed as an image instead. Now use this controller in yourTextField
controller.Delete using the backspace will now work as well.
You can break down the design into basic Flutter widgets. Here’s a breakdown:
Also, to remove the images one by one on backspace events, we can use the
Focus
widget to capture key events, specifically listening for the backspace key.Here is my implementation of this custom widget:
Then our
CustomTextFormField
can be used like this: