假设您需要在运行 Widget UI 测试的 Flutter widget 树中单击以下
TextSpan
斜体文本范围。
用户界面如下所示:
RichText(
key: Key("anyKey"),
textAlign: TextAlign.center,
text: TextSpan(
text: "This is a heading\n",
children: <TextSpan>[
TextSpan(
text: "Text span in bold",
recognizer: TapGestureRecognizer()
..onTap = () {
ref.read(sampleServiceProvider).open(Urls.url1);
},
),
TextSpan(text: " and "),
TextSpan(
text: "Text span in italic",
recognizer: TapGestureRecognizer()
..onTap = () {
ref.read(sampleActionProvider).actionOne();
},
),
],
),
)
如何区分 Flutter 中 RichText 小部件内的
TextSpan
点击?
使用以下代码单击小组件测试中的特定 TextSpan:
RichText richText = ($.widgetByKey(const Key("anyKey")) as RichText);
richText.click("Text span in italic");
具有以下扩展:
/// Enables Widget tests to click on a specific text INSIDE text spans/rich texts
extension TextSpanHelper on RichText {
void click(String innerText) {
text.visitChildren((span) {
if (span.toPlainText() == innerText) {
((span as TextSpan).recognizer as TapGestureRecognizer).onTap?.call();
return false;
}
return true;
});
}
}
T widget<T extends Widget>() => tester.widget(find.byType(T));
Iterable<T> widgetList<T extends Widget>() => tester.widgetList(find.byType(T));
Widget widgetByKey(Key key) => tester.widget(find.byKey(key));
使用