如何在Flutter测试中模拟和验证文本选择?

问题描述 投票:0回答:1

我有一个简单的测试应用程序:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: const Center(
          child: SelectionArea(
            child: Text('Selectable text'),
          ),
        ),
      ),
    );
  }
}

我想编写一个测试来验证测试是否可选。我怎样才能做到这一点?

flutter dart selection flutter-text
1个回答
0
投票

这是一个测试,选择文本的前半部分并验证相关渲染段落是否具有正确的选择:

testWidgets('Verify the text can be selected', (WidgetTester tester) async {
  await tester.pumpWidget(
    const MyApp(),
  );

  final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Selectable text'), matching: find.byType(RichText)));
  final Rect paragraphRect = tester.getRect(find.text('Selectable text'));
  final TestGesture gesture = await tester.startGesture(paragraphRect.centerLeft, kind: PointerDeviceKind.mouse);
  addTearDown(gesture.removePointer);
  await tester.pump();

  await gesture.moveTo(paragraphRect.center);
  await tester.pump();
  expect(paragraph1.selections.first, const TextSelection(baseOffset: 0, extentOffset: 7));

  await gesture.up();
});
© www.soinside.com 2019 - 2024. All rights reserved.