flutterdartselectionflutter-text

How to simulate and verify text selection in Flutter tests?


I have a simple test app:

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'),
          ),
        ),
      ),
    );
  }
}

I would like to write a test that verifies the test is selectable. How can I do that?


Solution

  • Here is a test that selects the first half of the text and verifies the related render paragraph has the correct selection:

    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();
    });