Home > Mobile >  How can I code a editable textfield in a CustomPainter in Flutter
How can I code a editable textfield in a CustomPainter in Flutter

Time:01-16

I have a CustomPainter extending class. Until now, I paint only rectangles with some static text in it. Now I want to improve this a little bit and want that the user of my Flutter-App can edit this text.

I added a TextEditingController to my Object-Class and tried this:

    TextField textField = TextField(
      controller: object.textController,
    );
    textField.createRenderObject(context).paint;
    textFieldPainter.paint(canvas, Offset.zero);
  }

Unfortunaly, there is nothing like a textField.createRenderObject-Function in Flutter. So I look for a idea how I can get my a "controlled Text" working.

I also played around with TextSpan(). But I can't set the Controller to this.

CodePudding user response:

The following steps are not the best solution , but you can try this solution.

Steps:

  • create an OverlayEntry, put a (hidden) TextField into it with a FocusNode and TextEditController.
  • after added the overlay entry, request focus on the focusNode, so the keyboard will open.
  • Add an onChanged to the TextField, and notify the painter somehow (e.g. valueNotifier) on text change.
  • In the TextPainer use the TextEditController.text value

CodePudding user response:

For me, the following solution fit: I built a function that checks if a click was done within the dimensions of the rectangle. If yes, a "properties dialog" opens (currently only the text) and here the text can now also be changed.

I know, this is only a workaround and not a real solution to my question, but maybe the approach helps one or the other.

  • Related