[英]Flutter - how to get Text widget on widget test
I'm trying to create a simple widget test in Flutter.我正在尝试在 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.
我必须创建小部件并且它可以工作,但是我无法读取 Text 组件的值来断言生成的文本是正确的。
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.
我尝试了几种方法,如果我得到 finder asString() 我可以解释字符串以获取值,但我认为这不是一个好的解决方案。 I wanted to read the component as a Text so that I have access to all the properties.
我想将组件作为文本读取,以便我可以访问所有属性。
So, how would I read the Text widget so that I can access the data property?那么,我将如何读取 Text 小部件以便我可以访问 data 属性?
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);
});
}
I got it working.我让它工作了。 I had to access the widget property of the Element, and then cast it as text:
我必须访问 Element 的小部件属性,然后将其转换为文本:
var text = finder.evaluate().single.widget as Text;
print(text.data);
Please check this simple example.请检查这个简单的例子。
testWidgets('Test name', (WidgetTester tester) async {
// findig the widget
var textFind = find.text("text_of_field");
// checking widget present or not
expect(textFind, findsOneWidget);
//getting Text object
Text text = tester.firstWidget(textFind);
// validating properies
expect(text.style.color, Colors.black);
...
...
}
You can use find.text
您可以使用
find.text
https://flutter.io/docs/cookbook/testing/widget/finders#1-find-a-text-widget https://flutter.io/docs/cookbook/testing/widget/finders#1-find-a-text-widget
testWidgets('finds a Text Widget', (WidgetTester tester) async {
// Build an App with a Text Widget that displays the letter 'H'
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Text('H'),
),
));
// Find a Widget that displays the letter 'H'
expect(find.text('H'), findsOneWidget);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.