Flutter-如何在小部件测试中获取文本小部件 [英] Flutter - how to get Text widget on widget test
问题描述
我正在尝试在Flutter中创建一个简单的小部件测试.我有一个自定义窗口小部件,该窗口小部件接收一些值,组成一个字符串并显示带有该字符串的文本.我必须创建该小部件并且它可以工作,但是在读取Text组件的值以断言所生成的文本正确时遇到了麻烦.
I'm trying to create a simple widget test in Flutter. I have a custom widget that receives some values, composes a string and shows a Text with that string. I got to create the widget and it works, but I'm having trouble reading the value of the Text component to assert that the generated text is correct.
我创建了一个简单的测试来说明问题.我想获取文本值,即文本".我尝试了几种方法,如果我得到查找程序asString(),我可以解释字符串以获取值,但是我认为这不是一个好的解决方案.我想以文本形式读取组件,以便可以访问所有属性.
I created a simple test that illustrates the issue. I want to get the text value, which is "text". I tried several ways, if I get the finder asString() I could interpret the string to get the value, but I don't consider that a good solution. I wanted to read the component as a Text so that I have access to all the properties.
那么,我将如何阅读文本"小部件以访问data属性?
So, how would I read the Text widget so that I can access the data property?
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('my first widget test', (WidgetTester tester) async {
await tester
.pumpWidget(MaterialApp(home: Text("text", key: Key('unit_text'))));
// This works and prints: (Text-[<'unit_text'>]("text"))
var finder = find.byKey(Key("unit_text"));
print(finder.evaluate().first);
// This also works and prints: (Text-[<'unit_text'>]("text"))
var finderByType = find.byType(Text);
print(finderByType.evaluate().first);
// This returns empty
print(finder.first.evaluate().whereType<Text>());
// This throws: type 'StatelessElement' is not a subtype of type 'Text' in type cast
print(finder.first.evaluate().cast<Text>().first);
});
}
推荐答案
我知道了.我必须访问Element的widget属性,然后将其强制转换为文本:
I got it working. I had to access the widget property of the Element, and then cast it as text:
var text = finder.evaluate().single.widget as Text;
print(text.data);
这篇关于Flutter-如何在小部件测试中获取文本小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!