[英]I want to dynamically replace words with widgets using rich text
我是日本人。 我英語不是很好,所以我提前道歉。 我正在開發一個填空測驗應用程序。 我想用以下小部件替換文本中“{}”包圍的部分,該小部件尚未完成。
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
),
),
);
}
}
我知道我們可以使用一種叫做 RichText 的 WidgetSpan 的東西,但這不是動態的,所以我想知道如何動態地做到這一點。期待您的回音。
你可以嘗試這樣的事情:
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),
],
));
}
}
那么這個
TextWithBlanks(text: "this is a {test} for this {blank} widget")
結果是
我冒昧地修改了你的空白,並給了 SizedBox 50 的寬度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.