Home > Net >  I want to dynamically replace words with widgets using rich text
I want to dynamically replace words with widgets using rich text

Time:08-01

I am Japanese. I am not very good at English, so I apologize in advance. I am developing a fill-in-the-blanks quiz app. I would like to replace the part surrounded by "{}" in the text with the following widget,which is not yet completed.

    class Blank extends StatelessWidget {
  final String answer;
  String answerHint = "";
  String value = "";
  Blank(this.answer);
  String hint="";
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: TextField(
        onChanged: (text) {
          value = text;
        },
        decoration: InputDecoration(
          hintText: hint
        ),
      ),
    );
  }
}

I understand that we can use something called RichText's WidgetSpan, but that is not dynamic, so I would like to know how to do this dynamically.I look forward to hearing from you.

CodePudding user response:

you can try something like this:

class TextWithBlanks extends StatelessWidget {
  final String text;
  static final regex = RegExp("(?={)|(?<=})");

  const TextWithBlanks({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final split = text.split(regex);
    return Text.rich(TextSpan(
      children: <InlineSpan>[
        for (String text in split)
          text.startsWith('{')
              ? WidgetSpan(child: Blank(text.substring(1, text.length - 1)))
              : TextSpan(text: text),
      ],
    ));
  }
}

Then this

TextWithBlanks(text: "this is a {test} for this {blank} widget")

results in

enter image description here

I took the liberty to modify your Blank and gave the SizedBox a width of 50.

  • Related