简体   繁体   中英

I want to dynamically replace words with widgets using rich text

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.

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM